Tkinter按钮在鼠标左右键上单击不同的命令 [英] Tkinter button different commands on right and left mouse click
问题描述
我正在用Python开发扫雷游戏,并使用tkinter库创建gui.有没有绑定到tkinter Button的方法有两个,一个是右键单击时的命令,另一个是鼠标左键时的命令?
I am making minesweeper game in Python and use tkinter library to create gui. Is there any way to bind to tkinter Button two commands, one when button is right-clicked and another when it's left clicked?
推荐答案
尽管tkinter允许您为具有任何小部件的几乎任何事件添加绑定,但是按钮通常仅用于单击.如果您要开发扫雷游戏,则可能不希望使用 Button
小部件,因为按钮可能具有您不需要的内置行为.
Typically buttons are designed for single clicks only, though tkinter lets you add a binding for just about any event with any widget. If you're building a minesweeper game you probably don't want to use the Button
widget since buttons have built-in behaviors you probably don't want.
相反,您可以相当容易地使用 Label
, Frame
或 Canvas
项目.主要困难在于,右键单击可能表示不同平台上的不同事件.对于某些而言,它是< Button-2>
,对于某些而言,它是< Button-3>
.
Instead, you can use a Label
, Frame
, or a Canvas
item fairly easily. The main difficulty is that a right click can mean different events on different platforms. For some it is <Button-2>
and for some it's <Button-3>
.
这是一个使用框架而不是按钮的简单示例.左键单击框架将使其变为绿色,右键单击将其变为红色.此示例也可以使用按钮来工作,尽管它的行为有所不同,因为按钮具有针对左键单击的内置行为,而框架和其他一些小部件则没有.
Here's a simple example that uses a frame rather than a button. A left-click over the frame will turn it green, a right-click will turn it red. This example may work using a button too, though it will behave differently since buttons have built-in behaviors for the left click which frames and some other widgets don't have.
import tkinter as tk
def left_click(event):
event.widget.configure(bg="green")
def right_click(event):
event.widget.configure(bg="red")
root = tk.Tk()
button = tk.Frame(root, width=20, height=20, background="gray")
button.pack(padx=20, pady=20)
button.bind("<Button-1>", left_click)
button.bind("<Button-2>", right_click)
button.bind("<Button-3>", right_click)
root.mainloop()
或者,您可以绑定到< Button>
,< ButtonPress>
或< ButtonRelease>
,这将不会触发无论单击哪个鼠标按钮.然后,您可以检查传入的事件对象的 num
参数,以确定单击了哪个按钮.
Alternately, you can bind to <Button>
, <ButtonPress>
, or <ButtonRelease>
, which will trigger no matter which mouse button was clicked on. You can then examine the num
parameter of the passed-in event object to determine which button was clicked.
def any_click(event):
print(f"you clicked button {event.num}")
...
button.bind("<Button>", any_click)
这篇关于Tkinter按钮在鼠标左右键上单击不同的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!