没有什么能阻止您从按钮创建小部件。只需创建一个创建标签的命令,然后从按钮调用它。
import tkinter as tk
def create_label():
count = len(root.winfo_children())
label = tk.Label(root, text=f"Label #{count}")
label.pack(side="top")
root = tk.Tk()
root.geometry("500x500")
button = tk.Button(root, text="Create label", command=create_label)
button.pack(side="top")
root.mainloop()
如果您希望以后能够访问这些标签,请将它们添加到全局数组或字典中:
labels = []
def create_label():
count = len(root.winfo_children())
label = tk.Label(root, text=f"Label #{count}")
label.pack(side="top")
labels.append(label)
如果你想创建一个带有一个或多个按钮的标签,我建议创建一个自定义类。这是一个模拟“TO DO”项目的示例,带有一个会自行销毁的按钮。这不是特别好的设计,但它显示了一般概念。
class TodoItem(tk.Frame):
def __init__(self, parent, text):
super().__init__(parent)
self.label = tk.Label(self, text=text, anchor="w")
self.delete = tk.Button(self, text="Delete", command=self.delete)
self.delete.pack(side="right")
self.label.pack(side="left", fill="both", expand=True)
def delete(self):
self.destroy()
然后您可以像对待任何其他小部件一样对待它,包括能够通过单击按钮来创建它:
def create_label():
count = len(root.winfo_children())
item = TodoItem(root, f"This is item #{count}")
item.pack(side="top", fill="x")