Python Forum

Full Version: Clickable Rectangles Tkinter Canvas
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello there.

I am attempting to bind the left mouse button to a grid of tkinter rectangles. I am trying to execute function clicked() when someone clock on a tkitner rectangle. I am looping their creation to create a grid. However, when I click the rectangle, the code is not executed.

Grid Creation Loop:
for x in range(0, wid, 60):
    for y in range(0, leng, 60):
        rectangle = drawCanv.create_rectangle(x, y, x+60, y+60, outline='black')  
        drawCanv.tag_bind("rectangle","<Button-1>",lambda: clicked)
Function (just testing. will replace with other code):
def clicked():
    print("You Clicked Me")
Is this what you are looking for?

from tkinter import *

def clicked (event) :
	print (f'You clicked at {event.x} X {event.y}.')

root = Tk ()
drawCanv = Canvas (width = 541, height = 301, bd = 0)
drawCanv.bind ('<Button>', clicked)

for x in range (1, 540, 60) :
	for y in range (1, 300, 60) :
		rectangle = drawCanv.create_rectangle (x, y, x + 60, y + 60,\
			outline = 'black')  
drawCanv.pack ()

mainloop ()
I need the rectangles to act as buttons. I need to bind the key press directly to the RECTANGLE, not the canvas.
As far as I know, you will have to manually check if the mouse in inside of one of the boxes when it is clicked. See if this helps.

from tkinter import *

def clicked (event) :
	button_number = (int (event.y / 60) * 9) + (1 + int (event.x / 60))
	print (f'You clicked button number {button_number}.')

root = Tk ()
drawCanv = Canvas (width = 541, height = 301, bd = 0)
drawCanv.bind ('<Button-1>', clicked)

button_number = 1
for y in range (1, 300, 60) :
	for x in range (1, 540, 60) :
		rectangle = drawCanv.create_rectangle (x, y, x + 60, y + 60,\
			outline = 'black')  
		drawCanv.create_text (x + 25, y + 30, text = button_number)
		button_number += 1
drawCanv.pack ()

mainloop ()
Alternately you can use real button configured to look like your little squares.

from tkinter import *

button_list = ['dummy']
class button_box :
	def __init__ (self, button, ID_number) :
		self.ID_number = ID_number
		self.button = button

	def clicked (self, event) :
		print (f'You pressed button number {self.ID_number}')

root = Tk ()

button_number = 1
for y in range (5) :
	for x in range (9) :
		button = Button (width = 5, height = 3, text = button_number)
		button.config (relief = 'solid', borderwidth = 1)
		button.grid (row = y, column = x)
		button_list.append (button_box (button, button_number))
		button.bind ('<Button-1>', button_list[button_number].clicked)
		button_number += 1

mainloop ()
Yes. I can very easily incorporate this with my existing code.
Thanks