我想在右上角放置一个按钮,并使该按钮成为图像。我了解范围界定/垃圾收集等方面的知识,并且看到这里提出的所有其他问题都忽略了这一事实。
但是,我尝试了许多方法,包括创建self.photo
和将图片声明为全局变量。实际上,我什至都不认为这是问题所在,因为我在与称为mainloop()
的范围内声明了照片。
我现在的代码(由于我对tkinter不太熟悉,所以我的代码大多是从Drag window when using overrideredirect借来的):
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()
答案 0 :(得分:2)
创建照片图像的正确方法是将路径传递到file
参数。否则,您的路径将分配给内部图像名称,因此该图像将不会与任何文件关联。
photo=tkinter.PhotoImage(file="close.gif")
答案 1 :(得分:1)
我通常给PhotoImage
命名,并在image
参数中使用该名称:
photo=tkinter.PhotoImage(name='close', file="close.gif")
close_button.config(image='close')
我不确定这是否是唯一的方法,但这在这里有效。