【问题标题】:Tkinter - Button to add labelTkinter - 添加标签的按钮
【发布时间】:2020-09-20 17:45:38
【问题描述】:

所以我目前正在与 Tkinter 合作,并且在我正在尝试创建的程序上取得了相当大的进展。 目前我想要一个在框架中添加标签的按钮。

这是我的代码:

import tkinter as tk

#Window
root = tk.Tk()
root.geometry("800x700")
root.title("Account Overview")

#Title_Frame
title_frame = tk.Frame(root, width=800, height=100, bg='#b1b7ba')
title_frame.pack(side='top')
title_label = tk.Label(title_frame, text="Account Overview", font='Courier 35 underline')
title_label.place(relx=0.2, rely=0.2)

#Account_Frame
account_frame = tk.Frame(root, width=300, height=700, bg='#9dd7f5')
account_frame.pack(side='right')
add_account_button = tk.Button(account_frame, text="Add Account", font='Courier 15')
add_account_button.place(relx=0.26, rely=0.03)
account = tk.Label(account_frame, text="Account Nr1", font='Helvetica 40')
account.place(relx=0.01, rely=0.125)

root.mainloop()

现在,如果您尝试代码,您会看到在打开的窗口中,有一个侧框 它会显示一个按钮,上面写着“添加帐户”。在它下方,您可以看到一个标签,上面写着 "Account Nr1"。我想要发生的是,一旦您打开程序,“Account Nr1” 标签就不会出现,并且只有在您单击 后才会出现在那个确切的位置“添加帐户”

【问题讨论】:

  • 您希望小部件不存在,还是只希望它显示不存在?如果您不希望用户在选择帐户之前看到任何内容,则可以将文本设置为空字符串。 GUI 通常使所有数据字段可见,但在有数据之前将它们留空。

标签: python button tkinter label


【解决方案1】:

根据您的代码,一个快速的解决方案是在屏幕外创建标签,然后在单击按钮时移动它。

def showlabel():
   account.place(relx=0.01, rely=0.125)  # move on screen

#Account_Frame
account_frame = tk.Frame(root, width=300, height=700, bg='#9dd7f5')
account_frame.pack(side='right')
add_account_button = tk.Button(account_frame, text="Add Account", font='Courier 15', command=showlabel)
add_account_button.place(relx=0.26, rely=0.03)
account = tk.Label(account_frame, text="Account Nr1", font='Helvetica 40')
account.place(relx=10.01, rely=0.125)  # off screen

root.mainloop()

如果您使用网格设置表单,则可以使用 forget 方法隐藏标签:https://www.geeksforgeeks.org/python-forget_pack-and-forget_grid-method-in-tkinter/

--- 更新---

要动态创建标签,请创建标签列表并使用按钮创建新标签并附加到列表中。

lbllst = []
def addlabel():
    account = tk.Label(account_frame, text="Account Nr"+str(len(lbllst)+1), font='Helvetica 40')
    account.place(relx=0.01, rely=0.125*(len(lbllst)+1))
    lbllst.append(account)
   
#Account_Frame
account_frame = tk.Frame(root, width=300, height=700, bg='#9dd7f5')
account_frame.pack(side='right')
add_account_button = tk.Button(account_frame, text="Add Account", font='Courier 15', command=addlabel)
add_account_button.place(relx=0.26, rely=0.03)

root.mainloop()

【讨论】:

  • 为什么开头是place呢?把它放在那里,只在点击按钮时放置它?
  • 非常感谢!这是一个非常聪明的解决方法!
  • 有没有一种方法可以添加标签而不首先存在标签,因为我希望您要创建的下一个帐户标签位于您创建的第一个帐户标签下方等等。
  • 谢谢你,我无法形容你在这里帮助了我多少!我非常感谢你的帮助。顺便说一句,如果我需要有关这方面的更多帮助,你能在聊天中留意吗?
猜你喜欢
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多