2

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()
Miraj50
  • 4,257
  • 1
  • 21
  • 34
WarBro
  • 305
  • 2
  • 10
  • `global photo` is useless here btw. `global` is only necessary if you want to write a global variable inside a function. – mkiever Jan 25 '19 at 16:08

2 Answers2

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")
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Ug, I had this and it still wasn't working but I had been doing something else wrong and somehow when I changed the other thing I lost the `file=`?? I feel dumb.... XD – WarBro Jan 25 '19 at 16:03
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.

mkiever
  • 894
  • 5
  • 13
  • The name isn't necessary (though there's nothing wrong with using it). The fix is to make sure the path is given to the `file` parameter. – Bryan Oakley Jan 25 '19 at 16:02
  • @BryanOakley RIght, just tried it. Just a habitude of mine doing it with image names. – mkiever Jan 25 '19 at 16:04