Reputation: 99
I am in the process of porting a game that I wrote into a user friendly GUI. Please bear with me, as it is my first time playing around with tkinter.
Once the player inputs how many rows/columns he would like to play with, we draw up the gameboard.
If you look at the following code, you see that I assign tags to each square that we create, in the format of 'row, col'
I called .tag_bind to the square located in row 0, column 3. When clicked, it should call the _on_canvas_clicked function. However, when I run the program, it doesn't respond or do anything when I click that square.
gameframe = tkinter.Frame(master = self._dialog_window)
gameframe.grid(row = 2, column = 0, columnspan = 2, padx = 10, pady = 10, sticky = tkinter.W)
boardWidth = cols * self._sqheight
boardHeight = rows * self._sqheight
self.gameboard = Canvas(gameframe, width = boardWidth, height = boardHeight, bg = 'green')
self.gameboard.grid(row = 0, column = 0)
for row in range(rows):
for col in range(cols):
top = row * self._sqheight
left = col * self._sqheight
bottom = row * self._sqheight + self._sqheight -1
right = col * self._sqheight + self._sqheight -1
rect = self.gameboard.create_rectangle(left,top,right,bottom,outline='gray',fill='',tags="(row, col)")
self.gameboard.itemconfig(rect, tags='{},{}'.format(row, col))
self.gameboard.tag_bind('0,3', '<ButtonPress-1>', self._on_canvas_clicked)
self.gameboard.bind('<Button-1>', self._on_canvas_clicked)
works as intended. But tag_bind does not. I made sure (I think...) that the tags were properly being assigned.
Anyone care to help me out? Thanks in advance.
Upvotes: 0
Views: 123
Reputation: 385900
When you bind to a rectangle, the event fires when you click on one of the pixels that belongs to a rectangle. Since you're using fill=""
, the interior of the rectangle has no pixels. Your code actually works if you position your mouse over the border.
You should give your rectangles a fill color if you want to be able to click on them. Or, you can add one binding to a canvas and then use the canvas's ability to find the object(s) nearest the click.
Also, you need to move the tag_bind
inside the loop if your intention is to add the binding for each rectangle.
Upvotes: 1