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

rec*_*gle 4 python tkinter event-binding

只要按住鼠标左键,我就需要执行一个命令.

Jes*_*lon 5

查看文档的表 7-1。有些事件指定按下按钮时的动作<B1-Motion><B2-Motion>等等。

如果您不是在谈论按下并移动事件,那么您可以开始做您的活动,<Button-1>并在您收到<B1-Release>.

  • 显然现在链接应该是:http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm (2认同)

Bry*_*ley 5

如果你想"事情发生"没有任何干预的事件(即:未经用户移动鼠标或按下任何其他按钮),你唯一的选择是轮询.按下按钮时设置标志,释放时取消设置.轮询时,检查标志并运行代码(如果已设置).

这里有一点可以说明这一点:

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()
Run Code Online (Sandbox Code Playgroud)

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