简体   繁体   中英

Tkinter - Button to add label

So I'm currently working with Tkinter and I've came quite far on a program I'm trying to create. Currently I want to have a button which adds labels in the frame.

Here's my code:

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

Now, if you try the code, you'll see that in the window that gets opened, there's a side frame which displays a button that says "Add Account" . Under it you can see a label where it says "Account Nr1" . What I want to happen is that once you open the program, the "Account Nr1" label isn't gonna be there, and it is only gonna show up on that exact spot once you click "Add Account" .

Based on your code, a quick solution is to create the label off screen then move it when the button is clicked.

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

If you set up your form with a grid, you can hide the label using the forget methods: https://www.geeksforgeeks.org/python-forget_pack-and-forget_grid-method-in-tkinter/

--- Update ---

To create labels dynamically, create a label list and use the button to create new labels and append to the list.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM