5

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?

0

1 Answer 1

14

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Would using a single <Button> event handler and using the state bits to identify which mouse button be portable?
@martineau: it wouldn't be any more or less portable than binding to individual events, but yes, you can bind to <Button> and any button press will trigger the binding. You can examine the num field of the passed in event object to determine which button was clicked.
@BryanOakley, there is no OS with right button event other than Button-2 and Button-3, right?
@maddypie: I don't know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.