如何在Tkinter中使用pack_forget后使小部件再次可见
我有这段代码:
# -*- 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()
我希望这个程序能这样工作:如果我点击“主页”按钮,它就会重新创建主页。但是它并没有这样做。文本框和按钮没有重新出现。我该怎么做才能让它正常工作呢?
1 个回答
1
你没有把 text
和 label
声明为全局变量,所以 clear_screen
这个函数出错了。
调用 pack_forget
并不会销毁那些小部件,它只是把它们隐藏起来。你的代码每次点击按钮时都会创建新的小部件,这样就会造成内存泄漏——你每次点击按钮都会不断增加小部件的数量。
实现你想要的功能最简单的方法是把所有的小部件放在一个框架里,然后销毁并重新创建这个框架。当你销毁一个小部件时,里面的子小部件也会自动被销毁。这样做也更容易维护,因为如果你添加更多的小部件,就不需要改动其他的东西。