WarBro
WarBro

Reputation: 303

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

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()

Upvotes: 2

Views: 316

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 385980

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")

Upvotes: 2

mkiever
mkiever

Reputation: 891

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.

Upvotes: 1

Related Questions