GTK+ Main Loop

GTK+ is event-driven by nature in that actions or procedures are performed when an event occurs within the application. Take for example the ‘Hello World’ application from earlier:

#!/usr/bin/env python3

from gi.repository import Gtk

class HelloWorld:
    def close_hello_world(self, widget):
        Gtk.main_quit()

    def print_hello_world(self, widget):
        print("Hello World")

    def __init__(self):
        window = Gtk.Window()
        window.connect("destroy", self.close_hello_world)

        button = Gtk.Button("Click here")
        button.connect("clicked", self.print_hello_world)
        window.add(button)

        window.show_all()

HelloWorld()
Gtk.main()

Download: GTK+ Main Loop 1

After the HelloWorld() class has run, the application loops in the Gtk.main() line of code. This loop waits for an event in the application to occur such as a click, drag-and-drop, or any other number of events.

A Python application can either work as standalone or part of another application. However, if the application is being used as part of another, the GTK+ Main Loop position will cause a problem as it stands. Therefore, we only need to allow the Main Loop to run if the application is running standalone. We will need to change the code to the following:

#!/usr/bin/env python3

from gi.repository import Gtk

class HelloWorld:
    def close_hello_world(self, widget):
        Gtk.main_quit()

    def print_hello_world(self, widget):
        print("Hello World")

    def __init__(self):
        window = Gtk.Window()
        window.connect("destroy", self.close_hello_world)

        button = Gtk.Button("Click here")
        button.connect("clicked", self.print_hello_world)
        window.add(button)

        window.show_all()

if __name__ == "__main__":
    HelloWorld()
    Gtk.main()

Download: GTK+ Main Loop 2