有没有一种方法可以通过按下按钮来使用tkinter创建标签

时间:2020-09-09 04:13:00

标签: python tkinter window

我有一个程序,希望它存储用户编写的信息,除了我希望将其存储在窗口中,并在用户每次存储该数据时不断创建新标签和按钮。但是,我找不到代码本身为程序添加标签的方法。编写一堆标签以便事后启用似乎不切实际,我正在寻找更好的解决方案。

2 个答案:

答案 0 :(得分:1)

好的。您可以轻松完成。下面的示例绝对可以用不同的方式来考虑,但是它说明了您想要做的事情的基本原理。

import tkinter as tk

#create root
root = tk.Tk()
root.geometry('400x300')

#configure grid
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(1, weight=1)

#just a container for generated labels
label_frame = tk.Frame(root, bg='black')
label_frame.grid(row=0, column=0, sticky='nswe', columnspan=3)

#instructions for this example
tk.Label(root, text='enter label text and click create', anchor='w').grid(row=1, column=0, sticky='w')

#entry field for example purposes
label_ent = tk.Entry(root)
label_ent.grid(row=1, column=1, sticky='we')

#called when the button is clicked
def create_label(master, row, column, sticky='w', **kwargs):
    #really, it's as simple as creating a label and adding it to the display
    #~ with grid, pack or place, within a function that is called by a button
    tk.Label(master, **kwargs).grid(row=row, column=column, sticky=sticky)
    
#button that creates labels
tk.Button(root, text='create', command=lambda: create_label(label_frame, 
                                                            row=len(label_frame.winfo_children()), 
                                                            column=0, 
                                                            text=label_ent.get())).grid(row=1, column=2, sticky='w')

root.mainloop()

答案 1 :(得分:1)

没有什么可以阻止您通过按钮创建窗口小部件的。只需创建一个创建标签的命令,然后通过按钮调用即可。

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)

如果要使用一个或多个按钮创建标签,建议您创建一个自定义类。这是一个模拟“待办事项”项目的示例,其按钮会自毁。这不是特别好的设计,但它显示了一般概念。

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")