Search code examples
python-3.xgtk3

pygtk+: How to display a second image 3 seconds after the first?


I am writing a pygtk+ program that would allow a user to navigate thru a book by using buttons in a toolbar. On opening the program, I would like to display a "title" or "cover page" image for a few seconds while the GUI is completed. Then a background image would be displayed. This script only displays the second image after a delay of 3s.

import gi, time
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk

class FirstScrn(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self)

        image = Gtk.Image.new_from_file("../images/first.png")
        self.add(image)
        self.show_all()
        time.sleep(3)
        self.remove(image)
        image = Gtk.Image.new_from_file("../images/second.png")
        self.add(image)
        self.show_all()

first = FirstScrn()
first.connect("delete-event", Gtk.main_quit)

Gtk.main()

How could I achieve the desired effect?


Solution

  • This might be a possible solution:

    import gi, time
    gi.require_version('Gtk', '3.0')
    from gi.repository import Gtk, Gdk, GLib
    
    class FirstScrn(Gtk.Window):
    
        def __init__(self):
            Gtk.Window.__init__(self)
    
            image = Gtk.Image.new_from_file("../images/first.png")
            self.add(image)
            self.show_all()
            GLib.timeout_add_seconds(3, self.show_next_image, image)
    
        def show_next_image (self, previous_image):
            self.remove(previous_image)
            image = Gtk.Image.new_from_file("../images/second.png")
            self.add(image)
            self.show_all()
    
    first = FirstScrn()
    first.connect("delete-event", Gtk.main_quit)
    
    Gtk.main()
    

    Remember, time.sleep will make Gtk unresponsive. And threads don't work either. That is why you use things like timeout_add and idle_add.