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?

1 Answers1

9

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)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Would using a single ` – martineau Jan 11 '20 at 19:09
  • 1
    @martineau: it wouldn't be any more or less portable than binding to individual events, but yes, you can bind to ` – Bryan Oakley Jan 11 '20 at 21:29
  • @BryanOakley, there is no OS with right button event other than `Button-2` and `Button-3`, right? – Adarsh TS Sep 29 '20 at 06:07
  • @maddypie: I don't know. – Bryan Oakley Sep 29 '20 at 13:53