【问题标题】:Accessing class methods from another class in Python 2.7在 Python 2.7 中从另一个类访问类方法
【发布时间】:2013-05-06 11:51:57
【问题描述】:

我正在为一项作业编写 Tkinter GUI,但在访问类方法时遇到了一些问题。我在这里粘贴的第一段代码是顶级接口类。代码的主要功能是创建这个类的一个实例,其中“master”是和 Tk() 的实例。

class PlotApp(object):
    """
    Top level interface. Contains canvas and other widgets.
    """

    def __init__(self, master):

        # Initialise variables, world screen class and window features
        master.wm_minsize(740, 480)
        master.configure(bg = "gray80")
        self.isFunctionDrawn = False           

        # Create objects
        self.pointf = PointFrame(master)
        self.canvas = Canvas(master, bg = "white", bd = 2, relief = SUNKEN,
                             highlightbackground = "gray80")
        self.canvas.pack(expand = True, fill = BOTH, padx = 10, side = TOP)
        self.functionf = FunctionFrame(master)
        self.plotf = PlotFrame(master)
        self.buttonf = ButtonFrame(master, self.canvas)

self.functionf 是我的FunctionFrame 类的一个实例,其中包含一个名为getFunction() 的方法。我想要ButtonFrame 类实例中的一个按钮来访问此方法,但我不知道该怎么做。我试过了:

def testFunction(self):
    self.parent.functionf.getFunction()

(其中parent 是代码第一位中的master 参数)但这似乎将functionf 作为Tk() 的对象调用,这显然是行不通的。有没有办法解决这个问题?

【问题讨论】:

    标签: python class python-2.7 tkinter


    【解决方案1】:

    master 是你的 Tk() 实例。仅仅因为您在 ButtonFrame 类中调用了变量 parent 并不意味着它是创建实例的对象。

    您需要将 selfPlotApp 作为父级传递(如果您需要在 ButtonFrame 中使用 master 对象,请将 master 保存在 self.master 中的 PlotApp 中),或者您需要还将您的PlotApp 实例的self 变量传递给您的ButtonFrame

    【讨论】:

      猜你喜欢
      • 2022-12-05
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 2015-01-21
      • 2017-05-12
      • 1970-01-01
      • 2017-01-03
      相关资源
      最近更新 更多