在 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)
关于python - 在 Tkinter 中运动期间避免事件抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25712493/