#!/usr/bin/env python """ demo of a GUI with buttons and stuff. """ import graphics, threading, time # -- globals and constants ------------------------- _window = None # AppWindow object # -- class definitions ---------------------- class AppWindow(graphics.GraphWin): """application window """ def __init__(self, title='', width=200, height=200, window=None): graphics.GraphWin.__init__(self, title, width, height) class Button(threading.Thread): """a clickable button""" char_height = 14 # estimated character sizes (in pixels) char_width = 6 x_margin = 2 # empty space around text (in pixels) y_margin = 2 animate_time = 1.0 # time interval when something interesting happens colors = ('red', 'white', 'blue') color_index = 0 # which of colors is currently set def __init__(self, title, left, top, command=None, window=None): threading.Thread.__init__(self) self.window = window width = self.char_width*len(title) + 2*self.x_margin height = self.char_height + 2*self.y_margin top_left = graphics.Point(left, top) bot_right = graphics.Point(left + width, top + height) midpoint = graphics.Point(left+width/2, top+height/2) self.rect = graphics.Rectangle(top_left, bot_right) self.text = graphics.Text(midpoint, title) self.animating = True self.draw() # self.start() def draw(self, window=None): """Draw this button in the given window or in its default window.""" if not window: window = self.window if window and not self.window: self.window = window self.rect.draw(window) self.text.draw(window) def setFill(self, color): self.rect.setFill(color) def change_color(self): self.color_index = (self.color_index + 1) % len(self.colors) self.setFill(self.colors[self.color_index]) # error if not in main thread def run(self): while self.animating: next_animate_time = time.clock() + self.animate_time # in sec print "change color" # self.change_color() self.rect.move(10,10) while time.clock() < next_animate_time: continue # -- main ------------------------------------ print "creating window" _window = AppWindow(title='GUI demo', width=300, height=300) print "creating button" _button = Button(title="make circle", left=20, top=270, window=_window) input = raw_input('continue? ') _button.start() input = raw_input('continue? ') _button.animating = False