0

I am trying to show a tkinter Toplevel window, have the script sleep for one second, then continue running. However, the sleep function always occurs before the toplevel window appears. I'm doing this because I want to show an indication to the user that a label text has been copied on click.

I am planning to have the Toplevel show, sleep for one second, then destroy it. However, as it is currently, the sleep occurs first and then the Toplevelshows and is destroyed immediately too fast for the user to perceive.

Is there a way to have these events happen in my desired order? Here is a script demonstrating what I'm dealing with:

from tkinter import *
from tkinter import ttk
import time

root = Tk()  # Creating instance of Tk class

def make_new_window(event):
    new_window = Toplevel()
    clabel = Label(new_window, text = "Copied")
    clabel.pack()
    time.sleep(1)

l = Label(root, text = "Example text")
l.pack()
l.bind('<1>', make_new_window)

root.mainloop()
martineau
  • 119,623
  • 25
  • 170
  • 301
Elsayeda
  • 19
  • 3
  • 1
    You shouldn't use `time.sleep` when using `tkinter`, use `.after` scripts instead. So basically you can use `clabel.after(1000, new_window.destroy)`, where the 1000 is in milliseconds. – TheLizzard Jul 04 '21 at 23:12
  • Here's some [documentation](https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/universal.html) on the universal widget `after()` method. – martineau Jul 05 '21 at 00:32
  • 1
    Let me explain why this doesn't work. Tkinter, like all GUI frameworks, is event driven. When you create a window or a widget, or update a widget, nothing happens immediately. All that does is send a message to the window. The action only happens when the "main loop" receives and dispatches that message. When you block the thread like this, the main loop isn't running, so no messages are dispatched. You have to think "event driven" to write a successful GUI. – Tim Roberts Jul 05 '21 at 00:36
  • Also see accepted answer to [Tkinter — executing functions over time](https://stackoverflow.com/questions/9342757/tkinter-executing-functions-over-time). – martineau Jul 05 '21 at 13:16

0 Answers0