英文:
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('Mouse is pressed!')
#creating canvas
my_canvas = tkinter.Canvas(height=400, width=600)
my_canvas.pack()
#binding
my_canvas.bind('<Button-1>', 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
要绑定的事件是 <ButtonPress-1>
,如果您想在按钮被按下时调用函数。
如果您想在鼠标按下时持续调用函数,同时鼠标移动,那么您可以绑定到 <B1-Motion>
。这将允许您在用户移动鼠标时进行绘制。
英文:
The event you need to bind to is <ButtonPress-1>
, 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 <B1-Motion>
. That would allow you to draw as the user moves the mouse around.
答案2
得分: 1
对于像使用鼠标进行'painting'(绘画)的操作,通常我会使用bind('<B1-Motion>', <callback>)
。
当然,你也可以使用B2
或B3
来绑定到其他按钮。
这里的注意事项是事件不会立即触发 - 你必须先移动鼠标。不过,你可以轻松地绑定第二个处理程序到'<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('<B1-Motion>', <callback>)
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 <'Button-1'>
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('<ButtonPress-1>', lambda e: print(e))
my_canvas.bind('<B1-Motion>', lambda e: print(e))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论