Python - 从另一个类调用函数

标签 python tkinter

我刚刚开始学习 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)

关于Python - 从另一个类调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37582375/

相关文章:

python - 如何将 Python 的 itertools.product 库从列表理解转换为普通的 for 循环?

python - Django CreateView - 仅显示外键字段中的特定对象

Python3列表切片: specific use in class method

python - 在子包之间共享模块的最佳实践是什么?

python - Tkinter 框架不填充剩余空间

python - 我的模拟时钟项目中笨重/缓慢的拖动功能

python - 如何检查制表符分隔文件中的列是否具有有效值?

python - 如何在不编写类的情况下访问 Tkinter 中按钮的父级?

python - 如何获取组合框中所选项目的索引?

Python/MySQL - 将csv文件导入mysql