Skip to main content
 首页 » 编程设计

python之在 Tkinter 运动期间避免事件抓取

2024年10月25日10xiaohuochai

在 Tkinter 中是否可以避免当您在小部件上按下鼠标按钮并在移动鼠标时按住它时发生的事件抓取?

我想注册鼠标按钮,然后跟踪用户在按下按钮时移动鼠标时输入的所有小部件。当用户释放鼠标按钮时,应用程序对所有跟踪的小部件执行相同的操作。

下面的代码应该可以解释我想做什么。

# Set a tracking flag 
widget.bind('<Button>', start_tracking) 
# Add the entered widget to the tracked widgets, if the tracking flag is set 
widget.bind('<Enter>', add_to_tracked_widgets) 
# Execute an action for every tracked widget; unset the flag 
widget.bind('<ButtonRelease>', end_tracking) 

我查看了 grab_current 和 grab_status 方法,但它们总是返回 None。

Python 版本为 3.4.1。

请您参考如下方法:

这可能是最复杂的方法,但是没关系。 使这变得更复杂的一件事是 Tkinter 本身,因为 event.widget 仍然指的是最初被点击的小部件。我们可以使用的另一个不同的事件是 Motion,当鼠标在小部件内移动时它会被激活。

tk.bind("<Motion>", add_tracked) 

我认为你可以自己实现列表和状态变量,所以我们来到 add_tracked 方法(我只是重命名它,它是你的 add_to_tracked_widgets):

def add_tracked(event): 
    if tracking: 
        # Get coordinated of the event and use the master window method to determine 
        # wich widget lays inside these. 
        widget = tk.winfo_containing(event.x_root, event.y_root) 
        # Since 'Motion' creates many events repeatedly, you have to convert this 
        # list into a set to remove duplicates. 
        widgets.append(widget)