【问题标题】:Is there a way to create labels with tkinter by pushing a button有没有办法通过按下按钮用 tkinter 创建标签
【发布时间】:2020-09-09 04:13:00
【问题描述】:

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

【问题讨论】:

  • 您应该能够根据命令生成标签并使用显示管理器显示它们?如果您可以发布 minimal reproducible example 会有所帮助。
  • 您可以使用Text 小部件来保存所需的信息,而不是一堆Labels。

标签: python tkinter window


【解决方案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)

如果你想创建一个带有一个或多个按钮的标签,我建议创建一个自定义类。这是一个模拟“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")

【讨论】:

    【解决方案2】:

    当然。你可以很容易地做到这一点。下面的示例肯定可以考虑不同,但它说明了您想要做的事情背后的基本原则。

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

    【讨论】:

    • columnconfigure()rowconfigure() 是做什么的?
    • @CoolCloud - 谷歌它。答案太长,无法评论。简而言之,根据我使用它们的方式,它们可以像 pack(fill='both', expand=True) 一样协同工作,但并不完全一样。
    猜你喜欢
    • 2022-11-01
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    相关资源
    最近更新 更多