I want to draw a circle on top of a button centered at its center when I click it. I tried to add a canvas to do so but when I try to pack it in init to the root then I get an error that i'm tring to use geometry and grid at the same time.
If I don't pack it to the root then when I click a button nothing happens.
thanks
from tkinter import *
class Game:
def __init__(self, root, size):
self.root = root
self.size = size
self.turn = "red"
self.board = self.init_board()
self.current_turn_label = None
self.load_button = None
self.save_button = None
self.init_head()
self.canvas = Canvas(root)
# self.canvas.pack() # ERROR
def init_board(self):
board = [[0] * self.size for _ in range(self.size)]
for row in range(self.size):
for col in range(self.size):
board[row][col] = Button(width=5, height=2, bg='white',
command= lambda r=row, c=col: self.handle_click(r,c))
board[row][col].grid(row=row+1, column=col)
return board
def handle_click(self, r, c):
print(f"inside click, r: {r} c: {c}")
button = self.board[r][c]
x, y = self.location(r, c)
# draw circle at center of button of color self.turn
self.canvas.create_oval(x, y, x + button.winfo_width(), y + button.winfo_height(), fill=self.turn)
# nothing happens
def load_game(self):
print("inside load game")
def save_game(self):
print("inside save game")
def location(self, r, c):
button = self.board[r][c]
x, y = button.winfo_x(), button.winfo_y()
return x, y
def init_head(self):
self.current_turn_label = Label(text=f"turn: {self.turn}")
self.current_turn_label.grid(row=0, column=0, columnspan=3)
self.load_button = Button(text="Load", command=self.load_game)
self.load_button.grid(row=0, column=3)
self.save_button = Button(text="Save", command=self.save_game)
self.save_button.grid(row=0, column=4)
root = Tk()
game = Game(root, 5)
mainloop()