python tkinter waiting for an input to be inputted by user

Question:

I have a code snippet. Entry widget creates itself with text, then waits seconds then destroys itself.

    entry_var_temporary = tk.StringVar()
    entry_var_temporary.set(varsoundTitle_usernameHeroContainer)
    entry_shtname_temp=tk.Entry(canvas2,width=30,textvariable=entry_var_temporary)
    entry_shtname_temp.pack()
    entry_shtname_temp.focus_set()
    root.update()
    time.sleep(10)
    entry_shtname_temp.destroy()
    root.update()

I have put 10 seconds to wait, and let user to modify the text, if it wants so. But as I see, time.sleep does not let the entry widget to be modified.
How can I get around this problem?
With wait.window() I realized I can edit text inside widget, but my problem is, it is not compulsory. So, if user doesn’t put any text on it, it then after 10 sec needs to be destroyed

Asked By: xlmaster

||

Answers:

Use the after method with the destroy method as the callback.

The main reason to use root.after vs time.sleep is the time.sleep stops the thread causing the code to completely stop compared to root.after which is thread-safe because it is implemented in terms of call.

Your widget will destroy itself automatically after a set amount of time.

for example:

import tkinter as tk


root = tk.Tk()

entry_var_temporary = tk.StringVar()
entry = tk.Entry(root,  textvariable=entry_var_temporary)
entry.pack()
root.after(10000, entry.destroy)  # 10000 milliseconds
root.mainloop()
Answered By: Alexander

This seems to be an extension of a previous question you asked. You only need to add one more line of code to that example in order to automatically delete the entry widget after 10 seconds.

In the following example, notice how I use after to destroy the window in 10 seconds. This call must be done before waiting for the window. This is the example I gave in your previous question, with just that one new statement added:

entry_var = tk.StringVar()
new_sheetname_entryBox=tk.Entry(canvas2,width=30, textvariable=entry_var)
new_sheetname_entryBox.pack()
new_sheetname_entryBox.bind("<Return>", lambda event: new_sheetname_entryBox.destroy())
new_sheetname_entryBox.focus_set()

# wait for the entry widget to be deleted, but automatically
# delete it after 10 seconds if the user doesn't respond.
root.after(10000, new_sheetname_entryBox.destroy)
new_sheetname_entryBox.wait_window()
Answered By: Bryan Oakley
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.