Tkinter测验应用点击按钮无法切换图片问题求解
问题根源
- 现有代码中两个图片Label
panel和panel2调用pack()时仅做新增展示,没有隐藏已显示的另一个图片Label,后添加的组件会排在先添加的组件下方,窗口高度不足时就会被遮挡,看起来就像点击按钮无响应 - 就算窗口高度足够,也只会出现两张图片同时展示的情况,不符合预期的切换效果
修复方案
推荐只用1个共用的图片Label,点击按钮时直接修改Label的图片属性即可,逻辑更简洁:
# 预加载两张图片,保留全局引用避免被Tkinter垃圾回收导致图片空白 img = PhotoImage(file="unknown.png") img1 = PhotoImage(file="11232.png") # 仅创建一个共用的图片展示Label img_panel = Label(master) def OpenPic(): # 切换Label展示的图片 img_panel.config(image=img) # 把图片引用绑定到Label属性上,避免被回收 img_panel.image = img img_panel.pack(side = "bottom", fill="both") def OpenPic2(): img_panel.config(image=img1) img_panel.image = img1 img_panel.pack(side = "bottom", fill="both")
如果要保留原有双Label的写法,每次展示前隐藏另一个Label即可:
def OpenPic(): # 先隐藏另一张图片 panel2.pack_forget() panel.pack(side = "bottom", fill="both") def OpenPic2(): # 先隐藏另一张图片 panel.pack_forget() panel2.pack(side = "bottom", fill="both")
内容的提问来源于stack exchange,提问作者candy
相关产品推荐
相关产品推荐

