Tkinter can't display image on button

Question:

I’m trying to program a minesweeper game in tkinter and so far everything went smoothly, but somehow I can’t have an Image. I start with an image, I can configure any other parameter.
I have a reference since I have it as attributes to the class

class Tile:
    def __init__(self, x: int, y: int, bomb: bool, mainframe: ttk.Frame) -> None:
        self.pos_x = x
        self.pos_y = y
        self.marked = False
        self.bomb = bomb
        self.mainframe = mainframe

        self.image = PhotoImage()
        self.blank_image = PhotoImage()
        self.flag_image = PhotoImage("Flag.png", width=30, height=30)
        self.bomb_image = "test"

        self.tile = tkinter.Button(self.mainframe, height=30, width=30, image=self.blank_image)
        self.tile.grid(row=self.pos_y, column=self.pos_x)
        self.tile.bind('<Button-1>', self.open)
        self.tile.bind('<Button-3>', self.right)
    
    def open(self, tmp):
        print(f"open {self.pos_x} {self.pos_y}")
        self.tile.config(bg="grey")

    def mark(self):
        self.marked = True
        print("mark")
        self.tile.config(image=self.flag_image)
        
    def unmark(self):
        self.marked = False
        print("mark")
        self.tile.config(image=self.blank_image)

    def right(self, tmp):
        if self.marked:
            self.unmark()
        else:
            self.mark()

The open method works fine, so changing the color works.. I also get the output in my terminal, so the mark and unmark methods are called.

Asked By: Liam K.

||

Answers:

You aren’t creating the image properly. The first positional argument is a name for the image, not the file. The filename needs to be assigned to the file option.

Change this:

self.flag_image = PhotoImage("Flag.png", width=30, height=30)

To this:

self.flag_image = PhotoImage(file="Flag.png", width=30, height=30)
Answered By: Bryan Oakley
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.