I l@ve RuBoard |
9.13 Module: Building GTK GUIs InteractivelyCredit: Brian McErlean One of Python's greatest strengths is that it allows you to try things interactively at the interpreter. Tkinter shares this strength, since you can create buttons, windows, and other widgets, and see them instantly on screen. You can 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 interactive development is not possible. Before anything is actually displayed, the gtk.mainloop function must be called, ending the possibility of interactive manipulation. Example 9-1 simulates a Python interpreter while transparently letting the user use GTK widgets without requiring a call to mainloop, which is similar to how Tk widgets work. This version contains enhancements added by Christian Robottom Reis to add readline-completion support. This program works by running the GTK main loop in a separate thread. The main thread is responsible only for reading lines input by the user and for passing these 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 to call gtk.mainloop for GTK event handling to occur. Example 9-1. Building GTK GUIs interactivelyimport _ _builtin_ _, _ _main_ _
import codeop, keyword, gtk, os, re, readline, threading, traceback, signal, sys
def walk_class(klass):
list = []
for item in dir(klass):
if item[0] != "_":
list.append(item)
for base in klass._ _bases_ _:
for item in walk_class(base):
if item not in list: list.append(item)
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._ _class_ _)
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
TIMEOUT = 100 # interval in milliseconds 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:
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 is
if 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
9.13.1 See AlsoPyGTK is described and available at http://www.daa.com.au/~james/pygtk. |
I l@ve RuBoard |