Search code examples
pythonpython-3.xtkintertoplevel

How do I make modifications to the root window from a sub window in tkinter?


I'm trying to make a sub-window which allows you to alter certain parameters within the main window. I created a function which, when called by a button, will pop up, have an option menu to choose which option you want to alter, then some entry boxes to enter in what you want to alter.

My first thought was to alter the data in the function then just return it, but I didn't think that would work since the function is being called at the touch of a button. Anyone have any recommendations?


Solution

  • Below is a simple example of how one could update the root window directly and any variables in the global namespace. Its just a matter of what you do in the functions you call from you buttons.

    Let me know if you have any questions.

    import tkinter as tk
    
    
    root = tk.Tk()
    root.config(background='white')
    root.geometry('250x100')
    
    label_1 = tk.Label(root, text=0)
    label_1.pack()
    label_2 = tk.Label(root, text='test')
    label_2.pack()
    
    
    def toggle_root_bg():
        # check the color of the root window and toggle accordingly.
        if root['background'] == 'black':
            root.config(background='white')
        else:
            root.config(background='black')
    
    
    def update_root_labels(one, two):
        # Apply argument values to the text fields of the labels defined in the global namespace.
        label_1.config(text=one)
        label_2.config(text=two)
    
    
    def sub_window():
        # setting sub window variable name to be used with other widgets.
        top = tk.Toplevel(root)
        tk.Label(top, text='Provide a number: ').grid(row=0, column=0)
        tk.Label(top, text='Provide a string: ').grid(row=1, column=0)
        entry_1 = tk.Entry(top)
        entry_2 = tk.Entry(top)
        entry_1.grid(row=0, column=1)
        entry_2.grid(row=1, column=1)
    
        # create a sub function to get the current entry field values
        # then pass these values on to our update function.
        def submit_update():
            update_root_labels(entry_1.get(), entry_2.get())
    
        tk.Button(top, text='Update root labels', command=submit_update).grid(row=2, column=0)
        tk.Button(top, text='Toggle Root Background', command=toggle_root_bg).grid(row=3, column=0)
    
    
    tk.Button(root, text='Open sub window', command=sub_window).pack()
    root.mainloop()
    

    Before:

    enter image description here

    After:

    enter image description here