I have 2 canvas rectangles, which have a binding for Button-1. Sometimes I want that when one rectangle gets this event, then the other rectangle should also get this event. So I have to duplicate the Button-1 event by the widget method "event_generate".
My example code is kind of minimal, so you can only press once the left mouse button. When you press the left mouse button over the red rectangle, this event is recognized, which is proved by the message "button1 red " showing up. Because I have added a second binding to each of the rectangles, also the method "create_event_for_rectangle" is started, which is proved by the message "Create event for other rectangle" showing up. This method also generates a new Button-1 event at the green rectangle. The coordinates of the generated event seem to be correct, as additionally a small rectangle is created at the calculated coordinates. This generated event at the the green rectangle now should create the message "button1 green 45 45", but nothing happens.
This is my code:
import tkinter as tk
class rectangle():
def __init__(self, factor, color):
self.canvas_id=canvas.create_rectangle(factor*10,factor*10,
(factor+1)*10,(factor+1)*10,fill=color)
canvas.tag_bind(self.canvas_id, "<Button-1>", self.button1)
self.color = color
def button1(self, event):
print("button1", self.color, event.x, event.y)
def get_canvas_id(self):
return self.canvas_id
def get_center(self):
coords = canvas.coords(self.canvas_id)
return (coords[0]+coords[2])/2, (coords[1]+coords[3])/2
def create_event_for_rectangle(not_clicked):
print("Create event for other rectangle")
canvas.tag_unbind(red.get_canvas_id() , "<Button-1>", func_id_red)
canvas.tag_unbind(green.get_canvas_id(), "<Button-1>", func_id_green)
not_clicked_center_x, not_clicked_center_y = not_clicked.get_center()
canvas.event_generate("<Button-1>",
x=not_clicked_center_x, y=not_clicked_center_y)
canvas.create_rectangle(not_clicked_center_x-1, not_clicked_center_y-1,
not_clicked_center_x+1, not_clicked_center_y+1)
root = tk.Tk()
canvas = tk.Canvas(width=100, height=100)
canvas.grid()
red = rectangle(1, "red" )
green = rectangle(4, "green")
func_id_red = canvas.tag_bind(red.get_canvas_id() , "<Button-1>",
lambda event: create_event_for_rectangle(green), add="+multi")
func_id_green = canvas.tag_bind(green.get_canvas_id(), "<Button-1>",
lambda event: create_event_for_rectangle(red ), add="+multi")
root.mainloop()
What am I doing wrong?