简体   繁体   English

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

[英]How do I bind an event to the left mouse button being held down?

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

If you want "something to happen" without any intervening events (ie: without the user moving the mouse or pressing any other buttons) your only choice is to poll. 如果你想要“发生什么事情”而没有任何干预事件(即:没有用户移动鼠标或按任何其他按钮),你唯一的选择就是轮询。 Set a flag when the button is pressed, unset it when released. 按下按钮时设置标志,释放时取消设置。 While polling, check the flag and run your code if its set. 轮询时,检查标志并运行代码(如果已设置)。

Here's something to illustrate the point: 这里有一点可以说明这一点:

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()

However , polling is generally not necessary in a GUI app. 但是 ,在GUI应用程序中通常不需要轮询。 You probably only care about what happens while the mouse is pressed and is moving. 您可能只关心鼠标按下移动时会发生什么。 In that case, instead of the poll function simply bind do_work to a <B1-Motion> event. 在这种情况下,只需将do_work绑定到<B1-Motion>事件,而不是poll函数。

Look at table 7-1 of the docs. 请查看文档的表7-1。 There are events that specify motion while the button is pressed, <B1-Motion> , <B2-Motion> etc. 按下按钮时会有指定动作的事件, <B1-Motion><B2-Motion>等。

If you're not talking about a press-and-move event, then you can start doing your activity on <Button-1> and stop doing it when you receive <B1-Release> . 如果您不是在谈论按下并移动事件,那么您可以开始在<Button-1>上进行活动,并在收到<B1-Release>时停止活动。

Use the mouse move/motion events and check the modifier flags. 使用鼠标移动/运动事件并检查修改器标志。 The mouse buttons will show up there. 鼠标按钮将显示在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM