Nurol Alacaatli
Nurol Alacaatli

Reputation: 101

calling a method from tkinter class

I'm very new on Python and trying to develop a fake data generator software for data scientists to be able to learn faster. My question is about how we can call a method from a sub method between tkinter object classes. I have root class which creates root window and toplevel class which creates toplevel (sub-window). My sub-window class needs to update a widget in root window and I couldn't have done it.

enter code here

class Menu():
    def __init__(self,master):
    ....
    def openwindow(self):
        secondwindow = my_sub_window(root)
    def dosomething(self):
        ....

class my_sub_window():
    def __init__(self, master):
        update_root()
    def update_root(self):
        dosomething()  # How can I call dosomething method in Menu() class?

root = Tk()
myApp = Menu(root)
root.mainloop()

Upvotes: 0

Views: 507

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386362

In your specific case, you would call the function based off of the global myApp class:

class my_sub_window():
    def update_root(self):
       myApp.dosomething()

Though, it's generally not a good idea to rely on global variables like this. The most common solution is to pass the instance of Menu to the my_sub_window class.

Example:

class Menu():
    def openwindow(self):
        secondwindow = my_sub_window(root)
        ...

class my_sub_window():
    def __init__(self, root):
        self.root = root
    def update_root(self):
        self.root.dosomething()

Upvotes: 1

Related Questions