1

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.

1 Answers1

2

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.

TheLizzard
  • 7,248
  • 2
  • 11
  • 31
  • I want to keep the user's input on toplevel when the toplevel is closed. I do not want to print. When the user opens the toplevel again, I want it to see the entry he entered before. – simonkerike Feb 27 '21 at 21:36
  • @simonkerike I edited my answer. Is that better? – TheLizzard Feb 27 '21 at 21:56
  • Thanks, it works! Do you know how to do this for checkbuttons? – simonkerike Feb 28 '21 at 10:24
  • @simonkerike Do you want to have a check button instead of a button on the main window? – TheLizzard Feb 28 '21 at 10:33
  • No, I mean checkbutton instead of entry widget. The user could see the selections made before closing the toplevel when the toplevel is opened again. – simonkerike Feb 28 '21 at 13:21
  • @simonkerike changed code to also show a check button. Btw it is the same idea but now you need a tkinter variable (I used `tkinter.IntVar`) – TheLizzard Feb 28 '21 at 18:33