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

Tkinter弹出子窗口按钮添加图片后按钮消失问题求解

问题根源
  • Tkinter的图片对象PhotoImage不会被控件自动持有引用,如果你在函数内部创建图片对象赋值给局部变量,函数运行结束后局部变量会被垃圾回收,图片被销毁后绑定的按钮就会消失
  • 弹出子窗口不应该使用Tk()实例,应该用专门的子窗口类Toplevel(),多主窗口实例会导致资源管理异常,也会触发图片加载失效的问题
修正方案

首先将新窗口创建逻辑替换为Toplevel(),其次给每个子窗口按钮的图片手动绑定到按钮实例的属性上,保留引用避免被回收。

完整可运行代码
from tkinter import *

root = Tk()
root.title('GARBIL.TK')

p1 = PhotoImage(file='03.png')
root.iconphoto(False, p1)

canvas_width = 1900
canvas_height = 1080

w = Canvas(root, width=canvas_width, height=canvas_height)
w.pack()

serveron = PhotoImage(file="01.PNG")
serveroff = PhotoImage(file="02.PNG")

def SGX():
    # 替换Tk为Toplevel创建子窗口
    SGX_win = Toplevel(root)
    SGX_win.title('server map')
    SGX_win.geometry("900x700")
    # 创建按钮并绑定图片,也可以直接复用全局的serveroff变量
    sgx21_img = PhotoImage(file="02.PNG")
    SGX21 = Button(SGX_win, text='SGX.21', image=sgx21_img, bg='#008080', fg='#ffffff', compound=BOTTOM)
    # 手动保留图片引用,避免被垃圾回收
    SGX21.img = sgx21_img
    SGX21.place(x=200, y=250)

SGXon = Button(root, text=' SGX ', image=serveron, command=SGX, compound=BOTTOM)
SGXon.place(x=1080, y=100)

mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:57:03