无法销毁由 tkinter 中的函数创建的小部件

Unable to destroy widgets created by function in tkinter

from tkinter import *
import tkinter as tk

root = Tk()
root.geometry("500x500")

var1 = StringVar()

def create():
    twoLabel = Label(root,text="meh",)
    twoLabel.place(x=20,y=300)

    threeTextEntry = Entry(root, textvariable=var1)
    threeTextEntry.place(x=20,y=400)  

def destroy():    
    twoLabel.destroy()
    threeTextEntry.destroy()

zeroButton = tk.Button(root, text="create", width=8, fg="black", bg="gold", command=create)
zeroButton.place(x=20,y=100)

oneButton = tk.Button(root, text="destroy", width=8, fg="black", bg="gold", command=destroy)
oneButton.place(x=20,y=200)

twoLabel = Label(root,text="meh",)
twoLabel.place(x=20,y=300)

threeTextEntry = Entry(root, textvariable=var1)
threeTextEntry.place(x=20,y=400)  

小部件已创建,我可以先用小部件销毁它们,然后重新创建它们。但是在函数重新创建小部件后,我无法再销毁它们。我在这里做错了什么?抱歉,我是 tkinter 的新手 - 谢谢。

您需要将变量 twoLabelthreeTextEntry 定义为 globals ,因为当您在函数中创建这些变量时,它们是 local variables 而您不能从其他功能访问它们。

from tkinter import *
import tkinter as tk

root = Tk()
root.geometry("500x500")

var1 = StringVar()


def create():
    global twoLabel
    global threeTextEntry
    twoLabel = Label(root,text="meh",)
    twoLabel.place(x=20,y=300)

    threeTextEntry = Entry(root, textvariable=var1)
    threeTextEntry.place(x=20,y=400)

def destroy():
    twoLabel.destroy()
    threeTextEntry.destroy()

zeroButton = tk.Button(root, text="create", width=8, fg="black", bg="gold", command=create)
zeroButton.place(x=20,y=100)

oneButton = tk.Button(root, text="destroy", width=8, fg="black", bg="gold", command=destroy)
oneButton.place(x=20,y=200)

global twoLabel
global threeTextEntry
twoLabel = Label(root,text="meh",)
twoLabel.place(x=20,y=300)

threeTextEntry = Entry(root, textvariable=var1)
threeTextEntry.place(x=20,y=400)

root.mainloop()