在Python 2.7中从另一个类访问类方法

时间:2013-05-06 11:51:58

标签: python class python-2.7 tkinter

我正在为一项作业编写一个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()的对象,显然不是'去上班。有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:0)

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

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

相关问题