Reputation: 100
I am trying to make a Tic Tac Toe program for 2 players, and so I need to be able to have mouse clicks in certain areas of the window do different things. How do I do that? This is what I have so far.
from tkinter import *
# Creates Window
tk = Tk()
canvas = Canvas(tk, width=600, height=600)
tk.title('Tic Tac Toe')
canvas.pack
# Creates Board
line1 = canvas.create_line(200, 0, 200, 600)
line2 = canvas.create_line(400, 0, 400, 600)
line3 = canvas.create_line(0, 200, 600, 200)
line4 = canvas.create_line(0, 400, 600, 400)
# Creates Functions for Xs being placed on board
def x1(event):
canvas.create_line(0, 0, 200, 200)
canvas.create_line(200, 0, 0, 200)
def x2(event):
canvas.create_line(200, 0, 400, 200)
canvas.create_line(400, 0, 200, 200)
# Creates the buttons to put the Xs on the board when clicked DOESN'T WORK
canvas.pack()
canvas.bind("<Button-1>", x1)
canvas.mainloop()
Sorry if I formatted the code wrong. The second to last line is the line I am having trouble with. I want button-1 (mouse click) to be able to do x1 and x2 (and eventually other functions) depending on the region of the window it is on. Please help.
Upvotes: 1
Views: 244
Reputation: 1557
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 Window
tk = Tk()
width = 600
third = width / 3
canvas = Canvas(tk, width=width, height=width)
tk.title('Tic Tac Toe')
canvas.pack
# Creates Board
canvas.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.
Upvotes: 1
Reputation: 1557
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.
Upvotes: 0