如何在Python的tkinter中绑定”鼠标按下”事件?

huangapple go评论58阅读模式
英文:

How do i bind "mouse is pressed" in Python's tkinter?

问题

我是新手学习 tkinter,正在编写一个简单的“画图”程序,当我按下鼠标时,在屏幕上绘制一个像素点。

所以我尝试像这样绑定我的函数“is_pressed”:

#按下时触发的函数
def is_pressed(event):
    print('鼠标被按下了!')

#创建画布
my_canvas = tkinter.Canvas(height=400, width=600)
my_canvas.pack()

#绑定事件
my_canvas.bind('<Button-1>', is_pressed)

现在,我希望这个函数在鼠标按下时运行,而不是只在单击时运行。我该怎么做?

英文:

I'm new to tkinter and I'm coding a simple "Paint" program, that draws a pixel on screen when I press my mouse.

So i tried to bind my function "is_pressed" like this:

#is pressed
def is_pressed(event):
    print(&#39;Mouse is pressed!&#39;)

#creating canvas
my_canvas = tkinter.Canvas(height=400, width=600)
my_canvas.pack()

#binding
my_canvas.bind(&#39;&lt;Button-1&gt;&#39;, is_pressed)

Now, I want this function to run when mouse is pressed, not when it's just clicked. How do i do it?

答案1

得分: 1

要绑定的事件是 &lt;ButtonPress-1&gt;,如果您想在按钮被按下时调用函数。

如果您想在鼠标按下时持续调用函数,同时鼠标移动,那么您可以绑定到 &lt;B1-Motion&gt;。这将允许您在用户移动鼠标时进行绘制。

英文:

The event you need to bind to is &lt;ButtonPress-1&gt;, if you want to call a function when the button is pressed.

If you want to continuously call a function when the mouse is moved while the button is pressed, then you can bind to &lt;B1-Motion&gt;. That would allow you to draw as the user moves the mouse around.

答案2

得分: 1

对于像使用鼠标进行'painting'(绘画)的操作,通常我会使用bind('<B1-Motion>', <callback>)

当然,你也可以使用B2B3来绑定到其他按钮。

这里的注意事项是事件不会立即触发 - 你必须先移动鼠标。不过,你可以轻松地绑定第二个处理程序到'<Button-1>'

# 这应该捕获到鼠标按下的瞬间以及在按钮按住时的任何移动;
# lambda函数只是示例 - 使用你想要的任何回调函数
my_canvas.bind('<ButtonPress-1>', lambda e: print(e))
my_canvas.bind('<B1-Motion>', lambda e: print(e))
英文:

For something like 'painting' with the mouse, I've usually used bind(&#39;&lt;B1-Motion&gt;&#39;, &lt;callback&gt;)

Naturally, you can bind this to other buttons using B2 or B3 instead.

The caveat here is that the event doesn't trigger immediately - you have to move the mouse first. You could easily bind a second handler to &lt;&#39;Button-1&#39;&gt; though

# this should catch the moment the mouse is pressed as well as any motion while the
# button is held; the lambdas are just examples - use whatever callback you want
my_canvas.bind(&#39;&lt;ButtonPress-1&gt;&#39;, lambda e: print(e))
my_canvas.bind(&#39;&lt;B1-Motion&gt;&#39;, lambda e: print(e))

huangapple
  • 本文由 发表于 2023年6月29日 02:30:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575825.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定