如何将事件绑定到按住的鼠标左键?
-
17-09-2020 - |
题
我需要一个命令,只要按住鼠标左键就可以执行。
解决方案
查看文档的表7-1。在按下按钮时,有些事件指定了运动, <B1-Motion>
, <B2-Motion>
等。
如果你不是在谈论一个新闻和移动事件,那么你可以开始做你的活动 <Button-1>
并停止这样做,当你收到 <B1-Release>
.
其他提示
如果你想在没有任何干预事件的情况下"发生一些事情"(即:没有用户移动鼠标或按下任何其他按钮)您唯一的选择是轮询。按下按钮时设置标志,释放时取消设置。轮询时,检查标志并运行代码(如果已设置)。
这里有一些东西来说明这一点:
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>
事件。
使用鼠标移动/运动事件并检查修改器标志。鼠标按钮将显示在那里。
不隶属于 StackOverflow