Last active
January 5, 2023 15:48
-
-
Save fikr4n/2fd9de1d2f79720c4e2a to your computer and use it in GitHub Desktop.
Interactive Python interpreter to play with GTK+ without blocking the console
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
"""An interactive Python interpreter to play with GTK+ without blocking the console | |
Usage: | |
./pygigtk.py | |
You don't need to call 'Gtk.main' in the console, just start using Gtk, such as | |
creating a window and 'show_all' it. Gtk, GObject, etc have been imported. | |
Author: fikr4n <github.com/fikr4n> | |
""" | |
import threading | |
import code | |
import readline | |
import rlcompleter | |
from gi.repository import Gtk, Gdk, GObject, GLib | |
class GtkConsole(code.InteractiveConsole): | |
def __init__(self): | |
super().__init__({'__name__': '__console__', '__doc__': __doc__, | |
'Gtk': Gtk, 'Gdk': Gdk, 'GObject': GObject, 'GLib': GLib}) | |
self.event = threading.Event() | |
def runcode(self, code): | |
self.event.clear() | |
GObject.idle_add(self.runcode_sync, code) | |
self.event.wait() | |
def runcode_sync(self, code): | |
super().runcode(code) | |
self.event.set() | |
def gtk_main(): | |
GObject.threads_init() | |
while True: | |
Gtk.main() | |
print('\nMain has quitted, and has just restarted\n' | |
'Just continue playing or Ctrl+D (i.e. EOF) to stop') | |
if __name__ == '__main__': | |
thread = threading.Thread(target=gtk_main, daemon=True) | |
thread.start() | |
readline.set_completer(rlcompleter.Completer(globals()).complete) | |
readline.parse_and_bind('tab: complete') | |
GtkConsole().interact() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment