简体   繁体   中英

python Tkinter calling class methods from button press

I am using Tkinter to create a GUI. I have a class for setting up all my GUI elements and another class that does some functionality.

class class_one():

    def method_one(self):
        do_something()

class GUI()

    def __init__(self):
        button = Button(self, text="button", command=call_class_one_method)
        button.pack()

    def call_class_one_method(self):
         c = class_one()
         c.method_one()

Is this above code the correct way for calling other class methods or should I be instantiating the class in the GUI's __init__ method? Or perhaps something else?

In this specific case you should instantiate it in GUI.__init__ unless there's a reason you need to create a new instance every time they click the button.

class GUI()

    def __init__(self):
        self.class_one = class_one()
        button = Button(self, text="button", command=self.class_one.method_one)
        ...

除非您确实需要每次按下按钮时都需要一个新的类实例(在您的示例中似乎并非如此),否则您应该在init 中实例化它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM