Reputation: 23
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)
The widgets are created, I can destroy them initially with the widget and then recreate them. But then I can no longer destory them after the widgets have been recreated by the function. What am I doing wrong here? Sorry I'm new to tkinter - thanks.
Upvotes: 0
Views: 594
Reputation: 7206
you need to define your variables twoLabel
and threeTextEntry
as globals
,because when you are creating these variables in the function they are local variables
and you can not reach them from another functions.
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()
Upvotes: 1