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

8 投票
3 回答
17125 浏览
提问于 2025-04-16 01:33

我需要一个命令,在左键鼠标按住的时候一直执行。

3 个回答

2

使用鼠标移动或动作事件,并检查一些修饰符标志。鼠标按钮的信息会在这里显示出来。

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)应用中,通常不需要使用轮询。你可能只关心在鼠标按下的同时,它是如何移动的。在这种情况下,不如直接把要做的事情绑定到一个 <B1-Motion> 事件上。

7

看看文档中的表7-1。里面有一些事件是用来表示在按住按钮时的动作,比如 <B1-Motion><B2-Motion> 等等。

如果你不是在说按住并移动的事件,那么你可以在 <Button-1> 事件发生时开始你的操作,并在收到 <B1-Release> 事件时停止操作。

撰写回答