python如何实现通过代码变量来调用动态生成的控件?

要通过代码变量来调用动态生成的控件,可以将这些控件保存在一个列表或者字典中,然后通过索引或者键来随时访问它们。

下面是一个示例代码,展示了如何动态生成Button控件,并将它们存储在一个列表中。然后,我们可以根据用户点击的按钮的索引值,在列表中查找相应的控件,并执行相关操作:

import tkinter as tk

buttons = []

def create_buttons():
    num_buttons = int(entry.get())
    for i in range(num_buttons):
        button = tk.Button(root, text=f"Button {i+1}", command=lambda idx=i: button_click(idx))
        button.pack()
        buttons.append(button)

def button_click(idx):
    button = buttons[idx]
    button.config(bg="red")

root = tk.Tk()

label = tk.Label(root, text="Enter number of buttons to create:")
label.pack()

entry = tk.Entry(root)
entry.pack()

button = tk.Button(root, text="Create Buttons", command=create_buttons)
button.pack()

root.mainloop()

这个示例代码中,我们使用一个名为buttons的列表来存储所有动态生成的Button控件。在create_buttons()函数中,我们使用for循环创建指定数量的Button控件,并将它们添加到窗口中和buttons列表中。注意,我们在lambda函数中使用了idx=i来为每个Button控件保存一个独立的索引值,这将在后面的操作中用到。

button_click()函数中,我们根据用户点击的按钮的索引值,在buttons列表中查找相应的Button控件,并改变其背景颜色。

你可以根据自己的需求修改这个示例代码,例如将控件保存在字典中,使用键来访问它们。

原文链接:,转发请注明来源!