You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter代码正常时不显示图片,报错时却能显示的问题求助

问题分析与修复方案

核心原因

你碰到的是Tkinter的垃圾回收陷阱:uploadImg函数里的img是局部变量,函数执行完后,Python会自动回收这个变量的内存,导致Label关联的图片对象被销毁,所以窗口里看不到图片。

而加func()这类错误代码时,函数执行到错误行就会抛出异常,函数没有正常结束,局部变量img不会被立即回收,图片就能暂时显示出来。

修复方法

有两种常用的解决方式:

方法一:将img设为全局变量

修改uploadImg函数,声明img为全局变量,让它在函数结束后依然存在:

from tkinter import *
from tkinter.filedialog import askopenfile

def uploadImg():
    global img  # 声明为全局变量
    f = askopenfile(filetypes=[('PNG','*.png'),("JPG",'.jpg'),('JPEG','*.jpeg')])
    img = PhotoImage(file=f.name)
    l.config(image=img,width=img.width(),height=img.height())
    btn.place_forget()

root = Tk()
root.config(
    padx=50,
    pady=50
)
l = Label(master=root,width=100,height=20,borderwidth=1,relief='solid')
l.pack()

btn = Button(master=root,text='Choose A File',command=uploadImg)
btn.place(x=320,y=160)
root.mainloop()

方法二:把img绑定到Label对象的属性上

通过给Label添加属性保存图片对象,避免被垃圾回收:

from tkinter import *
from tkinter.filedialog import askopenfile

def uploadImg():
    f = askopenfile(filetypes=[('PNG','*.png'),("JPG",'.jpg'),('JPEG','*.jpeg')])
    img = PhotoImage(file=f.name)
    l.img = img  # 绑定到Label的属性上
    l.config(image=img,width=img.width(),height=img.height())
    btn.place_forget()

root = Tk()
root.config(
    padx=50,
    pady=50
)
l = Label(master=root,width=100,height=20,borderwidth=1,relief='solid')
l.pack()

btn = Button(master=root,text='Choose A File',command=uploadImg)
btn.place(x=320,y=160)
root.mainloop()

补充说明

这个问题和设备无关,是Tkinter使用时的常见坑,只要保证图片对象有全局引用或者被某个已存在的组件对象引用,就能避免被垃圾回收,图片就能正常显示。

内容的提问来源于stack exchange,提问作者Sarim09

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 15:24:07