且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

tkinter按钮不显示图像

更新时间:2023-02-22 15:41:15

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

Depending on how the rest of your program is structured, your image might be getting cleared by garbage-collection:

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

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

Note: When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.

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

To avoid this, the program must keep an extra reference to the image object. A simple way to do this is to assign the image to a widget attribute, like this:

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

对于您来说,可以通过将img1声明为全局变量来保留引用来启动函数:

In your case, you can start your function by declaring img1 as a global variable to retain a reference:

global img1

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

or, if you already have img1 elsewhere in your program:

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)