我正在使用Tkinter创建向导(Wizard)。在几乎每个步骤中,我都需要相同的页脚,包含用于导航和取消的按钮。我应该怎样实现这个功能呢?我需要创建一个框架(Frame)吗?通常情况下,所有步骤都应该创建为不同的框架(Frame)吗?
我建议为每个向导步骤创建一个单独的类,该类继承自 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>
其他步骤在概念上是相同的:一个带有一堆小部件的框架。
你的主程序或Wizard类将根据需要实例化每个步骤,或者提前实例化它们全部。然后,你可以编写一个方法,该方法以步骤编号作为参数,并相应地调整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)
root = Tk()
? - Jodooomiself.button_frame
。您可以在其中放置任何想要的内容,或创建多个页脚、页眉或任何您想要的东西。您可以像通常一样在任何时间/地点创建根窗口。 - Bryan Oakley
Frame
来创建Pages
- 您可以以相同的方式使用Frame
或使用Frame
创建带有按钮(和其他元素的位置)的小部件,然后使用此小部件构建Pages
。 - furas