Welcome, guest | Sign In | My Account | Store | Cart

One of pythons greatest strengths is the ability to try things interactively at the interpreter. Using Tkinter shares this strength, since one can create buttons, windows and other widgets, and instantly see them onscreen, click on buttons to activate callbacks and still be able to edit and add to the widgets from the python command line.

While the python GTK bindings are generally excellent, one of their flaws is that this is not possible. Before anything is actually displayed, the gtk.mainloop() function must be called, ending the possibility of interactive manipulation.

This recipe is a program which simulates a python interpreter which transparently allows the user to use gtk widgets without having to call mainloop(), in much the same way as Tk widgets.

This latest version contains enhancements added by Christian Robottom Reis to add readline completion support.

Python, 173 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/usr/bin/env python
import __builtin__
import __main__
import codeop
import keyword
import gtk
import os
import re
import readline
import threading
import traceback
import signal
import sys

def walk_class (klass):
    list = []
    for item in dir (klass.__class__):
        if item[0] != "_":
            list.append (item)

    for base in klass.__class__.__bases__:
        list = list + walk_class (base())

    return list

class Completer:
    def __init__ (self, lokals):
        self.locals = lokals

        self.completions = keyword.kwlist + \
                            __builtins__.__dict__.keys() + \
                            __main__.__dict__.keys()
    def complete (self, text, state):
        if state == 0:
            if "." in text:
                self.matches = self.attr_matches (text)
            else:
                self.matches = self.global_matches (text)
        try:
            return self.matches[state]
        except IndexError:
            return None

    def update (self, locs):
        self.locals = locs

        for key in self.locals.keys ():
            if not key in self.completions:
                self.completions.append (key)

    def global_matches (self, text):
        matches = []
        n = len (text)
        for word in self.completions:
            if word[:n] == text:
                matches.append (word)
        return matches

    def attr_matches (self, text):
        m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
        if not m:
            return
        expr, attr = m.group(1, 3)

        obj = eval (expr, self.locals)
        if str (obj)[1:4] == "gtk":
            words = walk_class (obj)
        else:
            words = dir(eval(expr, self.locals))
            
        matches = []
        n = len(attr)
        for word in words:
            if word[:n] == attr:
                matches.append ("%s.%s" % (expr, word))
        return matches

class GtkInterpreter (threading.Thread):
    """Run a gtk mainloop() in a separate thread.
    Python commands can be passed to the thread where they will be executed.
    This is implemented by periodically checking for passed code using a
    GTK timeout callback.
    """
    TIMEOUT = 100 # Millisecond interval between timeouts.
    
    def __init__ (self):
        threading.Thread.__init__ (self)
        self.ready = threading.Condition ()
        self.globs = globals ()
        self.locs = locals ()
        self._kill = 0
        self.cmd = ''       # Current code block
        self.new_cmd = None # Waiting line of code, or None if none waiting

        self.completer = Completer (self.locs)
        readline.set_completer (self.completer.complete)
        readline.parse_and_bind ('tab: complete')

    def run (self):
        gtk.timeout_add (self.TIMEOUT, self.code_exec)
        gtk.mainloop ()

    def code_exec (self):
        """Execute waiting code.  Called every timeout period."""
        self.ready.acquire ()
        if self._kill: gtk.mainquit ()
        if self.new_cmd != None:  
            self.ready.notify ()  
            self.cmd = self.cmd + self.new_cmd
            self.new_cmd = None
            try:
                code = codeop.compile_command (self.cmd[:-1]) 
                if code: 
                    self.cmd = ''
                    exec (code, self.globs, self.locs)
                    self.completer.update (self.locs)
            except Exception:
                traceback.print_exc ()
                self.cmd = ''  
                                    
        self.ready.release()
        return 1 
            
    def feed (self, code):
        """Feed a line of code to the thread.
        This function will block until the code checked by the GTK thread.
        Return true if executed the code.
        Returns false if deferring execution until complete block available.
        """
        if (not code) or (code[-1]<>'\n'): code = code +'\n' # raw_input strips newline
        self.completer.update (self.locs) 
        self.ready.acquire()
        self.new_cmd = code
        self.ready.wait ()  # Wait until processed in timeout interval
        self.ready.release ()
        
        return not self.cmd

    def kill (self):
        """Kill the thread, returning when it has been shut down."""
        self.ready.acquire()
        self._kill=1
        self.ready.release()
        self.join()
        
# Read user input in a loop, and send each line to the interpreter thread.

def signal_handler (*args):
    print "SIGNAL:", args
    sys.exit()

if __name__=="__main__":
    signal.signal (signal.SIGINT, signal_handler)
    signal.signal (signal.SIGSEGV, signal_handler)
    
    prompt = '>>> '
    interpreter = GtkInterpreter ()
    interpreter.start ()
    interpreter.feed ("from gtk import *")
    interpreter.feed ("sys.path.append('.')")
    if len (sys.argv) > 1:
        for file in open (sys.argv[1]).readlines ():
            interpreter.feed (file)
    print 'Interactive GTK Shell'

    try:
        while 1:
	    command = raw_input (prompt) + '\n' # raw_input strips newlines
            prompt = interpreter.feed (command) and '>>> ' or '... '
    except (EOFError, KeyboardInterrupt): pass

    interpreter.kill()
    print

