我正在查看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()
答案 0 :(得分:0)
你不应该在lambda中加入任何逻辑。只需创建一个具有所需逻辑的普通函数,然后从按钮中调用它。这真的没那么复杂了。
class SomePage(...):
def __init__(...):
...
button1 = tk.Button(self, text="Back to Home",
command=lambda: self.maybe_switch_page(StartPage))
...
def maybe_switch_page(self, destination_page):
if ...:
self.controller.show_frame(destination_page)
else:
...
如果您想要更通用的解决方案,请将逻辑移至show_frame
,并让它在当前页面上调用方法以验证是否可以切换。
例如:
class Controller(...):
...
def show_frame(self, destination):
if self.current_page is None or self.current_page.ok_to_switch():
# switch the page
else:
# don't switch the page
然后,这只是在每个页面类中实现ok_to_switch
的问题。