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

我只是一个虾纸丫 提交于 2020-01-30 06:28:12

问题


I want to place a button in the upper right corner and have the button be an image. I understand about scoping/garbage-collection etc. and have seen all the other questions asked here that overlook this fact.

However, I have tried numerous methods including creating a self.photo and declaring photo as a global variable. I'm actually not even convinced that that's the issue, because I declare the photo in the same scope as I call the mainloop().

My code right now (which is mostly borrowed from Drag window when using overrideredirect since I'm not really familiar with 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()

回答1:


I typically give PhotoImages a name and use the name in image parameters:

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

I'm not sure if this is the only way, but this works here.




回答2:


The correct way to create the photoimage is by passing the path to the file parameter. Otherwise, your path gets assigned to the internal image name and thus no file will be associated with the image.

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


来源:https://stackoverflow.com/questions/54368569/tkinter-image-wont-show-up-on-button-despite-keeping-global-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!