Skip to main content
 首页 » 编程设计

Python之从另一个类调用函数

2025年04月02日17myhome

我刚刚开始学习 Python,我最近阅读了一篇关于使用 tkinter 切换窗口的教程。在本教程中,该人员使用 lambda 从 __init__ 中的按钮内部切换窗口,但我想在切换窗口之前通过一个函数。该函数从 WindowA 类内部运行,需要调用 GLApp 类内部的函数。运行该函数后,如果成功,它应该会打开 WindowB。

如果我尝试从 windowA 中的函数内部调用 show_frame,则会出现此错误。

--controller is not defined 

谁能解释一下实际从 windowA 函数内部调用 show_frame 函数背后的思考过程,我将不胜感激!

class GLApp(tk.Tk): 
 
    def __init__(self, *args, **kwargs): 
 
            self.frames = {} 
 
        for F in (WindowA, WindowB): 
 
            frame = F(container, self) 
 
            self.frames[F] = frame 
 
            frame.grid(row=0, column=0, sticky="nsew") 
 
        def show_frame(self, cont): 
            frame = self.frames[cont] 
            frame.tkraise() 
 
 
class windowA(tk.Frame): 
 
    def __init__(self, parent, controller): 
 
        tk.Frame.__init__(self,parent) 
 
        #window styling and function calling 
 
        self.attempt_login = tk.Button(self,text="Login",command= self.function) 
 
        def function(self): 
 
             try: 
 
                trysomething 
 
             else: 
 
                controller.show_frame(WindowB) 

请您参考如下方法:

本教程没有告诉您的是,您应该保存一个 Controller 实例,以便您可以在页面类的每个函数中使用它。要查看为教程复制的原始代码,请参阅 https://stackoverflow.com/a/7557028/7432

在其中您会看到每个页面类所做的第一件事就是保存 Controller 。一旦你这样做了,你就可以在页面类的任何地方使用 self.controller。

此外,在您的代码中,您将 function 嵌套在 __init__ 中。在这种情况下根本没有理由这样做。将函数移出一层,这样写:

class windowA(tk.Frame): 
    def __init__(self, parent, controller): 
        tk.Frame.__init__(self,parent) 
        self.controller = controller 
        ... 
 
    def function(self): 
         try: 
            trysomething 
         else: 
            self.controller.show_frame(WindowB)