【问题标题】:python Tkinter calling class methods from button presspython Tkinter从按钮按下调用类方法
【发布时间】:2016-05-12 14:04:15
【问题描述】:

我正在使用 Tkinter 创建一个 GUI。我有一个用于设置所有 GUI 元素的类和另一个执行某些功能的类。

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()

上面的代码是调用其他类方法的正确方法,还是我应该在 GUI 的 __init__ 方法中实例化该类?还是别的什么?

【问题讨论】:

    标签: python class tkinter


    【解决方案1】:

    在这种特定情况下,您应该在 GUI.__init__ 中实例化它,除非有理由需要在他们每次单击按钮时创建一个新实例。

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

    【讨论】:

      【解决方案2】:

      除非您每次按下按钮都需要一个新的类实例(在您的示例中似乎不是这种情况),否则您应该在 init 中实例化它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-21
        • 1970-01-01
        • 2013-04-11
        • 2022-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-21
        相关资源
        最近更新 更多