I am using tkinter to make a simple drawing tool. I am trying to put an image, fill_bucket.png
, on the button. However, when I run the program, the button is incredibly small, like it has no content, and there is not image.
From looking around, it seems like the issue is probably Python's garbage collection, however I have tried many ways of fixing this and nothing seems to work. The simplest thing I have tried is:
self.fill_bucket_photo = PhotoImage(file='./img/fill_bucket.png')
self.fillButton = Button(self.button_layout, image=self.fill_bucket_photo, compound='top', font=('Arial', 25), width=1, height=1, command=lambda: self.selectTool('fill'))
However this does not work. I have also tried this solution, which I found here:
label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
However when I do self.fillButton.image
after assigning self.fillButton
, I get an Attribute error for the image
attribute.
Everything that I am doing is inside a class, and I can define normal buttons with text fine.
Additionally, doing
self.fill_bucket_photo = PhotoImage(file='./img/fill_bucket.png')
self.label = Label(image=self.fill_bucket_photo).grid(row=1, column=1)
shows the image normally.
Full example. On my computer, this code creates a window that contains one blank button with no image on it:
from tkinter import *
class App():
def __init__(self):
self.root = Tk()
self.root.resizable(False, False)
self.fill_bucket_photo = PhotoImage(file='./img/fill_bucket.png')
self.fillButton = Button(self.root, image=self.fill_bucket_photo, compound='top', font=('Arial', 25), width=40, height=40).pack()
self.root.mainloop()
app = App()
What are some possible solutions to this?