[Solved] python variables between functions


Working example with global variable and two windows.

It uses only one mainloop() and Toplevel() to create second window.

import tkinter as tk

# --- functions ---

def main():
    #inform function to use external/global variable
    global int_var # only if you will use `=` to change value

    root = tk.Tk()
    root.title("Root")

    # change global variable using `=`
    int_var = tk.IntVar()

    # use global variable
    e = tk.Entry(root, textvariable=int_var)
    e.pack()

    tk.Button(root, text="Second", command=second).pack(fill="x")
    tk.Button(root, text="Exit", command=root.destroy).pack(fill="x")

    root.mainloop()


def second():
    #inform function to use external/global variable
    #global int_var # only if you will use `=` to change value

    other = tk.Toplevel()
    other.title("Other")

    # use global variable
    l = tk.Label(other, textvariable=int_var)
    l.pack()

    tk.Button(other, text="Exit", command=other.destroy).pack()

    #other.wait_window()

# --- start ---

# create global variable
int_var = None

main()

solved python variables between functions