【问题标题】:How to bind multiple mouse buttons to a widget?如何将多个鼠标按钮绑定到一个小部件?
【发布时间】:2016-08-10 16:35:41
【问题描述】:

我正在尝试制作扫雷游戏。我为每个未区分的正方形创建了一个按钮。

my_list = [[0 for i in range(9)] for j in range(9)]

all_buttons = []


def creaMatriz():
    for y, row in enumerate(my_list):
        buttons_row = [] 
        for x, element in enumerate(row):
            boton2 = Button(root, text="", width=6, height=3, command=lambda a=x, b=y: onButtonPressed(a, b))
            boton2.grid(row=y, column=x)
            buttons_row.append(boton2)
        all_buttons.append(buttons_row)


def onButtonPressed(x, y):
    all_buttons[y][x]['text'] = str(qwer[x][y]) # Some action!!!
....

当我在一个未分化的方块上按下鼠标左键时,我正在调用函数onButtonPressed(x, y),方块上会出现一个数字或一个地雷。

如何在未区分的正方形上按鼠标右键时调用另一个函数。我想在广场上看到“M”。

完整代码:http://pastebin.com/cWGS4fBp

【问题讨论】:

    标签: python button tkinter


    【解决方案1】:

    您需要绑定所需的键才能获得此功能。这是一个简单的概念:

    from tkinter import *
    
    root = Tk()
    
    def left(event):
        label.config(text="Left clicked")
    
    def right(event):
        label.config(text="Right clicked")
    
    label = Label(root, text="Nothing")
    label.pack()
    
    label.focus_set()
    label.bind("<1>", left)
    label.bind("<3>", right)
    

    如果您正在寻找它,请告诉我们。

    【讨论】:

    • 我有 9*9=81 个没有名字的按钮。列出包含 81 个按钮的 all_buttons,它们的坐标为 (x,y)。我不知道如何将键绑定到没有名称的按钮。
    【解决方案2】:

    您不需要做任何特别的事情,您只需单独绑定每个鼠标按钮,而不是使用command 属性。

    例如,让我们为鼠标左右键创建一个回调:

    def onLeftClick(x, y):
        print("you clicked on %x,%y" % (x, y))
    
    def onRightClick(x, y):
        print("you clicked on %x,%y" % (x, y))
    

    接下来,我们可以使用bind 方法分别绑定到每个函数。由于我们正在添加自定义绑定,我们确实想要设置按钮的command 属性。

    def creaMatriz():
        for y, row in enumerate(my_list):
            buttons_row = [] 
            for x, element in enumerate(row):
                button = Button(root, text="", width=6, height=3)
                ...
                button.bind("<1>", lambda event, x=x, y=y: onLeftClick(x,y))
                button.bind("<3>", lambda event, x=x, y=y: onRightClick(x,y))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-05
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多