Search code examples
pythontkintertoplevel

How can I store data on Toplevel?


On the toplevel window, if the toplevel is closed after get some input from the user using the entry widget, and then the same toplevel is opened by pressing the same button, is there a way to see the entry we received from the user in the entry widget?

For example user enter his name on toplevel window, and close the toplevel.Then the user open same toplevel,i want it to see his name in the entry widget.


Solution

  • Try this:

    import tkinter as tk
    
    last_user_input_entry = ""
    last_user_input_button = 0
    
    def on_closing():
        global entry, top, last_user_input_entry, last_user_input_button, button_var
        text = entry.get()
        last_user_input_entry = text
        last_user_input_button = button_var.get()
        print("The text entered =", last_user_input_entry)
        print("Checkbutton state =", last_user_input_button)
        top.destroy()
    
    def start_top():
        global entry, top, button_var
        top = tk.Toplevel(root)
        top.protocol("WM_DELETE_WINDOW", on_closing)
    
        entry = tk.Entry(top)
        entry.pack()
        entry.insert("end", last_user_input_entry)
    
        button_var = tk.IntVar()
        button_var.set(last_user_input_button)
        button = tk.Checkbutton(top, variable=button_var)
        button.pack()
    
    root = tk.Tk()
    button = tk.Button(root, text="Open toplevel", command=start_top)
    button.pack()
    
    root.mainloop()
    

    Basically we intercept the window closing and handle that our self. We also have a variable that stored the last user input and we put it in the tkinter.Entry after we create it.