简体   繁体   English

Tkinter 在鼠标左键单击时按钮不同的命令

[英]Tkinter button different commands on right and left mouse click

I am making minesweeper game in Python and use tkinter library to create gui.我正在用 Python 制作扫雷游戏并使用 tkinter 库来创建 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.通常按钮仅设计用于单击,尽管 tkinter 允许您为任何小部件的几乎任何事件添加绑定。 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.如果您正在构建扫雷游戏,您可能不想使用Button小部件,因为按钮具有您可能不想要的内置行为。

Instead, you can use a Label , Frame , or a Canvas item fairly easily.相反,您可以相当轻松地使用LabelFrameCanvas项目。 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> .有些是<Button-2> ,有些是<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()

Alternately, you can bind to <Button> , <ButtonPress> , or <ButtonRelease> , which will trigger no matter which mouse button was clicked on.或者,您可以绑定到<Button><ButtonPress><ButtonRelease> ,无论单击哪个鼠标按钮都会触发。 You can then examine the num parameter of the passed-in event object to determine which button was clicked.然后,您可以检查传入事件对象的num参数以确定单击了哪个按钮。

def any_click(event):
    print(f"you clicked button {event.num}")
...
button.bind("<Button>", any_click)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM