I started coding a little ago and already there is a bug I can't figure out. I'm trying to make a Minesweeper-like program. My issue is that when I try to get a cell to display the picture of a flag, a mine or any other image (not number or letters, that I could manage very well), the grid just breaks.
Here is a very condensed part of my code to show my issue :
from tkinter import *
from functools import partial as part
from PIL import Image, ImageTk
class Grid:
def __init__(self, master):
self.master = master
self.images, self.frames, self.grid = [], [], []
self.images = {
"mine": ImageTk.PhotoImage(image=Image.open("Sprites/mine.png").resize((20, 20))),
"flag": ImageTk.PhotoImage(image=Image.open("Sprites/flag.png").resize((20, 20))),
"ghost_flag": ImageTk.PhotoImage(image=Image.open("Sprites/ghost_flag.png").resize((20, 20)))}
self.draw_grid()
def _on_click(self, event, x, y, *args):
if event == "left-click":
self.grid[x][y]["widget"]["image"] = self.images["mine"]
if event == "right-click":
self.grid[x][y]["widget"]["image"] = self.images["flag"]
def draw_grid(self):
for x in range(0, 9):
self.frames.append(Frame(self.master))
self.frames[len(self.frames) - 1].pack(side="top")
self.grid.append([])
for y in range(0, 9):
self.grid[x].append({"widget": Label(self.frames[x], bg="#888888", width=4, height=2, image=None)})
self.grid[x][y]["widget"].pack(fill=BOTH, expand=1, side="left", padx=1, pady=1)
self.grid[x][y]["widget"].bind("<Button-1>", part(self._on_click, "left-click", x, y))
self.grid[x][y]["widget"].bind("<Button-2>", part(self._on_click, "right-click", x, y))
self.grid[x][y]["widget"].bind("<Button-3>", part(self._on_click, "right-click", x, y))
root = Tk()
grid = Grid(root)
root.mainloop()
I obviously got rid of any Minesweeper core code, and the program only places mines on left clicks and flags on right clicks. The two only parts of the code that lock a size in are the .resize(x, y)
function and the width
and height
arguments in the Label creation.
The result is something like that :
Hope someone can help me,
Have a good day
Edit: Also, if someone knows how to .bind
more efficiently, I would be delighted.
Edit 2: After a little bit of thinking, I realised there is a dumb solution, which is to do something like :
self.grid[x][y]["widget"]["width"] = 92
But I would appreciate a cleaner solution.