import tkinter as tk from random import shuffle class MyButton(tk.Button): def __init__(self, master,x,y,num,*args,**kwargs): super().__init__(master,*args,**kwargs, width=3, font='Calibri 15 bold') self.x = x self.y = y self.num = num self.is_mine = False def __repr__(self): return f"MyButton: {self.x} {self.y}; {self.num} {self.is_mine}" class MineSweeper: app = tk.Tk() ROW = 16 COLUMNS = 16 MINES = round(ROW*COLUMNS*0.2) def __init__(self): self.buttons = [] count = 1 for i in range(MineSweeper.ROW): temp = [] for j in range(MineSweeper.COLUMNS): btn = MyButton(MineSweeper.app,x=i,y=j,num=count) btn.config(command=lambda button = btn:self.click(button)) temp.append(btn) count +=1 self.buttons.append(temp) def click(self,clicked_button:MyButton): if clicked_button.is_mine: img = tk.PhotoImage(file="unnamed.png") clicked_button.config(image=img) else: clicked_button.config(text=clicked_button.num) def create_widgets(self): for i in range(MineSweeper.ROW): for j in range(MineSweeper.COLUMNS): btn = self.buttons[i][j] btn.grid(row=i, column=j) def print_buttons(self): for btn in self.buttons: print(btn) def start(self): self.create_widgets() self.insert_mines() self.print_buttons() MineSweeper.app.mainloop() @staticmethod def get_mines_places(): indexes = list(range(1,MineSweeper.ROW*MineSweeper.COLUMNS+1)) shuffle(indexes) return indexes[:MineSweeper.MINES] def insert_mines(self): index_mines = self.get_mines_places() print(index_mines) for row_btn in self.buttons: for btn in row_btn: if btn.num in index_mines: btn.is_mine = True def get_button_size(self): first_button = self.buttons[0][0] first_button.update_idletasks() # Обновляем геометрию button_width = first_button.winfo_width() button_height = first_button.winfo_height() print(f"Размер кнопки: {button_width}x{button_height}") game = MineSweeper() print(game.MINES) game.create_widgets() game.get_button_size() # В game.start()
Проблема в том, что в методе click вы используете this, который в данном случае является объектом, а не контекстом. Поэтому вам нужно передавать в метод click контекст, например, через конст