如何在tkinter中切换两个框架?
我刚开始写了一些带有漂亮小界面的脚本,跟教程里教的一样,但没有一个教程告诉我,怎么处理更复杂的程序。
比如说,如果你有一个“开始菜单”,作为你的开场画面,用户选择后你需要切换到程序的不同部分,并且相应地重新绘制界面,这样做的优雅方法是什么呢?
是直接用 .destroy()
方法把“开始菜单”的框架删掉,然后再创建一个新的框架,里面放上另一个部分的控件吗?当用户按下返回按钮时,再把这个过程反过来做?
4 个回答
注意: 根据JDN96的说法,下面的答案可能会导致内存泄漏,因为它会反复销毁和重新创建框架。不过,我自己没有测试过来验证这一点。
在tkinter
中切换框架的一种方法是先销毁旧的框架,然后用新的框架替换它。
我对Bryan Oakley的答案进行了修改,先销毁旧框架再替换它。额外的好处是,这样就不需要一个container
对象了,可以使用任何通用的Frame
类。
# Multi-frame tkinter application v2.3
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Open page one",
command=lambda: master.switch_frame(PageOne)).pack()
tk.Button(self, text="Open page two",
command=lambda: master.switch_frame(PageTwo)).pack()
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
class PageTwo(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
解释
switch_frame()
的工作原理是接受任何实现了Frame
的类对象。这个函数会创建一个新的框架来替换旧的框架。
- 如果旧的
_frame
存在,就删除它,然后用新的框架替换。 - 用
.pack()
添加的其他框架,比如菜单栏,不会受到影响。 - 可以与任何实现了
tkinter.Frame
的类一起使用。 - 窗口会自动调整大小以适应新的内容。
版本历史
v2.3
- Pack buttons and labels as they are initialized
v2.2
- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.
v2.1.1
- Remove type-hinting for backwards compatibility with Python 3.4.
v2.1
- Add type-hinting for `frame_class`.
v2.0
- Remove extraneous `container` frame.
- Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
- Frame switching is now done with `master.switch_frame()`.
v1.6
- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.
v1.5
- Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
- Initializing the frame before calling `.destroy()` results
in a smoother visual transition.
v1.4
- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
- Remove `new_frame` variable.
v1.3
- Rename `parent` to `master` for consistency with base `Frame` class.
v1.2
- Remove `main()` function.
v1.1
- Rename `frame` to `_frame`.
- Naming implies variable should be private.
- Create new frame before destroying old frame.
v1.0
- Initial version.
这里有一个简单的答案,不过没有使用类。
from tkinter import *
def raise_frame(frame):
frame.tkraise()
root = Tk()
f1 = Frame(root)
f2 = Frame(root)
f3 = Frame(root)
f4 = Frame(root)
for frame in (f1, f2, f3, f4):
frame.grid(row=0, column=0, sticky='news')
Button(f1, text='Go to frame 2', command=lambda:raise_frame(f2)).pack()
Label(f1, text='FRAME 1').pack()
Label(f2, text='FRAME 2').pack()
Button(f2, text='Go to frame 3', command=lambda:raise_frame(f3)).pack()
Label(f3, text='FRAME 3').pack(side='left')
Button(f3, text='Go to frame 4', command=lambda:raise_frame(f4)).pack(side='left')
Label(f4, text='FRAME 4').pack()
Button(f4, text='Goto to frame 1', command=lambda:raise_frame(f1)).pack()
raise_frame(f1)
root.mainloop()
一种方法是把多个框架(frames)叠在一起,然后你可以简单地把其中一个框架抬高,这样它就会在最上面,变得可见。这个方法最适合所有框架大小相同的情况,不过只要稍微动动脑筋,任何大小的框架也能做到。
注意:为了让这个方法有效,页面上的所有小部件(widgets)必须有这个页面(也就是 self
)或者它的子类作为父级(或者说主控,根据你喜欢的术语来)。
这里有一个稍微复杂一点的例子,来帮助你理解这个概念:
try:
import tkinter as tk # python 3
from tkinter import font as tkfont # python 3
except ImportError:
import Tkinter as tk # python 2
import tkFont as tkfont # python 2
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is the start page", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.pack()
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 1", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
如果你觉得在类中创建实例这个概念有点混乱,或者不同的页面在构建时需要不同的参数,你可以明确地分别调用每个类。循环的主要作用是说明每个类是相同的。
例如,如果你想单独创建这些类,可以去掉循环(for F in (StartPage, ...)
),用下面的方式:
self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)
self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")
随着时间的推移,人们使用这段代码(或者复制了这段代码的在线教程)作为起点提出了其他问题。你可能想看看这些问题的答案: