这个问题的答案与Switch between two frames in tkinter 没有太大区别。唯一显着的区别是您希望底部有一组永久按钮,但那里没有什么特别的事情要做 - 只需创建一个带有一些按钮的框架,作为包含各个页面(或步骤)的小部件的兄弟。
我建议为从Frame 继承的每个向导步骤创建一个单独的类。然后只需删除当前步骤的框架并显示下一步的框架即可。
例如,一个步骤可能看起来像这样(使用 python 3 语法):
class Step1(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
header = tk.Label(self, text="This is step 1", bd=2, relief="groove")
header.pack(side="top", fill="x")
<other widgets go here>
其他步骤在概念上是相同的:一个带有一堆小部件的框架。
您的主程序或您的向导类将根据需要实例化每个步骤,或者提前将它们全部实例化。然后,您可以编写一个以步数为参数的方法,并相应地调整 UI。
例如:
class Wizard(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.current_step = None
self.steps = [Step1(self), Step2(self), Step3(self)]
self.button_frame = tk.Frame(self, bd=1, relief="raised")
self.content_frame = tk.Frame(self)
self.back_button = tk.Button(self.button_frame, text="<< Back", command=self.back)
self.next_button = tk.Button(self.button_frame, text="Next >>", command=self.next)
self.finish_button = tk.Button(self.button_frame, text="Finish", command=self.finish)
self.button_frame.pack(side="bottom", fill="x")
self.content_frame.pack(side="top", fill="both", expand=True)
self.show_step(0)
def show_step(self, step):
if self.current_step is not None:
# remove current step
current_step = self.steps[self.current_step]
current_step.pack_forget()
self.current_step = step
new_step = self.steps[step]
new_step.pack(fill="both", expand=True)
if step == 0:
# first step
self.back_button.pack_forget()
self.next_button.pack(side="right")
self.finish_button.pack_forget()
elif step == len(self.steps)-1:
# last step
self.back_button.pack(side="left")
self.next_button.pack_forget()
self.finish_button.pack(side="right")
else:
# all other steps
self.back_button.pack(side="left")
self.next_button.pack(side="right")
self.finish_button.pack_forget()
函数next、back 和finish 的定义非常简单:只需调用self.show_step(x),其中x 是应显示的步骤编号。例如,next 可能如下所示:
def next(self):
self.show_step(self.current_step + 1)