You must call a class method from another class without initializing the first class or in any other way

I have a little problem with my code.

There are two classes. First, a window is created with the "Options" button. After clicking the button, the second class is called and another window with the "OK" button is created. Let's say there is also a flag that changes the background color to black or something like that. After clicking the button, all changes made to the parameters are saved in the file, and the second window closes.

It all works great. My problem is that now I need to call the update_init method from the first class, which will apply these changes in MainWindow. The code below shows my first solution to this problem, but from what I understand, using the second mainloop, I create a second thread that should be avoided.

class MainWindow:

    def __init__(self, master):
        self.master = master
        self.options_btn = tk.Button(self.master, text="Options", command=self.open_options)
        self.options_btn.pack()
        self.options_window = None

    def open_options(self):
        options_master = tk.Toplevel()
        self.options_window = OptionsWindow(options_master)
        options_master.mainloop()
        lst = meta_load()   # loads changes from a file
        self.update_init(lst)

    def update_init(self, lst):
        #code


class OptionsWindow:

    def __init__(self, master):
        self.master = master
        self.ok_btn = tk.Button(self.master, text="OK", command=self.update_meta)
        self.ok_btn.pack()

    def update_meta(self):
        meta_save(12)  # saves changes into a file
        self.master.destroy()

main_master = tk.Tk()
main_master.minsize(width=1280, height=720)
b = MainWindow(main_master)
main_master.mainloop()

My second solution was to simply put both classes in one, but the code would be pretty confusing if I do this. Is there any way to call the update_init method (which is in the MainWindow class) from the OptionsWindow class without initializing a new window for the MainWindow class? Or is there any other way to handle this? I would appreciate any help.

, , , , .

+4
1

, , , - , python, self! , , .

class A:
    def __init__(self):
        self.foo = 'foo'

    def return_foo(self):
        return self.foo


class B:
    def __init__(self):
        self.bar = 'bar'
        print('Ha-ha Im inited!')

    def return_bar(self):
        try:
            return self.bar
        except AttributeError:
            return 'bar'


def test():
    a = A()
    # b = B()
    return_bar = getattr(B, 'return_bar', None)
    if callable(return_bar):
        print('%s%s' % (a.return_foo(), return_bar(None)))


test()

:

0

Source: https://habr.com/ru/post/1674304/


All Articles