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

时间:2019-07-18 18:48:30

标签: python-3.x tkinter widget destroy

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的新手-谢谢。

1 个答案:

答案 0 :(得分:1)

您需要将变量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()