How to get rid of a label once its text has been renamed?

谁说我不能喝 提交于 2021-02-08 11:48:20

问题


So I have a Label where when a button is pressed, it changes the name of the text to display another label below the existing label. It pretty much just prints the same label with a different text on the row below. When the Delete Text button is pressed, it will delete the new label that has been created but how do I delete the label before the new label? I can also only remove the label via destroy and not forget.

I tried changing the text of the variable back to what it says on the window but it seems like once the name has been changed, the label doesn't exist on python but it exists on the window only.

from tkinter import *

main = Tk()

NameList = []
counter = 0


def PrintText():

    #Globalising first and last name so that they can be used in other subroutines
    global name, counter, NameLabel

    #Defining the .get() function as something else to make it easier
    name = name_entry.get()

    NameList.append(name)
    NameLabel = Label(main, text=(NameList[0+counter]))
    NameLabel.grid(row=(counter+3))
    counter += 1

def DeleteText():

    global NameLabel, counter

    NameLabel.destroy()
    counter -= 1
    del NameList[counter]

def Name():
    #Globalising the labels and buttons so that they can be deleted later on
    global first_name_label, first_quit, next_button
    #
    name_label = Label(main, text="Name:")
    name_label.grid(row=0, column=0)
    #
    PrintTextButton = Button(main, text="Print Text", width=8, command=PrintText, bg="light blue")
    PrintTextButton.grid(row=2, column=0)
    DeleteTextButton = Button(main, text="Delete Text", width=8, command=DeleteText, bg="light blue")
    DeleteTextButton.grid(row=2, column=1)


name_entry = Entry(main)
name_entry.grid(row=0, column=1, columnspan=4)

errorName = StringVar()
Name()

When I enter what I want in the entry box and press Print Text, I want it to create a label. Each time I press Print Text, I want it to create a new Label beneath the old label. When I press remove item, I want it to delete the label I have created. When I keep pressing remove item, I would like it to keep removing the labels.


回答1:


Question: How to get rid of a label once its text has been renamed?

  • Define a Container class which holds the Label.
    Here we use class LabelListbox which inherits from tk.Frame.

    class LabelListbox(tk.Frame):
        def __init__(self, parent, *args, **kwargs):
            super().__init__(parent, *args, **kwargs)
    
  • The @property .labels returns all Label in the Container in sorted order.

    @property
    def labels(self):
        return sorted(self.children)
    
  • Add a new Label to the Container, layout to the end of the list

    def add_label(self, text):
        tk.Label(self, text=text).grid()
    
  • Changes the text= of a Label, referenced by its index.

    def configure_text(self, idx, text):
        labels = self.labels
        if idx in range(0, len(labels)):
            self.children[labels[idx]].configure(text=text)
    
  • Remove the last Label from the Container

    def remove_last(self):
        if self.labels:
            self.children[self.labels[-1]].destroy()
    
  • Remove a Label at the given index. (0-based)

    def remove_by_index(self, idx):
        labels = self.labels
        if idx in range(0, len(labels)):
            self.children[labels[idx]].destroy()
    
  • Remove all Label where the given text can be found

    def remove_by_text(self, text):
        for label in self.labels:
            if text in self.children[label]['text']:
                self.children[label].destroy()
    

Usage: Click one after another of the menu items!

import tkinter as tk


class LabelListbox(tk.Frame):
    # Here define all of the above


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.menubar = tk.Menu(self)
        self.config(menu=self.menubar)

        lbl_listbox = LabelListbox(self)
        lbl_listbox.grid(row=0, column=0)

        for _ in range(4):
            lbl_listbox.add_label('This is Label {}'.format(_))

        self.menubar.add_command(label='Remove last',
                                 command=lbl_listbox.remove_last)

        self.menubar.add_command(label='Remove by index 1',
                                 command=lambda:lbl_listbox.remove_by_index(1))

        self.menubar.add_command(label='Change Label text"',
                                 command=lambda:lbl_listbox.
                                 configure_text(0, 'The text changed to Label 1'))

        self.menubar.add_command(label='Remove by text "Label 1"',
                                 command=lambda:lbl_listbox.remove_by_text('Label 1'))

if __name__ == '__main__':
    App().mainloop()

Tested with Python: 3.5



来源:https://stackoverflow.com/questions/57931378/how-to-get-rid-of-a-label-once-its-text-has-been-renamed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!