raltandi
raltandi

Reputation: 97

Python - Calling a function from another class

I JUST started learning about Python, I recently read a tutorial about switching windows using tkinter. In the tutorial, the guy switched windows from inside the button in the __init__ using lambda, but I want to go through a function before switching windows. The function runs from inside Class WindowA and needs to call a function inside class GLApp. After it runs the function, if it is successful, it's supposed to open up WindowB.

I get this error if I try to call show_frame from inside the function in windowA.

--controller is not defined

Can someone please explain the thought process behind actually getting to call the show_frame function from inside the windowA function, I'd appreciate it a bunch!

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)

Upvotes: 2

Views: 1642

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385910

What the tutorial doesn't tell you is that you should save an instance of controller so that you can use it in every function of the page classes. To see the original code that was copied for the tutorial, see https://stackoverflow.com/a/7557028/7432

In it you'll see that one of the first things each page class does is save the controller. Once you do that you can use self.controller anywhere in a page class.

Also, in your code you're nesting function inside of __init__. There is simply no reason to do that in this case. Move the function out one level, and write it like this:

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)

Upvotes: 1

Related Questions