Tkinter Key Binding in Different Regions of Window Tkinter Key Binding in Different Regions of Window tkinter tkinter

Tkinter Key Binding in Different Regions of Window


When function x1 is called in response to a mouse click, the event object has the mouse click x and y co-ordinates (event.x and event.y). Use those to detect which part of the canvas was clicked on and act accordingly.


Here is how you can use the event co-ordinates to identify which square of the tic-tac-toe board the user clicked on:

from tkinter import *# Creates Windowtk = Tk()width = 600third = width / 3canvas = Canvas(tk, width=width, height=width)tk.title('Tic Tac Toe')canvas.pack# Creates Boardcanvas.create_line(third, 0, third, width)canvas.create_line(third*2, 0, third*2, width)canvas.create_line(0, third, width, third)canvas.create_line(0, third*2, width, third*2)def draw_cross(row,col):    canvas.create_line(col * third, row * third, (col + 1) * third, (row + 1) * third)    canvas.create_line((col + 1) * third, row * third, col * third, (row + 1) * third)def mouse_click(event):    col = int(event.x / third)    row = int(event.y / third)    draw_cross(row,col)canvas.pack()canvas.bind("<Button-1>", mouse_click)canvas.mainloop()

First of all I parametrized the board dimensions using variables width and third - just change width, and everything will resize correctly.

Second, clicking a mouse button on the canvas calls the mouse_click event handler, which obtains the co-ordinates of the point in the canvas on which the mouse was clicked (event.x and event.y), and computes the corresponding row (0, 1 or 2) and column (0, 1 or 2) of the square on the tic-tac-tow board. These are then passed as parameters to the function draw_cross which draws the two diagonals for that square.

Hope that helps.