Search code examples
pythontkintertkinter-entryclass-variablesgetattr

Can't read entry value from one class's instance to another in Tkinter while reading from the same class's init works fine


I have two classes in my project. One is the GUI and the other makes the calculations. I read data from two Entry boxes from the first and want to pass them to the second. So far, what I do is this:

class OptimizationGUI:
    land_entry = 0
    pop_entry = 0

    def __init__(self, master):
        self.land_entry_text = IntVar()
        self.pop_entry_text = IntVar()

        self.master = master

        OptimizationGUI.land_entry = Entry(master, textvariable=self.land_entry_text)

        self.advanced_options = Button(master, text="Advanced", command=self.advanced)

        self.run = Button(master, text="RUN", command=self.start, bg='black', fg='red', bd=4)


    def advanced(self):
        advanced_window = Toplevel()
        OptimizationGUI.pop_entry = Entry(advanced_window, textvariable=self.pop_entry_text)

    def start(self):
        opt = Optimization()
        method = getattr(opt,'get_result')
        yo = method()

In the above code, I initiate the two as class variables and then I create the Entries. I go from class OptimizationGui to the other with the getattr. The code of the other class is below:

class Optimization():

    def __init__(self):
        self.population = OptimizationGUI.pop_entry.get()
        self.land = OptimizationGUI.land_entry.get()
        print self.population, self.land

The weird thing is, that while it prints the data of land_entry correctly, when it comes to the self.population = OptimizationGUI.pop_entry.get() line, it prints the following error:

AttributeError: 'int' object has no attribute 'get'

The only difference I see between these two is that the pop_entry variable is not in the init function but in the "advanced". What is the way to overcome this?


Solution

  • Call the advanced method inside init:

    def __init__(self, master):
        ...
        self.advanced()
    

    The difference is that the class variable integer 0 land_entry gets overwritten by an Entry object whereas pop_entry isn't overwritten, as advanced is the part that overwrites it and it is never called.