2016-12-26 42 views
0

我在Tkinter中创建了一个向导。几乎每个步骤都应该使用导航和取消按钮。我怎样才能做到这一点?我应该创建一个框架?一般来说,所有的步骤是否应该创建为不同的框架?在Tkinter中创建向导

+0

真不明白,你能告诉更多的你的向导是如何组织和接口的样子,也究竟是页脚中的作用?按钮的功能似乎已经显而易见了。 –

+1

请参见[在tkinter中的两个帧之间切换](http://stackoverflow.com/questions/7546050/switch-between-two-frames-in-tkinter)。它使用'Frame'来创建'Pages' - 你可以以相同的方式使用Frame或者使用Frame来创建带有按钮的widget(并且放置其他元素),然后使用这个widget来构建Pages。 – furas

回答

1

这个问题的答案与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> 

其他步骤将是在概念上相同:框架与一群小部件。

您的主程序或您的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() 

的功能nextback的定义,和finish是非常直接的:只需要调用self.show_step(x)其中x是应该示出的步骤的数量。例如,next可能是这样的:

def next(self): 
    self.show_step(self.current_step + 1) 
+0

谢谢,1)脚注,几乎所有的步骤应该分享? 2)我应该在哪里创建'root = Tk()'? – Jodooomi

+0

@Jodooomi:“footer”是'self.button_frame'。你可以把任何你想要的东西放在那里,或者创建多个页脚或标题或任何你想要的东西。无论何时何地,您都可以像通常那样创建根窗口。 –

+0

是的,我应该在哪里创建根,你能告诉我吗?在“主”? – Jodooomi