【发布时间】:2018-01-15 17:37:32
【问题描述】:
我正在查看passing-functions-parameters-tkinter-using-lambda 的代码,并且需要在他的类 PageOne(tk.Frame) 中提供更多功能。而不是使用下面的 lambda 命令(就像他所做的那样):
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))`
我希望能够创建一个内部具有 if/then 层次结构的函数...特别是检查 PageOne 上的所有其他输入是否已首先完成(然后我知道该怎么做)允许换帧。
如果这可以使用 lambda 单独完成,那就更好了。谁能帮帮我?
更新:使用 Bryan 的建议并重新格式化他链接的原始代码,我现在有了:
class App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "APP") #window heading
self.title_font = tkfont.Font(family='Helvetica', size=12) #options: weight="bold",slant="italic"
container = tk.Frame(self) #container = stack of frames; one on top is visible
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):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame #puts all pages in stacked order
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"))
button1.pack()
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
####FIX PART 1####
self.next1 = tk.Button(self,text="Next",padx=18,highlightbackground="black",
command=lambda: self.maybe_switch("PageTwo"))
self.next1.grid(row=10,column=1,sticky='E')
####FIX PART 2####
def maybe_switch(self, page_name):
if ###SOMETHING###:
self.controller.show_frame(page_name)
if __name__ == "__main__":
app = App()
app.mainloop()
【问题讨论】:
-
最好在 FSM(有限状态机)中实现所有控制器逻辑,并且附加到
command事件的回调将自然是 FSM/控制器的事件。这将保证您的代码没有错误。因此,lambda 只会将事件“发送”到 FSM -
@[Nae] 我已经在上面更新了; Bryan 在回复中的最后一次编辑已修复
标签: python python-3.x tkinter