问题
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?
回答1:
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.
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()
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)
来源:https://stackoverflow.com/questions/59696557/tkinter-button-different-commands-on-right-and-left-mouse-click