This works by running the gtk main loop in a seperate thread. The main thread is responsible only for reading lines of input from the user, and passing these on to the gtk thread, which deals with pending lines by activating a timeout.

The resulting program is virtually identical to the python interpreter, except that there is now no need for gtk.mainloop() for Gtk event handling to take place.

3 comments

John Finlay 21 years, 3 months ago  # | flag

This program needs some simple mods to make it work with PyGTK2 and Python 2.2.2. To get this to work with PyGTK2 and Python 2.2.2 I had to make the following changes:

--- gtkpython.py-   Wed Jan 15 20:32:00 2003
+++ gtkpython.py    Wed Jan 15 14:00:35 2003
@@ -3,7 +3,6 @@
 import __main__
 import codeop
 import keyword
-import gtk
 import os
 import re
 import readline
@@ -11,6 +10,10 @@
 import traceback
 import signal
 import sys
+if sys.version[0] == '2':
+    import pygtk
+    pygtk.require("2.0")
+import gtk

 def walk_class (klass):
     list = []
@@ -28,8 +31,8 @@
         self.locals = lokals

         self.completions = keyword.kwlist + \
-                            __builtins__.__dict__.keys() + \
-                            __main__.__dict__.keys()
+                           __builtin__.__dict__.keys() + \
+                           __main__.__dict__.keys()
     def complete (self, text, state):
         if state == 0:
             if "." in text:
@@ -98,6 +101,11 @@

     def run (self):
         gtk.timeout_add (self.TIMEOUT, self.code_exec)
+        try:
+            if gtk.gtk_version[0] == 2:
+                gtk.gdk.threads_init()
+        except:
+            pass
         gtk.mainloop ()

     def code_exec (self):
Guilherme Salgado 19 years, 5 months ago  # | flag

Tab not working in gtk objects. I don't know why that walk_class() function was created, but using it I wasn't able to do something like this:

>>> w = gtk.Window()
>>> w.sh&lt;Tab&gt;

to see the gtk.Window methods that start with "sh".

The following patch fixes this, together with some cosmetic changes.

--- pygtk-console-old.py    2004-10-26 21:03:20.732813616 -0300
+++ pygtk-console.py        2004-10-26 20:42:36.893905872 -0300
@@ -10,22 +10,12 @@ import threading
 import traceback
 import signal
 import sys
+import string
 if sys.version[0] == '2':
     import pygtk
     pygtk.require("2.0")
 import gtk

-def walk_class (klass):
-    list = []
-    for item in dir (klass.__class__):
-        if item[0] != "_":
-            list.append (item)
-
-    for base in klass.__class__.__bases__:
-        list = list + walk_class (base())
-
-    return list
-
 class Completer:
     def __init__ (self, lokals):
         self.locals = lokals
@@ -66,10 +56,7 @@ class Completer:
         expr, attr = m.group(1, 3)

         obj = eval (expr, self.locals)
-        if str (obj)[1:4] == "gtk":
-            words = walk_class (obj)
-        else:
-            words = dir(eval(expr, self.locals))
+        words = dir(eval(expr, self.locals))

         matches = []
         n = len(attr)
@@ -79,7 +66,7 @@ class Completer:
         return matches

 class GtkInterpreter (threading.Thread):
-    """Run a gtk mainloop() in a separate thread.
+    """Run a gtk main() in a separate thread.
     Python commands can be passed to the thread where they will be executed.
     This is implemented by periodically checking for passed code using a
     GTK timeout callback.
@@ -106,12 +93,12 @@ class GtkInterpreter (threading.Thread):
                 gtk.gdk.threads_init()
         except:
             pass
-        gtk.mainloop ()
+        gtk.main()

(comment continued...)

Guilherme Salgado 19 years, 5 months ago  # | flag

(...continued from previous comment)

     def code_exec (self):
         """Execute waiting code.  Called every timeout period."""
         self.ready.acquire ()
-        if self._kill: gtk.mainquit ()
+        if self._kill: gtk.main_quit ()
         if self.new_cmd != None:
             self.ready.notify ()
             self.cmd = self.cmd + self.new_cmd
@@ -164,16 +151,21 @@ if __name__=="__main__":
     prompt = '>>> '
     interpreter = GtkInterpreter ()
     interpreter.start ()
-    interpreter.feed ("from gtk import *")
+    interpreter.feed ("import gtk")
     interpreter.feed ("sys.path.append('.')")
     if len (sys.argv) > 1:
         for file in open (sys.argv[1]).readlines ():
             interpreter.feed (file)
     print 'Interactive GTK Shell'
+    py_version = string.join(map(str, sys.version_info[:3]), '.')
+    pygtk_version = string.join(map(str, gtk.pygtk_version), '.')
+    gtk_version = string.join(map(str, gtk.gtk_version), '.')
+    print 'Python %s, Pygtk %s, GTK+ %s' % (py_version, pygtk_version,
+           gtk_version)

     try:
         while 1:
-       command = raw_input (prompt) + '\n' # raw_input strips newlines
+            command = raw_input (prompt) + '\n' # raw_input strips newlines
             prompt = interpreter.feed (command) and '>>> ' or '... '
     except (EOFError, KeyboardInterrupt): pass