如何删除数组中的所有 python tkinter 标签

How do you remove all python tkinter labels in an array

我正在尝试在 Python Tkinter 中编写一个应用程序,您可以在其中通过文本字段输入文本,然后显示输入文本中每个字符的标签。

from tkinter import *
array = []

root = Tk()
root.title('app interface')

inpframe = LabelFrame(root, text="input", padx=100, pady=20)
inpframe.pack()

outframe = LabelFrame(root, text="output", padx=100, pady=100)
outframe.pack()

c = " "

def on_enter(e):
    e.widget['background'] = 'green'
    c = e.widget['text']
    currentchar = Label(inpframe, text=c)
    currentchar.grid(row=1, column=1)

def on_leave(e):
    e.widget['background'] = 'SystemButtonFace'
    currentchar = Label(inpframe, text=" ")
    currentchar.grid(row=1, column=1)

inp = Entry(inpframe)
inp.grid(row=0, column=0)

def enterText():
    array.clear()
    inptxt = inp.get().lower()
    myLabel = Label(inpframe, text=inptxt)
    myLabel.grid(row=1, column=0)

    for i in inptxt:
        array.append(i)

    for i in range(0, len(array), 1):
        array[i] = Button(outframe, text=array[i], height=10, width=5)
        array[i].grid(row=2, column= i, padx=5, pady=10)
        array[i].bind("<Enter>", on_enter)
        array[i].bind("<Leave>", on_leave)

myButton = Button(inpframe, text="Enter", command=enterText)
myButton.grid(row=0, column=1)

root.mainloop()

问题来了。当我输入比前一个文本短的文本时,会显示较短的文本,但前一个文本中的剩余文本仍保留在界面上 enter image description here。 例如,当我键入“world”时,应用程序会显示 world。但是当我输入“hi”时,应用程序显示 h i r l d

我看到保存文本的标签也留在了新输入的文本后面。您可以简单地在全局范围内创建标签,然后在每次输入新文本时配置文本。

至于按钮;有一种简单的方法可以销毁小部件的所有子项,如下所示。

from tkinter import *
array = []

root = Tk()
root.title('app interface')

inpframe = LabelFrame(root, text="input", padx=100, pady=20)
inpframe.pack()
outframe = LabelFrame(root, text="output", padx=100, pady=100)
outframe.pack()
inp = Entry(inpframe)
inp.grid(row=0, column=0)
myLabel = Label(inpframe)   # Create label in the global scope
myLabel.grid(row=1, column=0)

c = " "

def on_enter(e):
    e.widget['background'] = 'green'
    c = e.widget['text']
    currentchar = Label(inpframe, text=c)
    currentchar.grid(row=1, column=1)

def on_leave(e):
    e.widget['background'] = 'SystemButtonFace'
    currentchar = Label(inpframe, text=" ")
    currentchar.grid(row=1, column=1)

def enterText():
    array.clear()
    inptxt = inp.get().lower()
    myLabel.config(text=inptxt) # Configure label for new text

    # Delete all current buttons
    for widget in outframe.winfo_children():
        widget.destroy()

    for i in inptxt:
        array.append(i)

    for i in range(0, len(array), 1):
        array[i] = Button(outframe, text=array[i], height=10, width=5)
        array[i].grid(row=2, column= i, padx=5, pady=10)
        array[i].bind("<Enter>", on_enter)
        array[i].bind("<Leave>", on_leave)

myButton = Button(inpframe, text="Enter", command=enterText)
myButton.grid(row=0, column=1)

root.mainloop()

或者您可以遍历数组并在清除数组之前删除每个按钮:

# Delete all current buttons
for i in array:
    i.destroy()
array.clear()