Python 3.x 无法销毁由tkinter中的函数创建的小部件

Python 3.x 无法销毁由tkinter中的函数创建的小部件,python-3.x,tkinter,widget,destroy,Python 3.x,Tkinter,Widget,Destroy,创建小部件后,我可以先用小部件销毁它们,然后重新创建它们。但是在函数重新创建小部件之后,我不能再破坏它们。我做错了什么?抱歉,我是tkinter新手-谢谢。您需要将变量twoLabel和threeTextEntry定义为globals,因为当您在函数中创建这些变量时,它们是局部变量,您无法从其他函数访问它们 from tkinter import * import tkinter as tk root = Tk() root.geometry("500x500") var1 = String

创建小部件后,我可以先用小部件销毁它们,然后重新创建它们。但是在函数重新创建小部件之后,我不能再破坏它们。我做错了什么?抱歉,我是tkinter新手-谢谢。

您需要将变量
twoLabel
threeTextEntry
定义为
globals
,因为当您在函数中创建这些变量时,它们是
局部变量
,您无法从其他函数访问它们

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问题,这是一个普通的python问题
twoLabel和
threeTextentry是局部变量。
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()