Not able to access a variable (created in a child frame) from the root window

Question:

I am trying to create an application where the user enters a directory name and it gets printed in the console. For this I have created 2 classes:

class FolderInputFrame(tk.Frame):
    ## child frame class
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self._widgets()
        self.pack()

    def _widgets(self):        
        self.directory = tk.StringVar()

        buttonDir = tk.Button(self, text = 'Source Directory: ', command = self.browse_button)
        buttonDir.pack(side = 'left', padx = 10, pady = 10)
        
        dirEntry = tk.Entry(self, textvariable = self.directory, width = 70)
        dirEntry.pack(side = 'left', padx = 10, pady = 10)

    def browse_button(self):
        dirname = filedialog.askdirectory(initialdir='/', title='Please select a directory')
        self.directory.set(dirname)
        print(self.directory.get())      ## directory string from child class

class MainWindow(tk.Tk):
    ## root class
    def __init__(self):
        tk.Tk.__init__(self)
        self.folder_input_container  = FolderInputFrame(self)
        print(self.folder_input_container.directory.get())     ## directory string from root class

Now when I am trying to print the directory string from the 2 classes, the child class shows the appropriate directory entered, but the root class shows an empty output. I am confused why this is happening? I am fairly new to Tkinter, so any help is appreciated here.

I was expecting the strings from both root and child class should have been same after the button is pressed. I need to know how the flow of control is happening here.

Asked By: SayanB6292

||

Answers:

You need to access the data from the instance of the FolderInputFrame since that is the class that created the variable:

print(self.folder_input_container.directory.get())

You need to make sure you do this after the user has clicked the button. In your example you’re attempting to print the value immediately after creating the instance of FolderInputFrame.

Use this modified version of MainWindow to see that the value has been updated. After selecting the directory, click the "Show Directory" button to have it print the value to the console.

class MainWindow(tk.Tk):
    ## root class
    def __init__(self):
        tk.Tk.__init__(self)
        self.folder_input_container  = FolderInputFrame(self)
        button = tk.Button(self, text="Print Directory", command=self.print_directory)
        button.pack()

    def print_directory(self):
        print(f"directory: {self.folder_input_container.directory.get()}")
Answered By: Bryan Oakley
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.