如何将事件绑定到按住左键鼠标?

8
只要左键一直按下,我需要执行一个命令。
3个回答

10
如果您希望“某些事情发生”而不受任何干扰事件的影响(即:无需用户移动鼠标或按下任何其他按钮),那么您唯一的选择就是轮询。在按下按钮时设置标志,在释放时取消设置。在轮询时,检查标志并在其设置时运行代码。
这里有一些例子来说明这个观点:
import Tkinter

class App:
    def __init__(self, root):
        self.root = root
        self.mouse_pressed = False
        f = Tkinter.Frame(width=100, height=100, background="bisque")
        f.pack(padx=100, pady=100)
        f.bind("<ButtonPress-1>", self.OnMouseDown)
        f.bind("<ButtonRelease-1>", self.OnMouseUp)

    def do_work(self):
        x = self.root.winfo_pointerx()
        y = self.root.winfo_pointery()
        print "button is being pressed... %s/%s" % (x, y)

    def OnMouseDown(self, event):
        self.mouse_pressed = True
        self.poll()

    def OnMouseUp(self, event):
        self.root.after_cancel(self.after_id)

    def poll(self):
        if self.mouse_pressed:
            self.do_work()
            self.after_id = self.root.after(250, self.poll)

root=Tkinter.Tk()
app = App(root)
root.mainloop()

然而,在GUI应用程序中通常不需要轮询。您可能只关心鼠标按下并且移动时发生的情况。在这种情况下,不要使用轮询函数,而是将do_work绑定到<B1-Motion>事件。


7
请查看文档中的表格7-1。其中有指定在按下按钮时指定运动的事件,例如<B1-Motion><B2-Motion>等。
如果您不是在讨论按下和移动事件,则可以在<Button-1>上开始执行您的操作,并在收到<B1-Release>时停止执行。

我建议保持一个像 mouse_is_down 的变量,并根据你是否收到按下或释放事件将其设置为 TrueFalse。在你的代码中,在循环期间,你可以检查变量是否为 True,这意味着鼠标已经按下,然后执行按钮按住的操作。当变量为 False 时,你可以跳过与鼠标按钮按住有关的代码。 - Jesse Dhillon
2
显然现在链接应该是:http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm - Victor Sergienko
@JesseDhillon 这个问题是当你将鼠标移出窗口时。 - Hippolippo

2
使用鼠标移动/运动事件并检查修改器标志。鼠标按钮将显示在那里。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接