python - 在 Tkinter 中动态创建函数和绑定(bind)按钮

标签 python dynamic tkinter

我正在尝试为按钮分配值,这些按钮在单击时返回它们的值(更准确地说,它们会打印它。)唯一需要注意的是按钮是使用 for 循环动态创建的。

如何将 id(和其他变量)分配给使用 for 循环创建的按钮?

示例代码:

#Example program to illustrate my issue with dynamic buttons.

from Tkinter import *

class my_app(Frame):
    """Basic Frame"""
    def __init__(self, master):
        """Init the Frame"""
        Frame.__init__(self,master)
        self.grid()
        self.Create_Widgets()

    def Create_Widgets(self):

        for i in range(1, 11): #Start creating buttons

            self.button_id = i #This is meant to be the ID. How can I "attach" or "bind" it to the button?
            print self.button_id

            self.newmessage = Button(self, #I want to bind the self.button_id to each button, so that it prints its number when clicked.
                                     text = "Button ID: %d" % (self.button_id),
                                     anchor = W, command =  lambda: self.access(self.button_id))#Run the method

            #Placing
            self.newmessage.config(height = 3, width = 100)
            self.newmessage.grid(column = 0, row = i, sticky = NW)

    def access(self, b_id): #This is one of the areas where I need help. I want this to return the number of the button clicked.
        self.b_id = b_id
        print self.b_id #Print Button ID

#Root Stuff


root = Tk()
root.title("Tkinter Dynamics")
root.geometry("500x500")
app = my_app(root)

root.mainloop()

最佳答案

问题是在创建按钮后调用命令时使用的是 self.button_id 的最后一个值。您必须为每个 lambda 绑定(bind)局部变量的当前值 lambda i=i: do_something_with(i):

def Create_Widgets(self):
    for i in range(1, 11):
        self.newmessage = Button(self, text= "Button ID: %d" % i, anchor=W,
                                 command = lambda i=i: self.access(i))
        self.newmessage.config(height = 3, width = 100)
        self.newmessage.grid(column = 0, row = i, sticky = NW)

关于python - 在 Tkinter 中动态创建函数和绑定(bind)按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17757434/

相关文章:

Python-将字典转换为嵌套字典

python - 理解位置参数的直观方法不应该跟在关键字参数之后

javascript - 使用 javascript 向表行 (<TR>) 添加内容?

java - 如何让 Android 按钮阵列的 onClickListener 正常工作

python - 在 python 和 tkinter 中检测碰撞

python - odoo xml 无法显示该字段

python - 加入上一年的附加计算

javascript - 通过引用更改 DOM 元素

python - geometry() 中的 +0+0 在 tkinter 中是什么意思?

python:如何删除此代码中的 lambda?