简体   繁体   中英

Python tkinter - Creating Labels and then deleting them

I want to create multiple labels one below the other upon button-click (Create) and then delete all labels in one instance upon another button-click (Delete).

Right now I am thinking of creating multiple names for the labels - each name created on a single click. So if I click button n times, I will get n names: myLabel1, myLabel2,..., myLabeln

Then when I click the Delete button, I will have something like - myLabel1.destroy(), myLabel2.destroy(), . . . myLabeln.destroy()

I am struggling with assigning these names to labels in the form of - myLabel1 = tk.Label, etc. I am thinking in terms of the eval function in MATLAB. Is there anything like that for Python?

Is there even a better way of doing what I want to do?

If I use the.pack() method, I get my labels one below the other. But they all are assigned to only myLabel (since I use myLabel = tk.Label). And when I use myLabel.destroy(), only the last instance of label is deleted.

Code with.pack() and single usage of myLabel where the labels are formed as needed, but only last one is deleted:

import tkinter as tk
from tkinter import ttk
import tkinter.font as tkFont

root = tk.Tk()

def click():
    global myLabel
    myLabel = tk.Label(root, text = e.get())
    myLabel.pack(pady=10)
    e.delete(0,'end')

def delete():
    myLabel.destroy()

e = tk.Entry(root, width = 50)
e.pack(padx = 10, pady = 10)

CreateButton = tk.Button(root, text = 'Enter name', command = click)
CreateButton.pack(pady=10)

DeleteButton = tk.Button(root, text = 'Delete', command = delete)
DeleteButton.pack(pady=40)

root.mainloop()

But as this only deletes the last label that was created, I tried the method I mentioned at the start -

import tkinter as tk
from tkinter import ttk
import tkinter.font as tkFont

ii = 0

root = tk.Tk()

def click():
    global labelname, ii
    ii += 1
    labelname = 'myLabel' + str(ii)
    print(labelname)
    labelname = tk.Label(root, text = e.get()) # I wanted 'labelname' here to be 'myLabel1'
    e.delete(0,'end')

def delete():
#     for ii in range(1,max(ii)):
    labelname.config(text = '') # I wanted 'labelname' here to be 'myLabeln' in a for loop going from 1 to n

e = tk.Entry(root, width = 50)
e.pack(padx = 10, pady = 10)

CreateButton = tk.Button(root, text = 'Enter name', command = click)
CreateButton.pack(pady=10)

DeleteButton = tk.Button(root, text = 'Delete', command = delete)
DeleteButton.pack(pady=40)

root.mainloop()

Maybe I going about it in a very convoluted way and there is an easier way without using For loop, etc.

Please advice.

Thank you

R

You can use this script: the text of each label is stocked in var labels.

Instead of assigning a variable for each label, you can recreate one label in a new row, but by adding it to an array, or something like that which can contain all the labels, so you can delete each of them whenever you want.

from tkinter import *

win = Tk()                         # create the window

labels = []                        # no labels

def add_label():
    global labels, text
    labels.append(Label(win, text=text.get())) # append a label object to the list
    labels[-1].pack()              # draw the last label

def delete_all_labels():
    global labels
    for label in labels:           # delete all the labels
        label.pack_forget()
    labels = []

text = Entry(win)                  # add the entry
text.pack()

Button(win, text="Create new label", command=add_label).pack()
Button(win, text="Delete all the labels", command=delete_all_labels).pack()

win.mainloop()

Fill the Entry and click buttons.

You can use grid to organize the window. In this case, use grid_forget and not pack_forget to delete the labels.

from tkinter import *

win = Tk()                         # create the window

labels = []                        # no labels

                                   # index for method grid()
rowIndex = 2                       # Set to 2 because of the
                                   # buttons and the entry.
                                   # this variable is used to increment
                                   # the y position of the labels so that
                                   # they are drawn one after the other,
                                   # and not on top of each other.

def add_label():
    global labels, text, rowIndex
    labels.append(Label(win, text=text.get())) # append a label object to the list
    rowIndex += 1                  # increment the y position

                                   # draw the added label
    labels[-1]\
            .grid(columnspan=2,    # for align in the middle.
                  row=rowIndex,    # y position specific to this label
                  pady=5)

def delete_all_labels():
    global labels
    for label in labels:           # delete all the labels
        label.grid_forget()        # one by one

    rowIndex = 2                   # reset the vars
    labels = []                    #

label=Label(win, text="Type the text :")
label.grid(column=0, row=0, padx=5)

text = Entry(win)                  # add the entry
text.grid(column=1, row=0, padx=5)
text.focus()                       # focus in entry

Button(win, text="Create new label", command=add_label)\
            .grid(column=0, row=1, padx=5)
Button(win, text="Delete all the labels", command=delete_all_labels)\
            .grid(column=1, row=1, padx=5)

win.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