Tkinter - 尽管保留了全局参考,但图像不会显示在按钮上

Tkinter - Image won't show up on button despite keeping global reference

我想在右上角放置一个按钮,并且按钮是一个图像。我了解 scoping/garbage-collection 等,并且已经看到此处提出的所有其他问题都忽略了这一事实。

但是,我尝试了很多方法,包括创建 self.photo 和将 photo 声明为全局变量。实际上,我什至不相信这就是问题所在,因为我在调用 mainloop().

的相同范围内声明了照片

我现在的代码(大部分是从 Drag window when using overrideredirect 借来的,因为我对 tkinter 不是很熟悉):

import tkinter

pink="#DA02A7"
cyan="#02DAD8"
blue="#028BDA"

class Win(tkinter.Tk):

    def __init__(self,master=None):
        tkinter.Tk.__init__(self,master)
        self.overrideredirect(True)
        self._offsetx = 0
        self._offsety = 0
        self.bind('<Button-1>',self.clickwin)
        self.bind('<B1-Motion>',self.dragwin)
        self.geometry("500x500")

    def dragwin(self,event):
        x = self.winfo_pointerx() - self._offsetx
        y = self.winfo_pointery() - self._offsety
        self.geometry('+{x}+{y}'.format(x=x,y=y))

    def clickwin(self,event):
        self._offsetx = event.x
        self._offsety = event.y

win = Win()

# put a close button
close_button = tkinter.Button(win, bd=0, command=win.destroy)
global photo
photo=tkinter.PhotoImage("close.gif")
close_button.config(image=photo, height="10", width="10")

# pack the widgets
close_button.pack(anchor=tkinter.NE)

win.configure(bg=pink)

win.mainloop()

我通常给 PhotoImage 一个名字,然后在 image 参数中使用这个名字:

photo=tkinter.PhotoImage(name='close', file="close.gif")
close_button.config(image='close')

我不确定这是否是唯一的方法,但这在这里行得通。

创建照片图像的正确方法是将路径传递给 file 参数。否则,您的路径将分配给内部图像名称,因此不会有文件与图像相关联。

photo=tkinter.PhotoImage(file="close.gif")