tkinter按钮不显示图像

用户名

嗨,我正在尝试将图像作为背景放在我的一个按钮上,我已经在主窗口中的许多其他按钮上完成了此操作,但是此特定按钮位于顶层窗口内,图像不会像这样加载应该,有人知道为什么吗?(我也尝试过定义按钮的宽度和高度,但这仍然不显示图像)

def rec_window():
    recw = Toplevel(width=500,height=500)
    recw.title('Record To.....')
    img1 = PhotoImage(file="C:/Users/Josh Bailey/Desktop/pi_dmx/Gif/mainmenu.gif")
    Button(recw, image=img1, command=rec_preset_1).grid(row=1, column=1)
    Button(recw, text="Preset 2", bg = 'grey70',width=40, height=12,command=rec_preset_2).grid(row=1, column=2)
    Button(recw, text="Preset 3", bg = 'grey70',width=40, height=12,command=rec_preset_3).grid(row=2, column=1)
    Button(recw, text="Preset 4", bg = 'grey70',width=40, height=12,command=rec_preset_4).grid(row=2, column=2)
    Button(recw, text="Cancel", bg='grey70', width=20, height=6, command=recw.destroy). grid(row=3,column=1,columnspan=2, pady=30)
地图学家

根据程序其余部分的结构,图像可能会被垃圾回收清除:

来自http://effbot.org/tkinterbook/photoimage.htm

注意:当PhotoImage对象被Python垃圾收集时(例如,当您从将图像存储在局部变量中的函数返回时),即使Tkinter小部件正在显示该图像,也会清除该图像。

为了避免这种情况,程序必须保留对图像对象的额外引用。一种简单的方法是将图像分配给小部件属性,如下所示:

label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()

在您的情况下,可以通过将img1声明为全局变量来保留引用来启动函数:

global img1

或者,如果您的程序中其他地方已经有img1:

img1 = PhotoImage(file="C:/Users/Josh Bailey/Desktop/pi_dmx/Gif/mainmenu.gif")
img1Btn = Button(recw, image=img1, command=rec_preset_1)
img1Btn.image = img1
img1Btn.grid(row=1, column=1)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章