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

Tkinter按钮触发函数显示图片失败:仅显示空Label问题求助

解决Tkinter点击按钮显示图片为空的问题

你的代码里有两个关键问题导致图片无法正常显示:

  1. PhotoImage对象被垃圾回收
    在addCards()函数中,imgTest是局部变量,函数执行完后Python会自动回收这个对象,Label组件也就失去了图片引用,只能显示空框。解决办法是把图片对象绑定到Label的属性上,让它和Label一起存在,避免被回收。

  2. 文件路径的转义错误
    Windows路径里的单反斜杠\会被Python识别为转义字符,比如\p会被解析成特殊字符,导致图片路径无效。可以把路径改成正斜杠/或者双反斜杠\\。

修改后的完整代码:

import tkinter as tk
from PIL import ImageTk, Image

def addCards():
    # 修复路径:用正斜杠或者双反斜杠
    img = Image.open("widgetClass/poker2.png")
    img = img.resize((50, 70), Image.ADAPTIVE)
    imgTest = ImageTk.PhotoImage(img)

    cards = tk.Label(
        master=frame,
        image=imgTest
    )
    # 绑定图片引用到Label,防止被垃圾回收
    cards.image = imgTest
    cards.place(x=20, y=50)

root = tk.Tk()
root.title("Display images")
root.geometry("400x400")
root.resizable(False, False)

frame = tk.Frame(borderwidth=2, height=100, highlightbackground="red", highlightthickness=2)
frame_b = tk.Frame(borderwidth=2, height=100, highlightbackground="red", highlightthickness=2)

label = tk.Label(frame, text="Picture demo")
button = tk.Button(frame_b, text="Add cards", command=addCards)

frame.pack(fill=X)
frame_b.pack(fill=X)
label.place(x=0, y=0)
button.place(x=0, y=0)

root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 07:07:15