gpt4 book ai didi

events - 虚拟事件多重绑定(bind)未按预期工作

转载 作者:行者123 更新时间:2023-12-02 01:34:56 24 4
gpt4 key购买 nike

这是我的代码的简化版本:

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()

当我运行这段代码并将鼠标 (B1-Motion) 移到蓝色框上时,它同时调用了内部和外部方法,所以我得到以下输出:

inner method called
outer method called

但是当我单击蓝色框 (Button-1) 时,它只调用内部方法,输出是:

inner method called

我期望这两种方法在任何一种情况下都能被调用。关于为什么这应该以这种方式表现的任何解释?

最佳答案

Tkinter 不会为同一事件调用两个回调。来自官方 tk 文档:

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.

当您单击鼠标按钮时,您有多个匹配的绑定(bind) -- <<my_event>> 上的绑定(bind)和 <1> 上的绑定(bind). <1> 的绑定(bind)比 <<my_event>> 上的绑定(bind)更具体, 所以这就是被选中的那个。

关于events - 虚拟事件多重绑定(bind)未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31810669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com