Tkinter button different commands on right and left mouse click

淺唱寂寞╮ 提交于 2021-01-28 11:10:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!