【问题标题】:How to get the variable name of a button I have just clicked, tkinter如何获取我刚刚单击的按钮的变量名称,tkinter
【发布时间】:2015-12-11 09:56:08
【问题描述】:

我目前正在编写一个带有按钮字段的游戏,每个按钮都有一个唯一的变量名称。每个按钮都是具有多个属性的“空间”类的一部分。每个按钮都有与之关联的相同命令:“move()”。当我单击一个按钮时,我希望代码使用“.getM()”函数获取该特定按钮的属性。我的移动代码如下,它不完整。如何将按钮名称分配给 var.?

def move():
    var = "???????"
    mGridv = var.getM()
    iGridv = var.getI()
    playv = var.getPlay()

    if playv != None:
        message = "This play is invalid"

【问题讨论】:

标签: python-3.x button tkinter


【解决方案1】:

假设您以通常的方式创建按钮,您可以使用lambda 来传递参数。 lambda 允许您创建一个带有参数的匿名函数,然后您可以使用它来调用您的函数。

如果您想传递实际的按钮引用,则需要分两步完成,因为按钮对象在创建之前不会存在。

for i in range(10):
    button = tk.Button(...)
    button.configure(command=lambda b=button: move(b))

您的move 函数需要如下所示:

def move(var):
    mGridv = var.getM()
    iGridv = var.getI()
    ...

您不一定要传入按钮的实例,也可以传入该按钮的属性。

【讨论】:

  • 谢谢,我相信这就是我要找的。​​span>
【解决方案2】:

你可以Bind the button event to the function

from Tkinter import *

def move(event):
    """will print button property _name"""
    w = event.widget                      # here we recover your Button object
    print w._name

root = Tk()

but_strings = ['But1', 'But2', 'But3']    # As many as buttons you want to create
buttons = []                              # let's create buttons automatically
for label in but_strings:                 # and store them in the list 'buttons'
    button_n = Button(root, text=label)
    button_n.pack()
    button_n.bind('<Button-1>', move)     # here we bind the button press event with
                                          #  the function 'move()' for each widget
    buttons.append(button_n)

root.mainloop() 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-04
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多