How to avoid global variables in a dynamically gen. tkinter form? Values inserted by functions won't save, hand typed values will after code change How to avoid global variables in a dynamically gen. tkinter form? Values inserted by functions won't save, hand typed values will after code change tkinter tkinter

How to avoid global variables in a dynamically gen. tkinter form? Values inserted by functions won't save, hand typed values will after code change


From what I can tell, this is what I can say.

With what the code is (global entry_objects is uncommented), everything is okay. When the save_file function runs, the entry_objects variable is set to the updated value and gives the correct data.

When the build_form function is run with the return statement, the open_file function isn't updated to take build_file as a value, rather it expects it to be a statement.

def open_file():    # this, save_file are just substitutes.    test_data = [['a1', 'a2', 'a3'],['b1', 'b2', 'b3'],['c1', 'c2', 'c3']]    build_form(test_data)    # this does nothing

What it should need to include the global statement (because it's changing a value outside the function) global entry_objects and it needs to set entry_objects to the value the build_form function gives, meaning entry_objects = build_form(test_data). Here's what the updated function looks like:

# updated open_file for when build_form returns a value rather than changing the value by itselfdef open_file():    # this makes changes to entry_objects visible to things outside the function    global entry_objects    test_data = [['a1', 'a2', 'a3'],['b1', 'b2', 'b3'],['c1', 'c2', 'c3']]    entry_objects = build_form(test_data)    # this sets the returned value to entry_objects

Basically what I'm saying (in this large jumble of words) is that entry_objects will have to be changed and the only way to make that change and project the updated value to all other calls of that variable is to use global and make all changes to entry_objects visible to everything else, including the

save_btn = tk.Button(    button_frame, text='Save',    command=lambda: save_file(entry_objects)).pack(side='left')

at the end.

Just a tiny tip, try to wrap your lines to 74 characters as it helps others with small screens see the whole picture rather than scrolling around :)

If I wasn't clear, feel free to tell me what I needed to explain more on. Great work on that form too :D