利用Tkinter模拟PyQt中的StackWeight的效果,在窗口中同一个位置切换不同界面。
首先给出代码,简要解释在注释中,详细解释在下面。
from tkinter import Tk, Label, Button
from tkinter.ttk import Frame
class SwitchFrame(object):
def __init__(self, root):
self.root = root
root.title('界面切换')
root.geometry('500x160')
root.resizable(width=False, height=False) # 阻止Python GUI的大小调整
L1 = Label(root)
L1.pack() # L1用pack布局,用于切换按钮居中显示
Button(L1, text='第1页', command=self.firstpage).grid(row=1, column=1, padx=10, pady=10)
Button(L1, text='第2页', command=self.secondpage).grid(row=1, column=2, padx=10, pady=10)
L2 = Label(root, borderwidth=2, relief="sunken")
L2.pack() # L2用pack布局,用于待切换界面居中显示
# frame1
frame1 = Frame(L2, padding=(5, 20, 10, 10)) # 界面1
self.frame1 = frame1
Label(frame1, text='Frame1').grid(row=1, column=1, padx=10, pady=10)
Label(frame1, text='Frame1').grid(row=1, column=2, padx=10, pady=10)
# frame2
frame2 = Frame(L2, padding=(5, 20, 10, 10)) # 界面2
self.frame2 = frame2
Label(frame2, text='Frame2').grid(row=1, column=1, padx=10, pady=10)
Label(frame2, text='Frame2').grid(row=1, column=2, padx=10, pady=10)
self.currentpage = frame1
self.currentpage.pack() # 默认显示界面1,并记录当前界面
def firstpage(self):
if self.currentpage != self.frame1:
self.currentpage.pack_forget() # 取消显示当前界面,并不是销毁
self.currentpage = self.frame1
self.currentpage.pack() # 显示界面1
def secondpage(self):
if self.currentpage != self.frame2:
self.currentpage.pack_forget() # 取消显示当前界面,并不是销毁
self.currentpage = self.frame2
self.currentpage.pack() # 显示界面2
root = Tk()
SwitchFrame(root)
root.mainloop()
解释
首先使用了pack布局,用于放置两个Label,在两个Label上分别放置切换Frame的按钮和被切换的Frame。
在第二个Label里放置Frame,这里也用了pack布局,我们要做的就是让两个Frame来回切换。
使用pack_forget方法,先隐去当前Frame再显示另一个Frame,并不是销毁,因为销毁的话如果控件较多比较复杂会造成线程阻塞。
pack布局对应了pack_forget方法隐去,其他两种布局分别是grid_remove和place_forget。