I am doing a simple GUI for Python program. In one function, I want to display a text message for a few seconds and then continue. My code for this part is:
self.message.set_text('This is a message')
time.sleep(3)
self.message_box.destroy()
# call another function
My issue is, the program firstly sleep and then displays the message and continue with destroying the message widget, instead of displaying the message for 3 seconds. I was told GTK is asynchronous and therefore it is better to use threads, however, I think for this simple program (displaying a few buttons and text messages depending on which one was clicked) it would be an overkill.
Is there any possibility how to display text for given time without threading?
You cannot use time.sleep()
because it blocks the gtk main loop. But you are right that threading is an overkill for your use case. You can use glib.timeout_add_seconds()
. This method is actually intended to execute a function every X seconds until it returns False
. If you return None
it won't be called again neither. So this is a simpler approach:
from gi.repository import Gtk, GLib
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self)
self.set_default_size(50, 20)
label = Gtk.Label("test")
self.add(label)
GLib.timeout_add_seconds(3, label.destroy)
win = MyWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()