Reputation: 143
I have this code:
# -*- coding: utf-8 -*-
def clear_screen():
button2.pack_forget()
button3.pack_forget()
text.pack_forget()
label.pack_forget()
def main_page():
var = StringVar()
label = Label( root, textvariable=var)
var.set("Fill in the caps: ")
label.pack()
global text
text = Text(root,font=("Purisa",12))
text.pack()
global button
button=Button(root, text ="Create text with caps.", command =lambda: full_function())
button.pack()
def clear_and_main():
clear_screen()
main_page()
def full_function():
global button2
global button3
button3=Button(root, text ="Main page", command=lambda: clear_and_main())
button3.pack()
button2=Button(root, text ="Answer")
button2.pack()
button.pack_forget()
from Tkinter import *
root = Tk()
main_page()
root.mainloop()
I want this program to work that way, if I click button "Main page", it will recreate main page. But it doesn't. Textfield and button wont reappear. How could I make it work right way?
Upvotes: 0
Views: 11048
Reputation: 385900
You are neglecting to declare text
and label
as global, so clear_screen
is failing.
Calling pack_forget
does not destroy widgets, it only hides them. Your code creates new widgets every time which means you have a memory leak -- you keep creating more and more and more widgets every time you click the button.
The easiest way to accomplish what you want is to put all of the widgets in a frame, and then destroy and recreate the frame. When you destroy a widget, any children widgets automatically get destroyed. This also makes it easier to maintain, since you don't have to change anything if you add more widgets.
Upvotes: 1