简体   繁体   中英

Accessing class methods from another class in Python 2.7

I am writing a Tkinter GUI for an assignment and have come to have some problems with accessing class methods. The first bit of code I've pasted in here is the top-level interface class. The main function of the code creates an instance of this class where "master" is and instance of 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 is an instance of my FunctionFrame class, which contains a method called getFunction() . I want a button in the ButtonFrame class instance to access this method, but I don't know how to do this. I've tried:

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

(where parent is the master argument in the first bit of code) but this seems to be calling functionf as an object of Tk() , which obviously isn't going to work. Is there any way around this?

master is your Tk() instance. just because you called the variable parent in your ButtonFrame class doesn't mean it's the object that created the instance.

You need to either pass in self from PlotApp as parent (and if you need your master object in your ButtonFrame, save master in something like self.master in PlotApp ), or you need to also pass in your PlotApp instance's self variable to your ButtonFrame .

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