Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual event multiple binding not working as expected

Tags:

events

tkinter

Here's a simplified version of my code:

from tkinter import *
class MyCustomWidget(Canvas):

    def __init__(self, parent = None, **options):
        Canvas.__init__(self, parent, options)
        self.box = self.create_rectangle(0, 0, 300, 300,fill="blue")
        self.bind('<Button-1>', self.on_clicked)
        self.tag_bind(self.box, '<B1-Motion>', self.on_clicked)  

    def on_clicked(self, event):
        print( "inner method called")

#now outside this class:
def my_callback(event=None):
    print ("outer method called")

root = Tk()
my_widget = MyCustomWidget()
my_widget.event_add('<<my_event>>', '<B1-Motion>', '<Button-1>')
my_widget.bind('<<my_event>>', my_callback)
my_widget.pack()
root.mainloop()

When I run this code and move my mouse (B1-Motion) over the blue box,It calls both the inner and outer method, so I get the following output:

inner method called
outer method called

But when I single click on the blue box (Button-1) it only calls the inner method and the output is:

inner method called

I was expecting both the methods to be called in either cases. Any explanation on why this should behave this way ?

like image 770
bhaskarc Avatar asked Mar 26 '26 22:03

bhaskarc


1 Answers

Tkinter won't call two callbacks for the same event. From the official tk documentation:

If more than one binding matches a particular event and they have the same tag, then the most specific binding is chosen and its script is evaluated. The following tests are applied, in order, to determine which of several matching sequences is more specific:

a) an event pattern that specifies a specific button or key is more specific than one that does not;

(b) a longer sequence (in terms of number of events matched) is more specific than a shorter sequence;

(c) if the modifiers specified in one pattern are a subset of the modifiers in another pattern, then the pattern with more modifiers is more specific.

(d) a virtual event whose physical pattern matches the sequence is less specific than the same physical pattern that is not associated with a virtual event.

(e) given a sequence that matches two or more virtual events, one of the virtual events will be chosen, but the order is undefined.

When you click the mouse button, you have more than one binding that matches -- the binding on <<my_event>> and the binding on <1>. The binding for <1> is more specific than the binding on <<my_event>>, so that is the one that is chosen.

like image 97
Bryan Oakley Avatar answered Apr 01 '26 09:04

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!