6

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

4

3 回答 3

9

如果您希望在没有任何干预事件的情况下“发生某事”(即:无需用户移动鼠标或按下任何其他按钮),您唯一的选择就是轮询。按下按钮时设置标志,释放时取消设置。轮询时,检查标志并运行您的代码(如果已设置)。

这里有一些东西可以说明这一点:

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>事件,而不是 poll 函数。

于 2010-07-20T11:09:46.493 回答
5

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

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

于 2010-07-20T08:06:18.430 回答
1

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

于 2010-07-20T08:02:08.997 回答