我是oop的新手,我想要一些帮助。我使用lambda来初始化更改框架的过程,但是我无法在类中使用函数(方法)中的lambda。
这是通常用于更改为食堂页面的lambda:
lambda: controller.show_frame(CanteenPage)
我一直在使用本教程: https://www.youtube.com/watch?v=jBUpjijYtCk&t=4s&list=PLQVvvaa0QuDclKx-QpC9wntnURXVJqLyk&index=4
原始版代码:Switch between two frames in tkinter
代码:
import tkinter as tk
from tkinter import ttk
class CashlessService(tk.Tk):
def __init__(self, *args, **kwards):
tk.Tk.__init__(self, *args, **kwards)
tk.Tk.wm_title(self, "CashlessService")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for i in (LoginPage, CanteenPage, AdminPage, StudentPage):
frame = i(container, self)
self.frames[i] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(LoginPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class LoginPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#Button to confirm ID and password
ttk.Button(self, text="Login", command=self.LoginCheck).grid(row=4, column=1)
def LoginCheck(self):
login = True
if login == True:
lambda: controller.show_frame(CanteenPage)
class CanteenPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="canteen?", font=LARGE_FONT)
label.pack(pady=10, padx=10)
很抱歉,长时间的请求,我已经坚持了好几个小时。
P.S没有出现错误信息
答案 0 :(得分:1)
您需要保存对控制器的引用,然后直接调用它。
class LoginPage(tk.Frame):
def __init__(self, parent, controller):
self.controller = controller
...
def LoginCheck(self):
...
if login == True:
self.controller.show_frame(CanteenPage)