Example #1
0
def main():
    root = Tk()
    # w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    w, h = 960, 540
    # get value from arduino
    # ser = serial.Serial('/dev/tty.usbserial', 9600)
    pos = 0
    root.overrideredirect(1)
    root.focus_set()
    root.bind("<Escape>", lambda e: e.widget.quit())
    root.geometry("%dx%d+300+300" % (w, h))
    canvas = Canvas(root, width=w, height=h, background="black")
    rect0 = canvas.create_rectangle(w/2-75, h/2-20, w/2+75, h/2+20, fill="#05f", outline="#05f")
    rect1 = canvas.create_rectangle(w/2-20, h/2-75, w/2+20, h/2+75, fill="#05f", outline="#05f")
    canvas.pack() 
    
    while (True):
        # gets angle and moves accordingly
        # pos = ser.readline()
        canvas.move(rect0, 1, 0)
        canvas.move(rect1, 1, 0)
        root.update()
        root.after(30)
      
    app = App(root)
    time.sleep(0.5)
    root.mainloop()  
Example #2
0
def demo():
    root = Tk()
    root.bind('<Control-q>', lambda e: root.destroy())

    table = Table(root, 'Word Synset Hypernym Hyponym'.split(),
                  column_weights=[0, 1, 1, 1], 
                  reprfunc=(lambda i,j,s: '  %s' % s))
    table.pack(expand=True, fill='both')

    from nltk.corpus import wordnet
    from nltk.corpus import brown
    for word, pos in sorted(set(brown.tagged_words()[:500])):
        if pos[0] != 'N': continue
        word = word.lower()
        for synset in wordnet.synsets(word):
            hyper = (synset.hypernyms()+[''])[0]
            hypo = (synset.hyponyms()+[''])[0]
            table.append([word,
                          getattr(synset, 'definition', '*none*'),
                          getattr(hyper, 'definition', '*none*'),
                          getattr(hypo, 'definition', '*none*')])

    table.columnconfig('Word', background='#afa')
    table.columnconfig('Synset', background='#efe')
    table.columnconfig('Hypernym', background='#fee')
    table.columnconfig('Hyponym', background='#ffe')
    for row in range(len(table)):
        for column in ('Hypernym', 'Hyponym'):
            if table[row, column] == '*none*':
                table.itemconfig(row, column, foreground='#666',
                                 selectforeground='#666')
    root.mainloop()
def main():
    fileWords = open('wordList.txt')
    fileWords = fileWords.read()
    fileWords = fileWords.split()
    def clear():
        os.system('cls' if platform.system() == "Windows" else "clear")
        
    def whenClicked(*args):
        prefix = pattern.get()
        labelText.set("")
        for word in fileWords:
            if word.startswith(prefix):
                labelText.set(str(labelText.get())+'\n'+word)
    
        
        
    root = Tk()
    root.title('AutoComplete')
    ttk.Label(root, text='Enter search pattern').pack()
    pattern = StringVar()
    ttk.Entry(root, textvariable=pattern).pack()
    ttk.Button(root, text='Submit', command=whenClicked).pack()
    labelText = StringVar()
    ttk.Label(root, textvariable=labelText).pack()
    root.bind('<Return>', whenClicked)
    root.mainloop()
Example #4
0
class TokenInputGUI(object):
    def show_entry_fields(self, event=None):
        self.code = self.e1.get()
        self.master.withdraw()
        self.master.quit()

    def quit(self):
        self.master.quit()
        self.code = None

    def doGUI(self, hostname=None):
        self.master = Tk()
        self.master.title('Blessclient - MFA')
        textmsg = 'Enter your AWS MFA code: '
        if hostname:
            textmsg = 'Enter your AWS MFA code to connect to {}: '.format(
                hostname)
        Label(self.master, text=textmsg).grid(row=0)
        self.e1 = Entry(self.master)
        self.e1.grid(row=0, column=1, padx=4)
        Button(self.master,
               text='OK',
               command=self.show_entry_fields,
               default=ACTIVE).grid(row=3, column=0, sticky=W, pady=4)
        Button(self.master, text='Cancel', command=self.quit).grid(row=3,
                                                                   column=1,
                                                                   sticky=W,
                                                                   pady=4)

        self.center()
        self.master.bind('<Return>', self.show_entry_fields)
        self.master.lift()
        self.master.attributes('-topmost', True)
        self.master.focus_force()
        self.e1.focus_set()
        if platform.system() == 'Darwin':
            try:
                from Cocoa import (NSRunningApplication,
                                   NSApplicationActivateIgnoringOtherApps)

                app = NSRunningApplication.runningApplicationWithProcessIdentifier_(
                    os.getpid())
                app.activateWithOptions_(
                    NSApplicationActivateIgnoringOtherApps)
            except ImportError:
                pass

        mainloop()

    # http://stackoverflow.com/questions/3352918/how-to-center-a-window-on-the-screen-in-tkinter
    def center(self):
        self.master.update_idletasks()
        w = self.master.winfo_screenwidth()
        h = self.master.winfo_screenheight()
        size = tuple(
            int(_) for _ in self.master.geometry().split('+')[0].split('x'))
        x = w / 2 - size[0] / 2
        y = h / 2 - size[1] / 2
        self.master.geometry("%dx%d+%d+%d" % (size + (x, y)))
Example #5
0
def talker(): 
    motion = Twist()
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10) # 10hz
    root = Tk()
    root.geometry("750x300+500+-1000")
    root.bind('<Key>', onKeyPress)
    app = DronControll(root,pubControllDron,pubControllTakeoff,pubControllLanding,pubControllCamera)
    root.mainloop() 
Example #6
0
def main():
    global root
    # Populate the content
    populate_content()

    # Launch the GUI
    root = Tk()
    # Center the window
    center(root, (800, 800))
    app = MainFrame(root)
    root.bind('<Control-c>', root.quit)
    root.mainloop()
def main():
    global root
    # Populate the content
    populate_content()
    
    # Launch the GUI
    root = Tk()
    # Center the window
    center(root, (800, 800))
    app = MainFrame(root)
    root.bind('<Control-c>', root.quit)
    root.mainloop()
Example #8
0
    def _init_ui(self):
        root = Tk()
        root.title("parakeet")
        root.bind("<FocusOut>", self.close)
        root.bind("<Escape>", self.close)

        text = Text(root)
        text.config(width=60, height=1)
        text.pack(side=LEFT, fill=Y)
        text.bind("<Return>", self.handle_query)
        text.focus_force()

        return root, text
Example #9
0
class Display:
    def __init__(self, fps=FPS, width=WIDTH, height=HEIGHT,
        board_offset_bottom=BOARD_OFFSET_BOTTOM,
        board_width=BOARD_WIDTH,
        board_height=BOARD_HEIGHT):
        self.root=Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.root.destroy)
        self.width = width
        self.height = height
        self.canvas=Canvas(self.root, bg="black",width=width,height=height)
        self.board_width = board_width
        self.board_height = board_height
        self.board_offset_bottom = board_offset_bottom
        self.canvas.pack()
        self.fps = fps
        self.controllers = []
        #For reset
        self.root.bind("<space>", lambda e:self.reset_all())
        self.root.bind("<Escape>", lambda e:self.root.destroy())
    def run(self):
        self.root.after(1000//self.fps, self.loop)
        try:
            self.root.mainloop()
        except KeyboardInterrupt:
            self.root.destroy()
    def loop(self):
        actions = [controller.get_action(self.model) for controller in self.controllers]
        self.model.update(1./self.fps, actions)
        self.draw()
        self.root.after(1000//self.fps, self.loop)
    def draw(self):
        self.canvas.delete('all')
        self.board = self.canvas.create_rectangle(
            self.model.x()-self.board_width/2,
            self.board_offset_bottom+self.height-self.board_height,
            self.model.x()+self.board_width/2,
            self.board_offset_bottom+self.height, fill="green")
        self.pendulum = self.canvas.create_line(
            self.model.x(),
            self.board_offset_bottom+self.height-self.board_height,
            self.model.x()+self.model.arm_length*math.sin(self.model.alpha()),
            self.board_offset_bottom+self.height-self.board_height-self.model.arm_length*math.cos(self.model.alpha()),
            fill="blue", width=20)
    def attach_model(self, model):
        self.model = model
        self.draw()
    def attach_controller(self, controller):
        self.controllers.append(controller)
    def reset_all(self):
        self.model.randomize()
Example #10
0
def quickentry(labels, callback, title='', defaults=None):
    "Simple dialog from grabbing parameters from the user."

    if defaults is None:
        defaults = {}

    root = Tk()

    root.title(title)
    root['padx'] = 20
    root['pady'] = 10

    widgets = {}
    for label in labels:

        # Create a text frame to hold the text Label and the Entry widget
        f = Frame(root)

        #Create a Label in textFrame
        l = Label(f)
        l['text'] = label
        l['width'] = 10
        l.pack(side=LEFT)

        w = Entry(f)
        w['width'] = 20
        w.pack(side=LEFT)

        w.insert(0, defaults.get(label, ''))

        widgets[label] = w

        f.pack()

    def cb():
        callback({label: widgets[label].get().strip() for label in labels})

    Button(root, text="Quit",
           command=lambda root=root: root.destroy()).pack(side=RIGHT)
    Button(root, text='Submit', command=cb).pack(side=RIGHT)

    root.protocol("WM_DELETE_WINDOW", lambda root=root: root.destroy())

    print '[quickentry] running'
    root.bind("<Return>", lambda e: cb())
    root.bind("<Escape>", lambda e: root.destroy())
    root.mainloop()
    print '[quickentry] done'
    return root
Example #11
0
def quickentry(labels, callback, title='', defaults=None):
    "Simple dialog from grabbing parameters from the user."

    if defaults is None:
        defaults = {}

    root = Tk()

    root.title(title)
    root['padx'] = 20
    root['pady'] = 10

    widgets = {}
    for label in labels:

        # Create a text frame to hold the text Label and the Entry widget
        f = Frame(root)

        #Create a Label in textFrame
        l = Label(f)
        l['text'] = label
        l['width'] = 10
        l.pack(side=LEFT)

        w = Entry(f)
        w['width'] = 20
        w.pack(side=LEFT)

        w.insert(0, defaults.get(label, ''))

        widgets[label] = w

        f.pack()

    def cb():
        callback({label: widgets[label].get().strip() for label in labels})

    Button(root, text="Quit", command=lambda root=root: root.destroy()).pack(side=RIGHT)
    Button(root, text='Submit', command=cb).pack(side=RIGHT)


    root.protocol("WM_DELETE_WINDOW", lambda root=root: root.destroy())

    print '[quickentry] running'
    root.bind("<Return>", lambda e: cb())
    root.bind("<Escape>", lambda e: root.destroy())
    root.mainloop()
    print '[quickentry] done'
    return root
def run(): # Main function that triggers the rest of the game
    root = Tk() # Initializes a new root
    root.resizable(width = FALSE, height = FALSE) # The canvas is not resizable
    root.title("Boggle - Aayush Tekriwal - (15-112 Term Project)") # Title
    (width, height) = (1000,600) # Width and height of 
    canvas = Canvas(root, width = width, height = height)
    canvas.pack()
    root.canvas = canvas.canvas = canvas
    class Struct: pass
    canvas.data = Struct() # Struct stores all data for global access
    canvas.data.width = width
    canvas.data.height = height
    initGame(root, canvas) 
    #root.bind("<Button-1>", printCoords) # Unhash to help modify graphics
    root.bind("<space >", lambda event: getWord(canvas, event))
    root.bind("<Return>", lambda event: getWord(canvas, event))
    root.mainloop()
Example #13
0
def demo3():
    from nltk import Production
    (S, VP, NP, PP, P, N, Name, V, Det) = \
        nonterminals('S, VP, NP, PP, P, N, Name, V, Det')

    productions = (
        # Syntactic Productions
        Production(S, [NP, VP]),
        Production(NP, [Det, N]),
        Production(NP, [NP, PP]),
        Production(VP, [VP, PP]),
        Production(VP, [V, NP, PP]),
        Production(VP, [V, NP]),
        Production(PP, [P, NP]),
        Production(PP, []),
        Production(PP, ['up', 'over', NP]),

        # Lexical Productions
        Production(NP, ['I']),
        Production(Det, ['the']),
        Production(Det, ['a']),
        Production(N, ['man']),
        Production(V, ['saw']),
        Production(P, ['in']),
        Production(P, ['with']),
        Production(N, ['park']),
        Production(N, ['dog']),
        Production(N, ['statue']),
        Production(Det, ['my']),
    )

    t = Tk()

    def destroy(e, t=t):
        t.destroy()

    t.bind('q', destroy)
    p = ProductionList(t, productions)
    p.pack(expand=1, fill='both')
    p.add_callback('select', p.markonly)
    p.add_callback('move', p.markonly)
    p.focus()
    p.mark(productions[2])
    p.mark(productions[8])
Example #14
0
class TokenInputGUI(object):
    def show_entry_fields(self, event=None):
        self.code = self.e1.get()
        self.master.withdraw()
        self.master.quit()

    def quit(self):
        self.master.quit()
        self.code = None

    def doGUI(self, hostname=None):
        self.master = Tk()
        self.master.title('Blessclient - MFA')
        textmsg = 'Enter your AWS MFA code: '
        if hostname:
            textmsg = 'Enter your AWS MFA code to connect to {}: '.format(hostname)
        Label(self.master, text=textmsg).grid(row=0)
        self.e1 = Entry(self.master)
        self.e1.grid(row=0, column=1, padx=4)
        Button(self.master, text='OK', command=self.show_entry_fields, default=ACTIVE).grid(row=3, column=0, sticky=W, pady=4)
        Button(self.master, text='Cancel', command=self.quit).grid(row=3, column=1, sticky=W, pady=4)

        self.center()
        self.master.bind('<Return>', self.show_entry_fields)
        self.master.lift()
        self.master.attributes('-topmost', True)
        self.master.focus_force()
        self.e1.focus_set()

        if platform.system() == 'Darwin':
            # Hack to get the GUI dialog focused in OSX
            os.system('/usr/bin/osascript -e \'tell app "Finder" to set frontmost of process "python" to true\'')

        mainloop()

    # http://stackoverflow.com/questions/3352918/how-to-center-a-window-on-the-screen-in-tkinter
    def center(self):
        self.master.update_idletasks()
        w = self.master.winfo_screenwidth()
        h = self.master.winfo_screenheight()
        size = tuple(int(_) for _ in self.master.geometry().split('+')[0].split('x'))
        x = w / 2 - size[0] / 2
        y = h / 2 - size[1] / 2
        self.master.geometry("%dx%d+%d+%d" % (size + (x, y)))
Example #15
0
def guiLogin():
    root = Tk()

    root.title("Enter Lastpass login")

    mainframe = ttk.Frame(root, padding="3 3 12 12")
    mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
    mainframe.columnconfigure(0, weight=1)
    mainframe.rowconfigure(0, weight=1)

    username = StringVar()
    password = StringVar()
    ret = []

    def done(*args):
        ret.append((username.get(), password.get()))
        root.destroy()

    ttk.Label(mainframe, text="Username:"******"Password:"******"Login", command=done).grid(column=2,
                                                           row=3,
                                                           sticky=W)

    for child in mainframe.winfo_children():
        child.grid_configure(padx=5, pady=2)

    username_entry.focus()
    root.bind('<Return>', done)
    root.bind('<Escape>', lambda event: root.destroy())

    root.lift()
    root.call('wm', 'attributes', '.', '-topmost', True)
    root.after_idle(root.call, 'wm', 'attributes', '.', '-topmost', False)

    root.mainloop()

    return ret and ret[-1] or None
Example #16
0
def demo3():
    from nltk import Production

    (S, VP, NP, PP, P, N, Name, V, Det) = nonterminals("S, VP, NP, PP, P, N, Name, V, Det")

    productions = (
        # Syntactic Productions
        Production(S, [NP, VP]),
        Production(NP, [Det, N]),
        Production(NP, [NP, PP]),
        Production(VP, [VP, PP]),
        Production(VP, [V, NP, PP]),
        Production(VP, [V, NP]),
        Production(PP, [P, NP]),
        Production(PP, []),
        Production(PP, ["up", "over", NP]),
        # Lexical Productions
        Production(NP, ["I"]),
        Production(Det, ["the"]),
        Production(Det, ["a"]),
        Production(N, ["man"]),
        Production(V, ["saw"]),
        Production(P, ["in"]),
        Production(P, ["with"]),
        Production(N, ["park"]),
        Production(N, ["dog"]),
        Production(N, ["statue"]),
        Production(Det, ["my"]),
    )

    t = Tk()

    def destroy(e, t=t):
        t.destroy()

    t.bind("q", destroy)
    p = ProductionList(t, productions)
    p.pack(expand=1, fill="both")
    p.add_callback("select", p.markonly)
    p.add_callback("move", p.markonly)
    p.focus()
    p.mark(productions[2])
    p.mark(productions[8])
Example #17
0
    def prompt_gui(self, name, propagate_exception = False):
        ''' Returns None if failed to load tkinter or open display.
        (unless propagate_exception == True).'''
        
        ''' I thought about caching and reusing the tkinter instance, but it might be hard
        to properly temporarily exit from mainloop and suspend the application.
        Anyway, it takes like 10ms to restart it.'''
        try:
            from Tkinter import Tk, Label, Frame, Entry, StringVar
            root = Tk()
        except:
            if propagate_exception:
                raise
            return None

        root.title('Enter value for \'%s\':' % name)
        frame = Frame(root)
        frame.pack(fill = 'y', expand = True)

        label = Label(frame, text='Enter value for \'%s\':' % name)
        label.pack(side='left')
        
        var = StringVar()
        entry = Entry(frame, textvariable = var)
        entry.pack(side='left')
        
        result = []
        root.bind('<Return>', lambda ev: (result.append(var.get()), root.destroy()))
        ws = root.winfo_screenwidth()
        hs = root.winfo_screenheight()
        root.geometry('+%d+%d' % (ws * 0.4, hs * 0.4))
        entry.focus()
        
        # If I don't do this then for some reason the window doesn't get focus
        # on the second and following invocations. 
        root.focus_force()

        root.mainloop()
        if not len(result):
            # mimic the behaviour of CLI version
            raise KeyboardInterrupt()
        return result[0]
Example #18
0
    def _init_ui(self):
        root = Tk()
        root.title("pylens")
        root.bind("<FocusOut>", self.close)
        root.bind("<Escape>", self.close)

        # center the window
        root.withdraw()
        root.update_idletasks()  # Update "requested size" from geometry manager
        x = (root.winfo_screenwidth() - root.winfo_reqwidth()) / 2
        y = (root.winfo_screenheight() - root.winfo_reqheight()) / 2
        root.geometry("+%d+%d" % (x, y))
        root.deiconify()

        text = Text(root)
        text.config(width=60, height=1)
        text.pack(side=LEFT, fill=Y)
        text.bind("<Return>", self.handle_query)
        text.focus_force()

        return root, text
Example #19
0
def main():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-W', '--width',  type='int', default=300)
    parser.add_option('-H', '--height', type='int', default=300)
    parser.add_option('-c', '--center', type='complex', default=0+0j)
    parser.add_option('-s', '--side',   type='float', default=4)
    (options, args) = parser.parse_args()

    root = Tk()
    l = Label(root)
    l.pack()

    W, H = options.width, options.height
    center, side = options.center, options.side

    im = Image.new('P', (W, H), 0)
    im.putpalette([randrange(256) for n in range(3 * 256)])
    p = im.load()
    
    z = z_converter(W, H, center, side)
    l.pim = PhotoImage(im)
    l.config(image=l.pim)

    def paint_column(x):
        if x % 10 == 0: print "Column %d" % x
        for y in range(H):
            p[x, y] = pixel(z(x, y))
        l.pim = PhotoImage(im)
        l.config(image=l.pim)

        if x + 1 < W:
            root.after(1, paint_column, x + 1)

    def start(event):
        root.after(1, paint_column, 0)

    root.bind('<FocusIn>', start)
    root.mainloop()
Example #20
0
def captcha_handler(captcha):
    root = Tk()
    root.title('captcha')

    def executor(event):
        global text
        text = entry.get()
        root.destroy()

    r = requests.get(captcha.get_url())
    with open('captcha.jpg', 'wb') as image:
        image.write(r.content)
    img = Image.open('captcha.jpg')
    photo = ImageTk.PhotoImage(img)
    label = Label(root, image=photo)
    entry = Entry()
    root.bind('<Return>', executor)
    root.focus_force()
    label.pack()
    entry.pack()
    entry.focus_force()
    root.mainloop()
    return captcha.try_again(text)
Example #21
0
def demo():
    root = Tk()
    root.bind('<Control-q>', lambda e: root.destroy())

    table = Table(root,
                  'Word Synset Hypernym Hyponym'.split(),
                  column_weights=[0, 1, 1, 1],
                  reprfunc=(lambda i, j, s: '  %s' % s))
    table.pack(expand=True, fill='both')

    from nltk.corpus import wordnet
    from nltk.corpus import brown
    for word, pos in sorted(set(brown.tagged_words()[:500])):
        if pos[0] != 'N': continue
        word = word.lower()
        for synset in wordnet.synsets(word):
            hyper = (synset.hypernyms() + [''])[0]
            hypo = (synset.hyponyms() + [''])[0]
            table.append([
                word,
                getattr(synset, 'definition', '*none*'),
                getattr(hyper, 'definition', '*none*'),
                getattr(hypo, 'definition', '*none*')
            ])

    table.columnconfig('Word', background='#afa')
    table.columnconfig('Synset', background='#efe')
    table.columnconfig('Hypernym', background='#fee')
    table.columnconfig('Hyponym', background='#ffe')
    for row in range(len(table)):
        for column in ('Hypernym', 'Hyponym'):
            if table[row, column] == '*none*':
                table.itemconfig(row,
                                 column,
                                 foreground='#666',
                                 selectforeground='#666')
    root.mainloop()
Example #22
0
def demo():
    root = Tk()
    root.bind("<Control-q>", lambda e: root.destroy())

    table = Table(
        root, "Word Synset Hypernym Hyponym".split(), column_weights=[0, 1, 1, 1], reprfunc=(lambda i, j, s: "  %s" % s)
    )
    table.pack(expand=True, fill="both")

    from nltk.corpus import wordnet
    from nltk.corpus import brown

    for word, pos in sorted(set(brown.tagged_words()[:500])):
        if pos[0] != "N":
            continue
        word = word.lower()
        for synset in wordnet.synsets(word):
            hyper = (synset.hypernyms() + [""])[0]
            hypo = (synset.hyponyms() + [""])[0]
            table.append(
                [
                    word,
                    getattr(synset, "definition", "*none*"),
                    getattr(hyper, "definition", "*none*"),
                    getattr(hypo, "definition", "*none*"),
                ]
            )

    table.columnconfig("Word", background="#afa")
    table.columnconfig("Synset", background="#efe")
    table.columnconfig("Hypernym", background="#fee")
    table.columnconfig("Hyponym", background="#ffe")
    for row in range(len(table)):
        for column in ("Hypernym", "Hyponym"):
            if table[row, column] == "*none*":
                table.itemconfig(row, column, foreground="#666", selectforeground="#666")
    root.mainloop()
Example #23
0
File: cfg.py Project: gijs/nltk
def demo3():
    from nltk import Production
    (S, VP, NP, PP, P, N, Name, V, Det) = \
        nonterminals('S, VP, NP, PP, P, N, Name, V, Det')
    
    productions = (
        # Syntactic Productions
        Production(S, [NP, VP]),
        Production(NP, [Det, N]),
        Production(NP, [NP, PP]),
        Production(VP, [VP, PP]),
        Production(VP, [V, NP, PP]),
        Production(VP, [V, NP]),
        Production(PP, [P, NP]),
        Production(PP, []),

        Production(PP, ['up', 'over', NP]),
        
        # Lexical Productions
        Production(NP, ['I']),   Production(Det, ['the']),
        Production(Det, ['a']),  Production(N, ['man']),
        Production(V, ['saw']),  Production(P, ['in']),
        Production(P, ['with']), Production(N, ['park']),
        Production(N, ['dog']),  Production(N, ['statue']),
        Production(Det, ['my']),
        )
    
    t = Tk()
    def destroy(e, t=t): t.destroy()
    t.bind('q', destroy)
    p = ProductionList(t, productions)
    p.pack(expand=1, fill='both')
    p.add_callback('select', p.markonly)
    p.add_callback('move', p.markonly)
    p.focus()
    p.mark(productions[2])
    p.mark(productions[8])
Example #24
0
def main():
    """Set up the stopwatch and the buttons/keyboard shortcuts to control it"""
    root = Tk()

    # Add stopwatch frame
    stopwatch = StopWatch(root)
    stopwatch.pack(side=TOP)

    # Add buttons
    Button(root, text='Start/Stop',
           command=stopwatch.start_stop, takefocus=False).pack(side=LEFT)
    Button(root, text='Reset',
           command=stopwatch.reset, takefocus=False).pack(side=LEFT)
    Button(root, text='Quit',
           command=root.quit, takefocus=False).pack(side=LEFT)

    # Add keyboard shurtcuts
    root.bind("<space>", lambda x: stopwatch.start_stop())
    root.bind("<BackSpace>", lambda x: stopwatch.reset())
    root.bind("<Escape>", lambda x: root.quit())

    root.focus_set()
    root.mainloop()
        ##      print
        screenedge.draw(mycanvas)
    mycanvas.postscript(file="circles.eps")


############################################
# MAIN PROGRAM STARTS HERE
############################################
if __name__ == "__main__":
    root = Tk()
    root.title('BVHPlay')

    mymenu = Menubar(root)

    mymenu.filemenu.entryconfig(0, command=open_file)
    root.bind('<Control-Key-o>', open_file2)
    mymenu.settingsmenu.entryconfig(0, command=toggle_grid)
    mymenu.settingsmenu.entryconfig(1, command=toggle_axes)
    mymenu.settingsmenu.entryconfig(2, command=toggle_readout)

    mytransport = Transport()  # Create and pack a frame of transport buttons
    mytransport.btn_begin.config(command=onBegin)
    mytransport.btn_end.config(command=onEnd)
    mytransport.btn_stop.config(command=onStop)
    mytransport.btn_play.config(command=onPlay)
    mytransport.btn_stepback.config(command=onStepback)
    mytransport.btn_stepfd.config(command=onStepfd)

    myplaybar = Playbar()
    slidert = IntVar()  # Special magic integer that allows me to tie it
    # to a Tk widget "variable" option, in this case
Example #26
0
root = Tk()
root.title("Feet to Meters")

mainframe = Tk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

feet = StringVar()
meters = StringVar()

feet_entry = Tk.Entry(mainframe, width=7, textvariable=feet)
feet_entry.grid(column=2, row=1, sticky=(W, E))

Tk.Label(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(W, E))
Tk.Button(mainframe, text="Calculate", command=calculate).grid(column=3,
                                                               row=3,
                                                               sticky=W)

Tk.Label(mainframe, text="feet").grid(column=3, row=1, sticky=W)
Tk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E)
Tk.Label(mainframe, text="meters").grid(column=3, row=2, sticky=W)

for child in mainframe.winfo_children():
    child.grid_configure(padx=5, pady=5)

feet_entry.focus()
root.bind('<Return>', calculate)

root.mainloop()
Example #27
0
class ShiftReduceApp(object):
    """
    A graphical tool for exploring the shift-reduce parser.  The tool
    displays the parser's stack and the remaining text, and allows the
    user to control the parser's operation.  In particular, the user
    can shift tokens onto the stack, and can perform reductions on the
    top elements of the stack.  A "step" button simply steps through
    the parsing process, performing the operations that
    ``nltk.parse.ShiftReduceParser`` would use.
    """
    def __init__(self, grammar, sent, trace=0):
        self._sent = sent
        self._parser = SteppingShiftReduceParser(grammar, trace)

        # Set up the main window.
        self._top = Tk()
        self._top.title('Shift Reduce Parser Application')

        # Animations.  animating_lock is a lock to prevent the demo
        # from performing new operations while it's animating.
        self._animating_lock = 0
        self._animate = IntVar(self._top)
        self._animate.set(10)  # = medium

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Initialize fonts.
        self._init_fonts(self._top)

        # Set up key bindings.
        self._init_bindings()

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_feedback(self._top)
        self._init_grammar(self._top)
        self._init_canvas(self._top)

        # A popup menu for reducing.
        self._reduce_menu = Menu(self._canvas, tearoff=0)

        # Reset the demo, and set the feedback frame to empty.
        self.reset()
        self._lastoper1['text'] = ''

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = tkFont.Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget('size'))

        self._boldfont = tkFont.Font(family='helvetica',
                                     weight='bold',
                                     size=self._size.get())
        self._font = tkFont.Font(family='helvetica', size=self._size.get())

    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill='both', side='left', padx=2)
        self._prodlist_label = Label(self._prodframe,
                                     font=self._boldfont,
                                     text='Available Reductions')
        self._prodlist_label.pack()
        self._prodlist = Listbox(self._prodframe,
                                 selectmode='single',
                                 relief='groove',
                                 background='white',
                                 foreground='#909090',
                                 font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._prodlist.pack(side='right', fill='both', expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert('end', (' %s' % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if 1:  #len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe, orient='vertical')
            self._prodlist.config(yscrollcommand=listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a production, apply it.
        self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select)

        # When they hover over a production, highlight it.
        self._hover = -1
        self._prodlist.bind('<Motion>', self._highlight_hover)
        self._prodlist.bind('<Leave>', self._clear_hover)

    def _init_bindings(self):
        # Quit
        self._top.bind('<Control-q>', self.destroy)
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Alt-q>', self.destroy)
        self._top.bind('<Alt-x>', self.destroy)

        # Ops (step, shift, reduce, undo)
        self._top.bind('<space>', self.step)
        self._top.bind('<s>', self.shift)
        self._top.bind('<Alt-s>', self.shift)
        self._top.bind('<Control-s>', self.shift)
        self._top.bind('<r>', self.reduce)
        self._top.bind('<Alt-r>', self.reduce)
        self._top.bind('<Control-r>', self.reduce)
        self._top.bind('<Delete>', self.reset)
        self._top.bind('<u>', self.undo)
        self._top.bind('<Alt-u>', self.undo)
        self._top.bind('<Control-u>', self.undo)
        self._top.bind('<Control-z>', self.undo)
        self._top.bind('<BackSpace>', self.undo)

        # Misc
        self._top.bind('<Control-p>', self.postscript)
        self._top.bind('<Control-h>', self.help)
        self._top.bind('<F1>', self.help)
        self._top.bind('<Control-g>', self.edit_grammar)
        self._top.bind('<Control-t>', self.edit_sentence)

        # Animation speed control
        self._top.bind('-', lambda e, a=self._animate: a.set(20))
        self._top.bind('=', lambda e, a=self._animate: a.set(10))
        self._top.bind('+', lambda e, a=self._animate: a.set(4))

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill='none', side='bottom')
        Button(
            buttonframe,
            text='Step',
            background='#90c0d0',
            foreground='black',
            command=self.step,
        ).pack(side='left')
        Button(buttonframe,
               text='Shift',
               underline=0,
               background='#90f090',
               foreground='black',
               command=self.shift).pack(side='left')
        Button(buttonframe,
               text='Reduce',
               underline=0,
               background='#90f090',
               foreground='black',
               command=self.reduce).pack(side='left')
        Button(buttonframe,
               text='Undo',
               underline=0,
               background='#f0a0a0',
               foreground='black',
               command=self.undo).pack(side='left')

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Reset Parser',
                             underline=0,
                             command=self.reset,
                             accelerator='Del')
        filemenu.add_command(label='Print to Postscript',
                             underline=0,
                             command=self.postscript,
                             accelerator='Ctrl-p')
        filemenu.add_command(label='Exit',
                             underline=1,
                             command=self.destroy,
                             accelerator='Ctrl-x')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label='Edit Grammar',
                             underline=5,
                             command=self.edit_grammar,
                             accelerator='Ctrl-g')
        editmenu.add_command(label='Edit Text',
                             underline=5,
                             command=self.edit_sentence,
                             accelerator='Ctrl-t')
        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label='Step',
                             underline=1,
                             command=self.step,
                             accelerator='Space')
        rulemenu.add_separator()
        rulemenu.add_command(label='Shift',
                             underline=0,
                             command=self.shift,
                             accelerator='Ctrl-s')
        rulemenu.add_command(label='Reduce',
                             underline=0,
                             command=self.reduce,
                             accelerator='Ctrl-r')
        rulemenu.add_separator()
        rulemenu.add_command(label='Undo',
                             underline=0,
                             command=self.undo,
                             accelerator='Ctrl-u')
        menubar.add_cascade(label='Apply', underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(label="Show Grammar",
                                 underline=0,
                                 variable=self._show_grammar,
                                 command=self._toggle_grammar)
        viewmenu.add_separator()
        viewmenu.add_radiobutton(label='Tiny',
                                 variable=self._size,
                                 underline=0,
                                 value=10,
                                 command=self.resize)
        viewmenu.add_radiobutton(label='Small',
                                 variable=self._size,
                                 underline=0,
                                 value=12,
                                 command=self.resize)
        viewmenu.add_radiobutton(label='Medium',
                                 variable=self._size,
                                 underline=0,
                                 value=14,
                                 command=self.resize)
        viewmenu.add_radiobutton(label='Large',
                                 variable=self._size,
                                 underline=0,
                                 value=18,
                                 command=self.resize)
        viewmenu.add_radiobutton(label='Huge',
                                 variable=self._size,
                                 underline=0,
                                 value=24,
                                 command=self.resize)
        menubar.add_cascade(label='View', underline=0, menu=viewmenu)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation",
                                    underline=0,
                                    variable=self._animate,
                                    value=0)
        animatemenu.add_radiobutton(label="Slow Animation",
                                    underline=0,
                                    variable=self._animate,
                                    value=20,
                                    accelerator='-')
        animatemenu.add_radiobutton(label="Normal Animation",
                                    underline=0,
                                    variable=self._animate,
                                    value=10,
                                    accelerator='=')
        animatemenu.add_radiobutton(label="Fast Animation",
                                    underline=0,
                                    variable=self._animate,
                                    value=4,
                                    accelerator='+')
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label='About', underline=0, command=self.about)
        helpmenu.add_command(label='Instructions',
                             underline=0,
                             command=self.help,
                             accelerator='F1')
        menubar.add_cascade(label='Help', underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    def _init_feedback(self, parent):
        self._feedbackframe = feedbackframe = Frame(parent)
        feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3)
        self._lastoper_label = Label(feedbackframe,
                                     text='Last Operation:',
                                     font=self._font)
        self._lastoper_label.pack(side='left')
        lastoperframe = Frame(feedbackframe, relief='sunken', border=1)
        lastoperframe.pack(fill='x', side='right', expand=1, padx=5)
        self._lastoper1 = Label(lastoperframe,
                                foreground='#007070',
                                background='#f0f0f0',
                                font=self._font)
        self._lastoper2 = Label(lastoperframe,
                                anchor='w',
                                width=30,
                                foreground='#004040',
                                background='#f0f0f0',
                                font=self._font)
        self._lastoper1.pack(side='left')
        self._lastoper2.pack(side='left', fill='x', expand=1)

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(parent,
                                   background='white',
                                   width=525,
                                   closeenough=10,
                                   border=2,
                                   relief='sunken')
        self._cframe.pack(expand=1, fill='both', side='top', pady=2)
        canvas = self._canvas = self._cframe.canvas()

        self._stackwidgets = []
        self._rtextwidgets = []
        self._titlebar = canvas.create_rectangle(0,
                                                 0,
                                                 0,
                                                 0,
                                                 fill='#c0f0f0',
                                                 outline='black')
        self._exprline = canvas.create_line(0, 0, 0, 0, dash='.')
        self._stacktop = canvas.create_line(0, 0, 0, 0, fill='#408080')
        size = self._size.get() + 4
        self._stacklabel = TextWidget(canvas,
                                      'Stack',
                                      color='#004040',
                                      font=self._boldfont)
        self._rtextlabel = TextWidget(canvas,
                                      'Remaining Text',
                                      color='#004040',
                                      font=self._boldfont)
        self._cframe.add_widget(self._stacklabel)
        self._cframe.add_widget(self._rtextlabel)

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        scrollregion = self._canvas['scrollregion'].split()
        (cx1, cy1, cx2, cy2) = [int(c) for c in scrollregion]

        # Delete the old stack & rtext widgets.
        for stackwidget in self._stackwidgets:
            self._cframe.destroy_widget(stackwidget)
        self._stackwidgets = []
        for rtextwidget in self._rtextwidgets:
            self._cframe.destroy_widget(rtextwidget)
        self._rtextwidgets = []

        # Position the titlebar & exprline
        (x1, y1, x2, y2) = self._stacklabel.bbox()
        y = y2 - y1 + 10
        self._canvas.coords(self._titlebar, -5000, 0, 5000, y - 4)
        self._canvas.coords(self._exprline, 0, y * 2 - 10, 5000, y * 2 - 10)

        # Position the titlebar labels..
        (x1, y1, x2, y2) = self._stacklabel.bbox()
        self._stacklabel.move(5 - x1, 3 - y1)
        (x1, y1, x2, y2) = self._rtextlabel.bbox()
        self._rtextlabel.move(cx2 - x2 - 5, 3 - y1)

        # Draw the stack.
        stackx = 5
        for tok in self._parser.stack():
            if isinstance(tok, Tree):
                attribs = {
                    'tree_color': '#4080a0',
                    'tree_width': 2,
                    'node_font': self._boldfont,
                    'node_color': '#006060',
                    'leaf_color': '#006060',
                    'leaf_font': self._font
                }
                widget = tree_to_treesegment(self._canvas, tok, **attribs)
                widget.node()['color'] = '#000000'
            else:
                widget = TextWidget(self._canvas,
                                    tok,
                                    color='#000000',
                                    font=self._font)
            widget.bind_click(self._popup_reduce)
            self._stackwidgets.append(widget)
            self._cframe.add_widget(widget, stackx, y)
            stackx = widget.bbox()[2] + 10

        # Draw the remaining text.
        rtextwidth = 0
        for tok in self._parser.remaining_text():
            widget = TextWidget(self._canvas,
                                tok,
                                color='#000000',
                                font=self._font)
            self._rtextwidgets.append(widget)
            self._cframe.add_widget(widget, rtextwidth, y)
            rtextwidth = widget.bbox()[2] + 4

        # Allow enough room to shift the next token (for animations)
        if len(self._rtextwidgets) > 0:
            stackx += self._rtextwidgets[0].width()

        # Move the remaining text to the correct location (keep it
        # right-justified, when possible); and move the remaining text
        # label, if necessary.
        stackx = max(stackx, self._stacklabel.width() + 25)
        rlabelwidth = self._rtextlabel.width() + 10
        if stackx >= cx2 - max(rtextwidth, rlabelwidth):
            cx2 = stackx + max(rtextwidth, rlabelwidth)
        for rtextwidget in self._rtextwidgets:
            rtextwidget.move(4 + cx2 - rtextwidth, 0)
        self._rtextlabel.move(cx2 - self._rtextlabel.bbox()[2] - 5, 0)

        midx = (stackx + cx2 - max(rtextwidth, rlabelwidth)) / 2
        self._canvas.coords(self._stacktop, midx, 0, midx, 5000)
        (x1, y1, x2, y2) = self._stacklabel.bbox()

        # Set up binding to allow them to shift a token by dragging it.
        if len(self._rtextwidgets) > 0:

            def drag_shift(widget, midx=midx, self=self):
                if widget.bbox()[0] < midx: self.shift()
                else: self._redraw()

            self._rtextwidgets[0].bind_drag(drag_shift)
            self._rtextwidgets[0].bind_click(self.shift)

        # Draw the stack top.
        self._highlight_productions()

    def _draw_stack_top(self, widget):
        # hack..
        midx = widget.bbox()[2] + 50
        self._canvas.coords(self._stacktop, midx, 0, midx, 5000)

    def _highlight_productions(self):
        # Highlight the productions that can be reduced.
        self._prodlist.selection_clear(0, 'end')
        for prod in self._parser.reducible_productions():
            index = self._productions.index(prod)
            self._prodlist.selection_set(index)

    #########################################
    ##  Button Callbacks
    #########################################

    def destroy(self, *e):
        if self._top is None: return
        self._top.destroy()
        self._top = None

    def reset(self, *e):
        self._parser.initialize(self._sent)
        self._lastoper1['text'] = 'Reset App'
        self._lastoper2['text'] = ''
        self._redraw()

    def step(self, *e):
        if self.reduce(): return 1
        elif self.shift(): return 1
        else:
            if len(self._parser.parses()) > 0:
                self._lastoper1['text'] = 'Finished:'
                self._lastoper2['text'] = 'Success'
            else:
                self._lastoper1['text'] = 'Finished:'
                self._lastoper2['text'] = 'Failure'

    def shift(self, *e):
        if self._animating_lock: return
        if self._parser.shift():
            tok = self._parser.stack()[-1]
            self._lastoper1['text'] = 'Shift:'
            self._lastoper2['text'] = '%r' % tok
            if self._animate.get():
                self._animate_shift()
            else:
                self._redraw()
            return 1
        return 0

    def reduce(self, *e):
        if self._animating_lock: return
        production = self._parser.reduce()
        if production:
            self._lastoper1['text'] = 'Reduce:'
            self._lastoper2['text'] = '%s' % production
            if self._animate.get():
                self._animate_reduce()
            else:
                self._redraw()
        return production

    def undo(self, *e):
        if self._animating_lock: return
        if self._parser.undo():
            self._redraw()

    def postscript(self, *e):
        self._cframe.print_to_file()

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle(): return
        self._top.mainloop(*args, **kwargs)

    #########################################
    ##  Menubar callbacks
    #########################################

    def resize(self, size=None):
        if size is not None: self._size.set(size)
        size = self._size.get()
        self._font.configure(size=-(abs(size)))
        self._boldfont.configure(size=-(abs(size)))
        self._sysfont.configure(size=-(abs(size)))

        #self._stacklabel['font'] = ('helvetica', -size-4, 'bold')
        #self._rtextlabel['font'] = ('helvetica', -size-4, 'bold')
        #self._lastoper_label['font'] = ('helvetica', -size)
        #self._lastoper1['font'] = ('helvetica', -size)
        #self._lastoper2['font'] = ('helvetica', -size)
        #self._prodlist['font'] = ('helvetica', -size)
        #self._prodlist_label['font'] = ('helvetica', -size-2, 'bold')
        self._redraw()

    def help(self, *e):
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(self._top,
                     'Help: Shift-Reduce Parser Application', (__doc__
                                                               or '').strip(),
                     width=75,
                     font='fixed')
        except:
            ShowText(self._top,
                     'Help: Shift-Reduce Parser Application', (__doc__
                                                               or '').strip(),
                     width=75)

    def about(self, *e):
        ABOUT = ("NLTK Shift-Reduce Parser Application\n" +
                 "Written by Edward Loper")
        TITLE = 'About: Shift-Reduce Parser Application'
        try:
            from tkMessageBox import Message
            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def edit_grammar(self, *e):
        CFGEditor(self._top, self._parser.grammar(), self.set_grammar)

    def set_grammar(self, grammar):
        self._parser.set_grammar(grammar)
        self._productions = list(grammar.productions())
        self._prodlist.delete(0, 'end')
        for production in self._productions:
            self._prodlist.insert('end', (' %s' % production))

    def edit_sentence(self, *e):
        sentence = string.join(self._sent)
        title = 'Edit Text'
        instr = 'Enter a new sentence to parse.'
        EntryDialog(self._top, sentence, instr, self.set_sentence, title)

    def set_sentence(self, sent):
        self._sent = sent.split()  #[XX] use tagged?
        self.reset()

    #########################################
    ##  Reduce Production Selection
    #########################################

    def _toggle_grammar(self, *e):
        if self._show_grammar.get():
            self._prodframe.pack(fill='both',
                                 side='left',
                                 padx=2,
                                 after=self._feedbackframe)
            self._lastoper1['text'] = 'Show Grammar'
        else:
            self._prodframe.pack_forget()
            self._lastoper1['text'] = 'Hide Grammar'
        self._lastoper2['text'] = ''

    def _prodlist_select(self, event):
        selection = self._prodlist.curselection()
        if len(selection) != 1: return
        index = int(selection[0])
        production = self._parser.reduce(self._productions[index])
        if production:
            self._lastoper1['text'] = 'Reduce:'
            self._lastoper2['text'] = '%s' % production
            if self._animate.get():
                self._animate_reduce()
            else:
                self._redraw()
        else:
            # Reset the production selections.
            self._prodlist.selection_clear(0, 'end')
            for prod in self._parser.reducible_productions():
                index = self._productions.index(prod)
                self._prodlist.selection_set(index)

    def _popup_reduce(self, widget):
        # Remove old commands.
        productions = self._parser.reducible_productions()
        if len(productions) == 0: return

        self._reduce_menu.delete(0, 'end')
        for production in productions:
            self._reduce_menu.add_command(label=str(production),
                                          command=self.reduce)
        self._reduce_menu.post(self._canvas.winfo_pointerx(),
                               self._canvas.winfo_pointery())

    #########################################
    ##  Animations
    #########################################

    def _animate_shift(self):
        # What widget are we shifting?
        widget = self._rtextwidgets[0]

        # Where are we shifting from & to?
        right = widget.bbox()[0]
        if len(self._stackwidgets) == 0: left = 5
        else: left = self._stackwidgets[-1].bbox()[2] + 10

        # Start animating.
        dt = self._animate.get()
        dx = (left - right) * 1.0 / dt
        self._animate_shift_frame(dt, widget, dx)

    def _animate_shift_frame(self, frame, widget, dx):
        if frame > 0:
            self._animating_lock = 1
            widget.move(dx, 0)
            self._top.after(10, self._animate_shift_frame, frame - 1, widget,
                            dx)
        else:
            # but: stacktop??

            # Shift the widget to the stack.
            del self._rtextwidgets[0]
            self._stackwidgets.append(widget)
            self._animating_lock = 0

            # Display the available productions.
            self._draw_stack_top(widget)
            self._highlight_productions()

    def _animate_reduce(self):
        # What widgets are we shifting?
        numwidgets = len(self._parser.stack()[-1])  # number of children
        widgets = self._stackwidgets[-numwidgets:]

        # How far are we moving?
        if isinstance(widgets[0], TreeSegmentWidget):
            ydist = 15 + widgets[0].node().height()
        else:
            ydist = 15 + widgets[0].height()

        # Start animating.
        dt = self._animate.get()
        dy = ydist * 2.0 / dt
        self._animate_reduce_frame(dt / 2, widgets, dy)

    def _animate_reduce_frame(self, frame, widgets, dy):
        if frame > 0:
            self._animating_lock = 1
            for widget in widgets:
                widget.move(0, dy)
            self._top.after(10, self._animate_reduce_frame, frame - 1, widgets,
                            dy)
        else:
            del self._stackwidgets[-len(widgets):]
            for widget in widgets:
                self._cframe.remove_widget(widget)
            tok = self._parser.stack()[-1]
            if not isinstance(tok, Tree): raise ValueError()
            label = TextWidget(self._canvas,
                               str(tok.node),
                               color='#006060',
                               font=self._boldfont)
            widget = TreeSegmentWidget(self._canvas, label, widgets, width=2)
            (x1, y1, x2, y2) = self._stacklabel.bbox()
            y = y2 - y1 + 10
            if not self._stackwidgets: x = 5
            else: x = self._stackwidgets[-1].bbox()[2] + 10
            self._cframe.add_widget(widget, x, y)
            self._stackwidgets.append(widget)

            # Display the available productions.
            self._draw_stack_top(widget)
            self._highlight_productions()

            #             # Delete the old widgets..
            #             del self._stackwidgets[-len(widgets):]
            #             for widget in widgets:
            #                 self._cframe.destroy_widget(widget)
            #
            #             # Make a new one.
            #             tok = self._parser.stack()[-1]
            #             if isinstance(tok, Tree):
            #                 attribs = {'tree_color': '#4080a0', 'tree_width': 2,
            #                            'node_font': bold, 'node_color': '#006060',
            #                            'leaf_color': '#006060', 'leaf_font':self._font}
            #                 widget = tree_to_treesegment(self._canvas, tok.type(),
            #                                              **attribs)
            #                 widget.node()['color'] = '#000000'
            #             else:
            #                 widget = TextWidget(self._canvas, tok.type(),
            #                                     color='#000000', font=self._font)
            #             widget.bind_click(self._popup_reduce)
            #             (x1, y1, x2, y2) = self._stacklabel.bbox()
            #             y = y2-y1+10
            #             if not self._stackwidgets: x = 5
            #             else: x = self._stackwidgets[-1].bbox()[2] + 10
            #             self._cframe.add_widget(widget, x, y)
            #             self._stackwidgets.append(widget)

            #self._redraw()
            self._animating_lock = 0

    #########################################
    ##  Hovering.
    #########################################

    def _highlight_hover(self, event):
        # What production are we hovering over?
        index = self._prodlist.nearest(event.y)
        if self._hover == index: return

        # Clear any previous hover highlighting.
        self._clear_hover()

        # If the production corresponds to an available reduction,
        # highlight the stack.
        selection = [int(s) for s in self._prodlist.curselection()]
        if index in selection:
            rhslen = len(self._productions[index].rhs())
            for stackwidget in self._stackwidgets[-rhslen:]:
                if isinstance(stackwidget, TreeSegmentWidget):
                    stackwidget.node()['color'] = '#00a000'
                else:
                    stackwidget['color'] = '#00a000'

        # Remember what production we're hovering over.
        self._hover = index

    def _clear_hover(self, *event):
        # Clear any previous hover highlighting.
        if self._hover == -1: return
        self._hover = -1
        for stackwidget in self._stackwidgets:
            if isinstance(stackwidget, TreeSegmentWidget):
                stackwidget.node()['color'] = 'black'
            else:
                stackwidget['color'] = 'black'
Example #28
0
class tk_window(object):
    _ret = None
    _frame = None
    _master = None
    _child = None
    _destroyed = False
    _parent = None

    def __init__(self, classname, classtitle):
        self._master = Tk(className=classname)
        self._master.protocol('WM_DELETE_WINDOW', self.destroy)
        super(tk_window, self).__init__()

        self._parent = None
        self._child = None
        self.set_class(classtitle)
        self._master.bind('<FocusIn>', self.focus_in)

    @property
    def master(self):
        return self._master

    @master.setter
    def master(self, value):
        self._master = value

    @property
    def parent(self):
        return self._parent

    @parent.setter
    def parent(self, value):
        self._parent = value

    @property
    def child(self):
        return self._child

    @child.setter
    def child(self, value):
        self._child = value

    @property
    def leaf(self):
        leaf = self.child
        while leaf.child is not None:
            leaf = leaf.child

        return leaf

    @property
    def trunk(self):
        trunk = self.parent
        while trunk.parent is not None:
            trunk = trunk.parent

        return trunk

    @property
    def is_destroyed(self):
        return self._destroyed

    def destroy(self, event=None):
        if not self.is_destroyed:
            self.destroy_child()

            try:
                self.master.quit()
                self.master.destroy()
            except TclError:
                pass

            self._destroyed = True

        if self.parent is not None:
            self.parent.child = None

    def set_class(self, classname):
        self.master.wm_iconname(classname)

    def set_title(self, title):
        self.master.wm_title(title)

    def set_size(self, width=None, height=None):
        if width is not None and height is not None:
            self.master.geometry('{}x{}'.format(width, height))

        else:
            (old_width, old_height) = [
                int(x) for x in self.master.geometry().split('+')[0].split('x')
            ]

            if width is not None:
                self.master.geometry('{}x{}'.format(width, old_height))

            elif height is not None:
                self.master.geometry('{}x{}'.format(old_width, height))

            #else: # do nothing, nothing specified

    def focus_in(self, event_instance):
        self.focus_child()

    def focus_child(self):
        if self.child is not None and not self.child.is_destroyed:
            self.child.master.lift()
            self.child.master.focus()

    def spawn_child(self, child):
        if self.child is not None:
            self.destroy_child()

        self.child = child
        child.parent = self
        return child.run()

    def destroy_child(self):
        if self.child is not None and not self.child.is_destroyed:
            self.child.destroy()

        self.child = None

    def run(self):
        try:
            self.master.mainloop()
        except KeyboardInterrupt:
            pass

        self.destroy()
        return self._ret
Example #29
0
class DrtGlueDemo(object):
    def __init__(self, examples):
        # Set up the main window.
        self._top = Tk()
        self._top.title('DRT Glue Demo')

        # Set up key bindings.
        self._init_bindings()

        # Initialize the fonts.self._error = None
        self._init_fonts(self._top)

        self._examples = examples
        self._readingCache = [None for example in examples]

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Set the data to None
        self._curExample = -1
        self._readings = []
        self._drs = None
        self._drsWidget = None
        self._error = None

        self._init_glue()

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_exampleListbox(self._top)
        self._init_readingListbox(self._top)
        self._init_canvas(self._top)

        # Resize callback
        self._canvas.bind('<Configure>', self._configure)

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_glue(self):
        tagger = RegexpTagger([
            ('^(David|Mary|John)$', 'NNP'),
            ('^(walks|sees|eats|chases|believes|gives|sleeps|chases|persuades|tries|seems|leaves)$',
             'VB'), ('^(go|order|vanish|find|approach)$', 'VB'),
            ('^(a)$', 'ex_quant'), ('^(every)$', 'univ_quant'),
            ('^(sandwich|man|dog|pizza|unicorn|cat|senator)$', 'NN'),
            ('^(big|gray|former)$', 'JJ'), ('^(him|himself)$', 'PRP')
        ])

        depparser = MaltParser(tagger=tagger)
        self._glue = DrtGlue(depparser=depparser, remove_duplicates=False)

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget('size'))

        self._boldfont = Font(family='helvetica',
                              weight='bold',
                              size=self._size.get())
        self._font = Font(family='helvetica', size=self._size.get())
        if self._size.get() < 0: big = self._size.get() - 2
        else: big = self._size.get() + 2
        self._bigfont = Font(family='helvetica', weight='bold', size=big)

    def _init_exampleListbox(self, parent):
        self._exampleFrame = listframe = Frame(parent)
        self._exampleFrame.pack(fill='both', side='left', padx=2)
        self._exampleList_label = Label(self._exampleFrame,
                                        font=self._boldfont,
                                        text='Examples')
        self._exampleList_label.pack()
        self._exampleList = Listbox(self._exampleFrame,
                                    selectmode='single',
                                    relief='groove',
                                    background='white',
                                    foreground='#909090',
                                    font=self._font,
                                    selectforeground='#004040',
                                    selectbackground='#c0f0c0')

        self._exampleList.pack(side='right', fill='both', expand=1)

        for example in self._examples:
            self._exampleList.insert('end', ('  %s' % example))
        self._exampleList.config(height=min(len(self._examples), 25), width=40)

        # Add a scrollbar if there are more than 25 examples.
        if len(self._examples) > 25:
            listscroll = Scrollbar(self._exampleFrame, orient='vertical')
            self._exampleList.config(yscrollcommand=listscroll.set)
            listscroll.config(command=self._exampleList.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a example, apply it.
        self._exampleList.bind('<<ListboxSelect>>', self._exampleList_select)

    def _init_readingListbox(self, parent):
        self._readingFrame = listframe = Frame(parent)
        self._readingFrame.pack(fill='both', side='left', padx=2)
        self._readingList_label = Label(self._readingFrame,
                                        font=self._boldfont,
                                        text='Readings')
        self._readingList_label.pack()
        self._readingList = Listbox(self._readingFrame,
                                    selectmode='single',
                                    relief='groove',
                                    background='white',
                                    foreground='#909090',
                                    font=self._font,
                                    selectforeground='#004040',
                                    selectbackground='#c0f0c0')

        self._readingList.pack(side='right', fill='both', expand=1)

        # Add a scrollbar if there are more than 25 examples.
        listscroll = Scrollbar(self._readingFrame, orient='vertical')
        self._readingList.config(yscrollcommand=listscroll.set)
        listscroll.config(command=self._readingList.yview)
        listscroll.pack(side='right', fill='y')

        self._populate_readingListbox()

    def _populate_readingListbox(self):
        # Populate the listbox with integers
        self._readingList.delete(0, 'end')
        for i in range(len(self._readings)):
            self._readingList.insert('end', ('  %s' % (i + 1)))
        self._readingList.config(height=min(len(self._readings), 25), width=5)

        # If they select a example, apply it.
        self._readingList.bind('<<ListboxSelect>>', self._readingList_select)

    def _init_bindings(self):
        # Key bindings are a good thing.
        self._top.bind('<Control-q>', self.destroy)
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Escape>', self.destroy)
        self._top.bind('n', self.next)
        self._top.bind('<space>', self.next)
        self._top.bind('p', self.prev)
        self._top.bind('<BackSpace>', self.prev)

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill='none', side='bottom', padx=3, pady=2)
        Button(
            buttonframe,
            text='Prev',
            background='#90c0d0',
            foreground='black',
            command=self.prev,
        ).pack(side='left')
        Button(
            buttonframe,
            text='Next',
            background='#90c0d0',
            foreground='black',
            command=self.next,
        ).pack(side='left')

    def _configure(self, event):
        self._autostep = 0
        (x1, y1, x2, y2) = self._cframe.scrollregion()
        y2 = event.height - 6
        self._canvas['scrollregion'] = '%d %d %d %d' % (x1, y1, x2, y2)
        self._redraw()

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(
            parent,
            background='white',
            #width=525, height=250,
            closeenough=10,
            border=2,
            relief='sunken')
        self._cframe.pack(expand=1, fill='both', side='top', pady=2)
        canvas = self._canvas = self._cframe.canvas()

        # Initially, there's no tree or text
        self._tree = None
        self._textwidgets = []
        self._textline = None

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Exit',
                             underline=1,
                             command=self.destroy,
                             accelerator='q')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        actionmenu = Menu(menubar, tearoff=0)
        actionmenu.add_command(label='Next',
                               underline=0,
                               command=self.next,
                               accelerator='n, Space')
        actionmenu.add_command(label='Previous',
                               underline=0,
                               command=self.prev,
                               accelerator='p, Backspace')
        menubar.add_cascade(label='Action', underline=0, menu=actionmenu)

        optionmenu = Menu(menubar, tearoff=0)
        optionmenu.add_checkbutton(label='Remove Duplicates',
                                   underline=0,
                                   variable=self._glue.remove_duplicates,
                                   command=self._toggle_remove_duplicates,
                                   accelerator='r')
        menubar.add_cascade(label='Options', underline=0, menu=optionmenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_radiobutton(label='Tiny',
                                 variable=self._size,
                                 underline=0,
                                 value=10,
                                 command=self.resize)
        viewmenu.add_radiobutton(label='Small',
                                 variable=self._size,
                                 underline=0,
                                 value=12,
                                 command=self.resize)
        viewmenu.add_radiobutton(label='Medium',
                                 variable=self._size,
                                 underline=0,
                                 value=14,
                                 command=self.resize)
        viewmenu.add_radiobutton(label='Large',
                                 variable=self._size,
                                 underline=0,
                                 value=18,
                                 command=self.resize)
        viewmenu.add_radiobutton(label='Huge',
                                 variable=self._size,
                                 underline=0,
                                 value=24,
                                 command=self.resize)
        menubar.add_cascade(label='View', underline=0, menu=viewmenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label='About', underline=0, command=self.about)
        menubar.add_cascade(label='Help', underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        canvas = self._canvas

        # Delete the old DRS, widgets, etc.
        if self._drsWidget is not None:
            self._drsWidget.clear()

        if self._drs:
            self._drsWidget = DrsWidget(self._canvas, self._drs)
            self._drsWidget.draw()

        if self._error:
            self._drsWidget = DrsWidget(self._canvas, self._error)
            self._drsWidget.draw()

    #########################################
    ##  Button Callbacks
    #########################################

    def destroy(self, *e):
        self._autostep = 0
        if self._top is None: return
        self._top.destroy()
        self._top = None

    def prev(self, *e):
        selection = self._readingList.curselection()
        readingListSize = self._readingList.size()

        # there are readings
        if readingListSize > 0:
            # if one reading is currently selected
            if len(selection) == 1:
                index = int(selection[0])

                # if it's on (or before) the first item
                if index <= 0:
                    self._select_previous_example()
                else:
                    self._readingList_store_selection(index - 1)

            else:
                #select its first reading
                self._readingList_store_selection(readingListSize - 1)

        else:
            self._select_previous_example()

    def _select_previous_example(self):
        #if the current example is not the first example
        if self._curExample > 0:
            self._exampleList_store_selection(self._curExample - 1)
        else:
            #go to the last example
            self._exampleList_store_selection(len(self._examples) - 1)

    def next(self, *e):
        selection = self._readingList.curselection()
        readingListSize = self._readingList.size()

        # if there are readings
        if readingListSize > 0:
            # if one reading is currently selected
            if len(selection) == 1:
                index = int(selection[0])

                # if it's on (or past) the last item
                if index >= (readingListSize - 1):
                    self._select_next_example()
                else:
                    self._readingList_store_selection(index + 1)

            else:
                #select its first reading
                self._readingList_store_selection(0)

        else:
            self._select_next_example()

    def _select_next_example(self):
        #if the current example is not the last example
        if self._curExample < len(self._examples) - 1:
            self._exampleList_store_selection(self._curExample + 1)
        else:
            #go to the first example
            self._exampleList_store_selection(0)

    def about(self, *e):
        ABOUT = (
            "NLTK Discourse Representation Theory (DRT) Glue Semantics Demo\n"
            + "Written by Daniel H. Garrette")
        TITLE = 'About: NLTK DRT Glue Demo'
        try:
            from tkMessageBox import Message
            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def postscript(self, *e):
        self._autostep = 0
        self._cframe.print_to_file()

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle(): return
        self._top.mainloop(*args, **kwargs)

    def resize(self, size=None):
        if size is not None: self._size.set(size)
        size = self._size.get()
        self._font.configure(size=-(abs(size)))
        self._boldfont.configure(size=-(abs(size)))
        self._sysfont.configure(size=-(abs(size)))
        self._bigfont.configure(size=-(abs(size + 2)))
        self._redraw()

    def _toggle_remove_duplicates(self):
        self._glue.remove_duplicates = not self._glue.remove_duplicates

        self._exampleList.selection_clear(0, 'end')
        self._readings = []
        self._populate_readingListbox()
        self._readingCache = [None for ex in self._examples]
        self._curExample = -1
        self._error = None

        self._drs = None
        self._redraw()

    def _exampleList_select(self, event):
        selection = self._exampleList.curselection()
        if len(selection) != 1: return
        self._exampleList_store_selection(int(selection[0]))

    def _exampleList_store_selection(self, index):
        self._curExample = index
        example = self._examples[index]

        self._exampleList.selection_clear(0, 'end')
        if example:
            cache = self._readingCache[index]
            if cache:
                if isinstance(cache, list):
                    self._readings = cache
                    self._error = None
                else:
                    self._readings = []
                    self._error = cache
            else:
                try:
                    self._readings = self._glue.parse_to_meaning(example)
                    self._error = None
                    self._readingCache[index] = self._readings
                except Exception as e:
                    self._readings = []
                    self._error = DrtVariableExpression(
                        Variable('Error: ' + str(e)))
                    self._readingCache[index] = self._error

                    #add a star to the end of the example
                    self._exampleList.delete(index)
                    self._exampleList.insert(index, ('  %s *' % example))
                    self._exampleList.config(height=min(
                        len(self._examples), 25),
                                             width=40)

            self._populate_readingListbox()

            self._exampleList.selection_set(index)

            self._drs = None
            self._redraw()

    def _readingList_select(self, event):
        selection = self._readingList.curselection()
        if len(selection) != 1: return
        self._readingList_store_selection(int(selection[0]))

    def _readingList_store_selection(self, index):
        reading = self._readings[index]

        self._readingList.selection_clear(0, 'end')
        if reading:
            self._readingList.selection_set(index)

            self._drs = reading.simplify().normalize().resolve_anaphora()

            self._redraw()
Example #30
0
#!/usr/bin/python

import os
from Tkinter import Tk, Label, Button, Entry, ACTIVE

root = Tk()
root.wm_title("Enter MFA Token")

Label(root, text="Token").pack()
entry = Entry(root)
entry.pack(padx=5)


def done():
    print entry.get()
    root.destroy()

b = Button(root, text="OK", default=ACTIVE, command=done)
b.pack(pady=5)

entry.focus_force()
root.bind('<Return>', (lambda e, b=b: b.invoke()))
os.system(('''/usr/bin/osascript -e 'tell app "Finder" to set '''
           '''frontmost of process "Python" to true' '''))
root.mainloop()
Example #31
0
        survive_rule = [2, 3]
        born_rule = [3]


root = Tk()
root.title("Game of Life")
frame = Frame(root, width=720, height=720)
frame.pack()
canvas = Canvas(frame, width=720, height=720)
canvas.pack()
universe = set()
create_grid()
#frame = Frame(root)
start = Button(root, text="Start", command=begin)
start.pack(side=LEFT)
stop = Button(root, text="Stop", command=stop)
stop.pack(side=LEFT)
clear = Button(root, text="Erase", command=clear)
clear.pack(side=LEFT)
text = Entry(root)
text.insert(0, "23/3")
text.pack(side=LEFT)
canvas.bind("<Button-1>", change_colour_on_click)
canvas.bind("<Button-3>", change_colour_on_click)
canvas.bind("<B1-Motion>", fill_on_click)
canvas.bind("<B3-Motion>", clear_on_click)
root.bind("<space>", step_ev)
#frame.pack()

root.mainloop()
Example #32
0
    if y >= 0.0:
        canvas.after(1, tick)


def space(evt):
    global vy, space_count
    if space_count < 20:
        vy += 1
        space_count += 1


root = Tk()
canvas = Canvas(root, width=w, height=h, bg='black')
canvas.pack()

root.bind('<space>', space)
#creates background
img1 = Image.open('earthrise.jpg').resize((w, h))
pmg1 = ImageTk.PhotoImage(img1)
canvas.create_image(w / 2, h / 2, image=pmg1)

#opens eagle.jpg
img2 = Image.open('eagle.jpg').resize((200, 200))
pmg2 = ImageTk.PhotoImage(img2)
ship = canvas.create_image(w / 4, 0, image=pmg2)

#creates landing pad
canvas.create_rectangle(w/4-150,int(0.5+0.7*h)+100,w/4+150,\
int(0.5+0.7*h)+125,outline = 'green',fill = 'green')

f = ('Times', 36, 'bold')
Example #33
0
    return vals



def reset_station():
#     listbox.delete(0, END)
     #listbox.insert(END, '')
    tree.delete(*tree.get_children())
            
if __name__ == '__main__':
    root = Tk()
    Label(root, text = "GoBike Station Recommendation", fg = "blue", font = "Verdana 20 bold").pack()
 #   listbox = Listbox(root, width = 150, height = 10)
#    listbox.pack(expand = True)
    ents = makeform(root, fields, OPTIONS)
    root.bind('<Return>', (lambda event, e=ents: fetch(e))) 
    global vals
    vals = fetch(ents)
    print vals

    fm = Frame(root)
    b1 = Button(fm, text='Show', command=(lambda e=ents: fetch(e)))
    b1.pack(side=LEFT, padx=5, pady=5)
 #   lb = Listbox(root)
    
    b = Button(fm, text="Reset",
           command=reset_station)
    b.pack(side=LEFT, padx=5, pady=5)
    fm.pack(fill=BOTH, expand = YES)
    car_header = ['rank', 'station_name', 'distance', 'duration', 'metric']
    root.title("GoApp")
Btn08.bind('<ButtonPress-1>', x_decrease)
Btn09.bind('<ButtonPress-1>', y_decrease)
Btn10.bind('<ButtonPress-1>', y_increase)
Btn11.bind('<ButtonPress-1>', xy_home)
# Btn07.bind('<ButtonRelease-1>', home_fun)
# Btn08.bind('<ButtonRelease-1>', home_fun)
# Btn09.bind('<ButtonRelease-1>', home_fun)
# Btn10.bind('<ButtonRelease-1>', home_fun)
# Btn11.bind('<ButtonRelease-1>', home_fun)

# =============================================================================
# Bind buttons on the keyboard with the corresponding callback function to
# control the car remotely with the keyboard.
# =============================================================================
top.bind(
    '<KeyPress-q>',
    left_fun)  # Press down key 'A' on the keyboard and the car will turn left.
top.bind('<KeyPress-d>', right_fun)
top.bind('<KeyPress-s>', backward_fun)
top.bind('<KeyPress-z>', forward_fun)
top.bind('<KeyPress-h>', home_fun)
top.bind('<KeyRelease-q>',
         home_fun)  # Release key 'A' and the car will turn back.
top.bind('<KeyRelease-d>', home_fun)
top.bind('<KeyRelease-s>', stop_fun)
top.bind('<KeyRelease-z>', stop_fun)

spd = 50


def changeSpeed(ev=None):
Example #35
0
DOOR_CABLES = 4


def end_fullscreen(self, event=None):
    win.state = False
    win.attributes("-fullscreen", False)
    win.geometry("200x200")
    return "break"


logging.basicConfig(filename='logfile.log',
                    level=logging.DEBUG,
                    format='%(asctime)s %(message)s')
win = Tk()
win.attributes("-fullscreen", True)
win.bind("<Escape>", end_fullscreen)
myFont = tkFont.Font(family='Helvetica', size=24, weight='bold')


#python don't have switch or case
def decrement_stock(num_door):
    global STOCK_HEADSETS
    global STOCK_MOUSES
    global STOCK_KEYBOARDS
    global STOCK_CABLES
    if num_door == DOOR_HEADSETS:
        STOCK_HEADSETS -= 1
        if STOCK_HEADSETS == 0:
            headsetButton.config(state="disabled")
    elif num_door == DOOR_MOUSES:
        STOCK_MOUSES -= 1
Example #36
0
    blue.walk(0.1, 0)


def bluebackward(event):
    blue.walk(-0.1, 0)


def blueleft(event):
    blue.walk(0, 0, angle=20)


def blueright(event):
    blue.walk(0, 0, angle=-20)


tkinst.bind("w", redfoward)
tkinst.bind("s", redbackward)
tkinst.bind("a", redleft)
tkinst.bind("d", redright)

tkinst.bind("i", bluefoward)
tkinst.bind("k", bluebackward)
tkinst.bind("j", blueleft)
tkinst.bind("l", blueright)

frame = Frame(tkinst, height=1000, width=1280)

if __name__ == "__main__":
    if usevid:
        thread0 = myThread(0, "video", frame)
        #thread1 = myThread(1, "red")
Example #37
0
output_label.grid(row=3,column=0,rowspan=1,columnspan=1,sticky=N+S+W+E,padx=PADDING,pady=PADDING)
output_box.grid(row=4,column=0,rowspan=2,columnspan=3,sticky=N+S+W+E,padx=PADDING,pady=PADDING)
submit_button.grid(row=5, column=3,sticky=N+S+W+E,padx=PADDING,pady=PADDING)
submit_button.bind("<Button-1>", click_down)
submit_button.bind("<ButtonRelease-1>", click_up)		

for x in range(1,root.grid_size()[0] - 1):
    root.grid_columnconfigure(x, weight=1,minsize=20)


root.grid_rowconfigure(0, weight=0,minsize=5)
root.grid_rowconfigure(1, weight=0,minsize=10)
root.grid_rowconfigure(2, weight=0,minsize=10)
root.grid_rowconfigure(3, weight=0,minsize=5)
root.grid_rowconfigure(4, weight=1,minsize=10)
root.grid_rowconfigure(5, weight=0,minsize=10)

input_box.bind("<Command-Return>", return_press)
output_box.bind("<Command-Return>", return_press)
root.bind("<Command-Return>", return_press)
input_box.bind("<Command-a>", select_all)
output_box.bind("<Command-a>", select_all)

root.title("Latin Translator")
root.geometry(str(WIDTH)+"x"+str(HEIGHT))
root.minsize(str(WIDTH),str(HEIGHT))
root.configure(background='#757575')
root.after(500, focus)
root.mainloop()

Example #38
0
        lines[1][0].set_data(t2, amplit)
        lines[1][1].set_data(t2, fdamp)

        lines[2][0].set_data(t2, signal)
        lines[2][1].set_data(t2, instfreq)

        lines[3][0].set_data(fdamp2, instfreq)
        lines[3][1].set_data(fdamp2, tswafit)

        for ax in axes:
            ax.relim()
            ax.autoscale_view(tight=True, scalex=True, scaley=True)

        fig.canvas.draw()
        return
    root.bind('<<update_plots>>', update_plots)

    q['update_results'] = Queue()
    def update_results(event):
        resultsdata = q['update_results'].get()
        res_amp, res_tau, res_tswa = resultsdata
        if res_tau[1]/res_tau[0] < 0.05:
            if epics['write_amp'].get():
                pv.ampl.put(res_amp[0])
            if epics['write_tau'].get():
                pv.tau.put(res_tau[0])
            if epics['write_tswa'].get():
                pv.tswa.put(res_tswa[0])
            results['amp'].set(('{0:.2f} ' + u'\u00B1' + ' {1:.2f} mm').format(*res_amp))
            results['tau'].set(('{0:.2f} ' + u'\u00B1' + ' {1:.2f} ms').format(*res_tau))
            results['tswa'].set(('{0:.2f} ' + u'\u00B1' + ' {1:.2f} Hz/mm' + u'\u00B2').format(*res_tswa))
Example #39
0
class Visualiser(Thread):
    """Superclass of both the realtime and offline VTK visualisers
    """
    def __init__(self, source):
        Thread.__init__(self)

        self.source = source

        # Structures for Height Based quantities
        self.height_quantities = []
        self.height_zScales = {}
        self.height_dynamic = {}
        self.height_offset = {}
        self.height_opacity = {}
        self.height_wireframe = {}

        # Structures for colouring quantities
        self.colours_height = {}

        # Structures used for VTK
        self.vtk_actors = {}
        self.vtk_axesSet = False
        self.vtk_drawAxes = False
        self.vtk_mappers = {}
        self.vtk_polyData = {}

        # A list of operations to be performed on the cube axes. Type: [(func, (args))]
        self.conf_axesAlterations = []
        # A list of all polygons to overlay. Type: [([coords], height, (colour)]
        self.conf_overlaidPolygons = []
        # A list of alterations to be performed on the Tk root. Type: [(func, (args))]
        self.conf_tkAlterations = []

    def run(self):
        self.vtk_renderer = vtkRenderer()
        self.setup_gui()
        self.setup_grid()

        # Handle any deferred configuration
        # Overlaid polygons
        for args in self.conf_overlaidPolygons:
            self.overlay_polygon_internal(*args)
        # Draw (and maybe alter) the axes
        if self.vtk_drawAxes:
            self.vtk_axes = vtkCubeAxesActor2D()
            # Perform all of the alterations required, by applying func to the vtk_axes instance (with the given args).
            for func, args in self.conf_axesAlterations:
                func(*((self.vtk_axes,) + args))
        # Alter the Tk root as necessary.
        for func, args in self.conf_tkAlterations:
            func(*((self.tk_root,) + args))
        # Finished with deferred configuration.

        # Draw Height Quantities
        for q in self.height_quantities:
            self.update_height_quantity(q, self.height_dynamic[q])
            self.draw_height_quantity(q)
            
        self.tk_root.mainloop()

    def redraw_quantities(self):
        """Redraw all dynamic quantities.
        """
        # Height quantities
        for q in self.height_quantities:
            if (self.height_dynamic[q]):
                self.update_height_quantity(q, self.height_dynamic[q])
                self.draw_height_quantity(q)
        if self.vtk_drawAxes is True:
            self.draw_axes()

    # --- Axes --- #
        
    def render_axes(self):
        """Intstruct the visualiser to render cube axes around the render.
        """
        self.vtk_drawAxes = True

    def draw_axes(self):
        """Update the 3D bounds on the axes and add them to the pipeline if not yet connected.
        """
        self.vtk_axes.SetBounds(self.get_3d_bounds())
        if not self.vtk_axesSet:
            self.vtk_axesSet = True
            self.vtk_axes.SetCamera(self.vtk_renderer.GetActiveCamera())
            self.vtk_renderer.AddActor(self.vtk_axes)
            self.vtk_renderer.ResetCamera(self.get_3d_bounds())
        
    def alter_axes(self, func, args):
        """Attempt to apply the function 'func' with args tuple 'args' to the
        vtkCubeAxesActor2D instance set up by render_axes. This is done this way to ensure
        the axes setup is handled in the visualiser thread.

        Example call:
        from vtk import vtkCubeAxesActor2D
        alter_axes(vtkCubeAxesActor2D.SetNumberOfPoints, (5,))
        """
        self.conf_axesAlterations.append((func, args))
            
    # --- Height Based Rendering --- #

    def setup_grid(self):
        """Create the vtkCellArray instance that represents the
        triangles. Subclasses are expected to override this function
        to read from their source as appropriate. The vtkCellArray should
        be stored to self.vtk_cells.
        """
        pass

    def render_quantity_height(self, quantityName, zScale=1.0, offset=0.0, opacity=1.0, dynamic=True, wireframe=False):
        """Instruct the visualiser to render a quantity using the
        value at a point as its height.  The value at each point is
        multiplied by z_scale and is added to offset, and if
        dynamic=False, the quantity is not recalculated on each
        update.
        """
        self.height_quantities.append(quantityName)
        self.height_zScales[quantityName] = zScale
        self.height_offset[quantityName] = offset
        self.height_dynamic[quantityName] = dynamic
        self.height_opacity[quantityName] = opacity
        self.height_wireframe[quantityName] = wireframe

    def update_height_quantity(self, quantityName, dynamic=True):
        """Create a vtkPolyData object and store it in
        self.vtk_polyData[quantityName]. Subclasses are expected to override this
        function.
        """
        pass

    def get_3d_bounds(self):
        """Get the minimum and maximum bounds for the x, y and z directions.
        Return as a list of double in the order (xmin, xmax, ymin, ymax, zmin, zmax),
        suitable for passing to vtkCubeAxesActor2D::SetRanges(). Subclasses are expected
        to override this function.
        """
        pass



    def store_height_quantity(self, quantityName, fileName=None):

        if fileName is None:
            fileName = quantityName + '.vtk'

        quantity_polyData = self.vtk_polyData[quantityName]

        import vtk
        w = vtk.vtkPolyDataWriter()
        #print quantity_polyData
        w.SetInput(quantity_polyData)
        w.SetFileName(fileName)
        w.Write()



    def draw_height_quantity(self, quantityName):
        """Use the vtkPolyData and prepare/update the rest of the VTK
        rendering pipeline.
        """
        if self.vtk_mappers.has_key(quantityName):
            mapper = self.vtk_mappers[quantityName]
        else:
            mapper = self.vtk_mappers[quantityName] = vtkPolyDataMapper()
        mapper.SetInput(self.vtk_polyData[quantityName])
        mapper.Update()

        if not self.vtk_actors.has_key(quantityName):
            actor = self.vtk_actors[quantityName] = vtkActor()
            actor.GetProperty().SetOpacity(self.height_opacity[quantityName])
            if self.height_wireframe[quantityName]:
                actor.GetProperty().SetRepresentationToWireframe()
            actor.SetMapper(mapper)
            self.vtk_renderer.AddActor(actor)
        else:
            actor = self.vtk_actors[quantityName]

        if self.colours_height.has_key(quantityName):
            colour = self.colours_height[quantityName]
            if type(colour) == TupleType:
                if type(colour[0]) == FunctionType:
                    # It's a function, so take colour[1] as the
                    # lower bound on the scalar range and
                    # colour[2] as the upper bound on the scalar
                    # range.
                    scalars = vtkFloatArray()

                    map(scalars.InsertNextValue, colour[0](self.build_quantity_dict()))
                    self.vtk_polyData[quantityName].GetPointData().SetScalars(scalars)
                    mapper.SetScalarRange(colour[1:])
                    mapper.Update()
                else:
                    # It's a 3-tuple representing an RGB value.
                    actor.GetProperty().SetColor(colour)
            else:
                actor.GetProperty().SetColor(0.5, 0.5, 0.5)
        else:
            actor.GetProperty().SetColor(0.5, 0.5, 0.5)

    # --- Colour Coding --- #

    def build_quantity_dict(self):
        """Build and return a dictionary mapping quantity name->Numeric array of vertex
        values for that quantity. Subclasses are expected to override
        this function."""
        pass

    def colour_height_quantity(self, quantityName, colour=(0.5, 0.5, 0.5)):
        """Add colouring to a height based quantity.

        The colour parameter can be one of the following:
        - a 3-tuple of values in [0,1] to specify R, G, B values
        - a 3-tuple of values:
          - a function that takes a dictionary mapping quantity name->Numeric array of vertex values.
            This function returns a list of vertex values to be used in the colour coding.
          - a float for the lower bound on the colouring
          - a float for the upper bound on the colouring
        """
        self.colours_height[quantityName] = colour

    # --- Overlaid Polygons --- #

    def overlay_polygon(self, coords, height=0.0, colour=(1.0, 0.0, 0.0)):
        """Add a polygon to the output of the visualiser.

        coords is a list of 2-tuples representing x and y coordinates.
        These are triangulated by vtkDelaunay2D.

        height is the z-value given to all points.

        colour is the colour of the polygon, as a 3-tuple representing
        r, g, b values between 0 and 1."""
        self.conf_overlaidPolygons.append((coords, height, colour))

    def overlay_polygon_internal(self, coords, height, colour):
        """Add a polygon to the output of the visualiser.

        coords is a list of 2-tuples representing x and y coordinates.
        These are triangulated by vtkDelaunay2D.

        height is the z-value given to all points.

        colour is the colour of the polygon, as a 3-tuple representing
        r, g, b values between 0 and 1.

        This function should not be called from outside the visualiser thread.
        Use overlay_polygon instead.
    
        """
        points = vtkPoints()
        for coord in coords:
            points.InsertNextPoint(coord[0], coord[1], height)
        profile = vtkPolyData()
        profile.SetPoints(points)
        delny = vtkDelaunay2D()
        delny.SetInput(profile)
        mesh = vtkPolyDataMapper()
        mesh.SetInput(delny.GetOutput())
        actor = vtkActor()
        actor.SetMapper(mesh)
        actor.GetProperty().SetColor(colour)
        self.vtk_renderer.AddActor(actor)
        
    # --- Vector Fields --- #

    # --- GUI Setup --- #

    def setup_gui(self):
        self.tk_root = Tk()
        self.tk_root.title("Visualisation")
        self.tk_root.after(100, self.redraw)
        self.tk_root.bind("<Destroy>", self.destroyed)
        self.tk_root.grid_rowconfigure(0, weight=1)
        self.tk_root.grid_columnconfigure(0, weight=1)

        self.tk_renderWidget = vtkTkRenderWidget(self.tk_root, width=400, height=400)
        self.tk_renderWidget.grid(row=0, column=0, sticky=N+S+E+W)
        self.tk_controlFrame = Frame(self.tk_root)
        self.tk_controlFrame.grid(row=1, column=0, sticky=E+W)
        self.tk_controlFrame.grid_rowconfigure(0, weight=1)
        self.tk_controlFrame.grid_columnconfigure(0, weight=1)
        
        self.tk_quit = Button(self.tk_controlFrame, text="Quit", command=self.shutdown)
        self.tk_quit.grid(row=0, column=0, sticky=E+W)
        self.tk_renderWidget.GetRenderWindow().AddRenderer(self.vtk_renderer)

    def alter_tkroot(self, func, args):
        """Apply func, with arguments tuple args to the root tk window for this visualiser.
        """
        self.conf_tkAlterations.append((func, args))

    # --- GUI Events --- #

    def destroyed(self, event):
        if event.widget == self.tk_root:
            self.shutdown()

    def redraw(self):
        self.tk_renderWidget.GetRenderWindow().Render()
        self.tk_root.update_idletasks()
        self.tk_root.after(100, self.redraw)

    def shutdown(self):
        self.tk_root.withdraw()
        self.tk_root.destroy()
Example #40
0
        n = (n+1)%len(pics)
    elif direction == "prev":
        n = (n-1)%len(pics)
    else:
        raise Exception("Got invalid direction")
    if n == current:
        updatePos(direction)

def changePic(direction):
    global n
    updatePos(direction)
    img = Image.open("../slideshow/"+slides[n])
    img = resize(img)
    photo = ImageTk.PhotoImage(img)
    panel.configure(image = photo)
    panel.image = photo

def resize(image):
    width, height = image.size
    print "ratio", width/float(height)
    ratio = max(width/float(size[0]), height/float(size[1]))
    return image.resize((int(width/ratio), int(height/ratio)), Image.ANTIALIAS)

root.after(0, autoChange) # set the initial image, no delay
root.bind("<Right>", callbackRight) # debug key control
root.bind("<Left>", callbackLeft) # debug key control
root.mainloop()

# Stop the program execution after the slideshow is closed
running = False
print "Terminating"
Example #41
0
#Terminal_window.config(yscrollcommand=terminal_scroll.set)

label_filename = Label(root, text="File path")
label_chip = Label(root, text="Chip")
label_frequency = Label(root, text="Frequency")
label_programmer = Label(root, text="Programmer")
label_lfuse = Label(root, text="Low fuse")
label_hfuse = Label(root, text="High fuse")
label_key_comp = Label(root, text="Compile : Ctrl+R")
label_key_flash = Label(root, text="Flash : Ctrl+F")

fuse_deact()

###----------Keys press-----------###

root.bind('<Control-r>', lambda e: key_comp())

root.bind('<Control-f>', lambda e: key_flash())

#####-------------- grid------------

label_filename.grid(row=0, column=0, padx=5, pady=5, sticky=E)
file_path_entry.grid(row=0, column=1, columnspan=3, padx=5, pady=5, sticky=W)
button_open.grid(row=0, column=5, padx=5, pady=5)

label_chip.grid(row=1, column=0, pady=5, sticky=E)
Chip_combobox.grid(row=1, column=1, pady=5, padx=5, sticky=W)

label_frequency.grid(row=1, column=2, pady=5, sticky=E)
frequency_entry.grid(row=1, column=3, sticky=W)
button_compile.grid(row=1, column=5, padx=5, pady=5)
Example #42
0
class DrtGlueDemo(object):
    def __init__(self, examples):
        # Set up the main window.
        self._top = Tk()
        self._top.title('DRT Glue Demo')

        # Set up key bindings.
        self._init_bindings()

        # Initialize the fonts.self._error = None
        self._init_fonts(self._top)

        self._examples = examples
        self._readingCache = [None for example in examples]

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Set the data to None
        self._curExample = -1
        self._readings = []
        self._drs = None
        self._drsWidget = None
        self._error = None

        self._init_glue()

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_exampleListbox(self._top)
        self._init_readingListbox(self._top)
        self._init_canvas(self._top)

        # Resize callback
        self._canvas.bind('<Configure>', self._configure)

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_glue(self):
        tagger = RegexpTagger(
            [('^(David|Mary|John)$', 'NNP'),
             ('^(walks|sees|eats|chases|believes|gives|sleeps|chases|persuades|tries|seems|leaves)$', 'VB'),
             ('^(go|order|vanish|find|approach)$', 'VB'),
             ('^(a)$', 'ex_quant'),
             ('^(every)$', 'univ_quant'),
             ('^(sandwich|man|dog|pizza|unicorn|cat|senator)$', 'NN'),
             ('^(big|gray|former)$', 'JJ'),
             ('^(him|himself)$', 'PRP')
        ])

        depparser = MaltParser(tagger=tagger)
        self._glue = DrtGlue(depparser=depparser, remove_duplicates=False)

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget('size'))

        self._boldfont = Font(family='helvetica', weight='bold',
                                    size=self._size.get())
        self._font = Font(family='helvetica',
                                    size=self._size.get())
        if self._size.get() < 0: big = self._size.get()-2
        else: big = self._size.get()+2
        self._bigfont = Font(family='helvetica', weight='bold',
                                    size=big)

    def _init_exampleListbox(self, parent):
        self._exampleFrame = listframe = Frame(parent)
        self._exampleFrame.pack(fill='both', side='left', padx=2)
        self._exampleList_label = Label(self._exampleFrame, font=self._boldfont,
                                     text='Examples')
        self._exampleList_label.pack()
        self._exampleList = Listbox(self._exampleFrame, selectmode='single',
                                 relief='groove', background='white',
                                 foreground='#909090', font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._exampleList.pack(side='right', fill='both', expand=1)

        for example in self._examples:
            self._exampleList.insert('end', ('  %s' % example))
        self._exampleList.config(height=min(len(self._examples), 25), width=40)

        # Add a scrollbar if there are more than 25 examples.
        if len(self._examples) > 25:
            listscroll = Scrollbar(self._exampleFrame,
                                   orient='vertical')
            self._exampleList.config(yscrollcommand = listscroll.set)
            listscroll.config(command=self._exampleList.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a example, apply it.
        self._exampleList.bind('<<ListboxSelect>>', self._exampleList_select)

    def _init_readingListbox(self, parent):
        self._readingFrame = listframe = Frame(parent)
        self._readingFrame.pack(fill='both', side='left', padx=2)
        self._readingList_label = Label(self._readingFrame, font=self._boldfont,
                                     text='Readings')
        self._readingList_label.pack()
        self._readingList = Listbox(self._readingFrame, selectmode='single',
                                 relief='groove', background='white',
                                 foreground='#909090', font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._readingList.pack(side='right', fill='both', expand=1)

        # Add a scrollbar if there are more than 25 examples.
        listscroll = Scrollbar(self._readingFrame,
                               orient='vertical')
        self._readingList.config(yscrollcommand = listscroll.set)
        listscroll.config(command=self._readingList.yview)
        listscroll.pack(side='right', fill='y')

        self._populate_readingListbox()

    def _populate_readingListbox(self):
        # Populate the listbox with integers
        self._readingList.delete(0, 'end')
        for i in range(len(self._readings)):
            self._readingList.insert('end', ('  %s' % (i+1)))
        self._readingList.config(height=min(len(self._readings), 25), width=5)

        # If they select a example, apply it.
        self._readingList.bind('<<ListboxSelect>>', self._readingList_select)

    def _init_bindings(self):
        # Key bindings are a good thing.
        self._top.bind('<Control-q>', self.destroy)
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Escape>', self.destroy)
        self._top.bind('n', self.next)
        self._top.bind('<space>', self.next)
        self._top.bind('p', self.prev)
        self._top.bind('<BackSpace>', self.prev)

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill='none', side='bottom', padx=3, pady=2)
        Button(buttonframe, text='Prev',
               background='#90c0d0', foreground='black',
               command=self.prev,).pack(side='left')
        Button(buttonframe, text='Next',
               background='#90c0d0', foreground='black',
               command=self.next,).pack(side='left')

    def _configure(self, event):
        self._autostep = 0
        (x1, y1, x2, y2) = self._cframe.scrollregion()
        y2 = event.height - 6
        self._canvas['scrollregion'] = '%d %d %d %d' % (x1,y1,x2,y2)
        self._redraw()

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(parent, background='white',
                                   #width=525, height=250,
                                   closeenough=10,
                                   border=2, relief='sunken')
        self._cframe.pack(expand=1, fill='both', side='top', pady=2)
        canvas = self._canvas = self._cframe.canvas()

        # Initially, there's no tree or text
        self._tree = None
        self._textwidgets = []
        self._textline = None

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Exit', underline=1,
                             command=self.destroy, accelerator='q')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        actionmenu = Menu(menubar, tearoff=0)
        actionmenu.add_command(label='Next', underline=0,
                               command=self.next, accelerator='n, Space')
        actionmenu.add_command(label='Previous', underline=0,
                               command=self.prev, accelerator='p, Backspace')
        menubar.add_cascade(label='Action', underline=0, menu=actionmenu)

        optionmenu = Menu(menubar, tearoff=0)
        optionmenu.add_checkbutton(label='Remove Duplicates', underline=0,
                                   variable=self._glue.remove_duplicates,
                                   command=self._toggle_remove_duplicates,
                                   accelerator='r')
        menubar.add_cascade(label='Options', underline=0, menu=optionmenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_radiobutton(label='Tiny', variable=self._size,
                                 underline=0, value=10, command=self.resize)
        viewmenu.add_radiobutton(label='Small', variable=self._size,
                                 underline=0, value=12, command=self.resize)
        viewmenu.add_radiobutton(label='Medium', variable=self._size,
                                 underline=0, value=14, command=self.resize)
        viewmenu.add_radiobutton(label='Large', variable=self._size,
                                 underline=0, value=18, command=self.resize)
        viewmenu.add_radiobutton(label='Huge', variable=self._size,
                                 underline=0, value=24, command=self.resize)
        menubar.add_cascade(label='View', underline=0, menu=viewmenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label='About', underline=0,
                             command=self.about)
        menubar.add_cascade(label='Help', underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        canvas = self._canvas

        # Delete the old DRS, widgets, etc.
        if self._drsWidget is not None:
            self._drsWidget.clear()

        if self._drs:
            self._drsWidget = DrsWidget( self._canvas, self._drs )
            self._drsWidget.draw()

        if self._error:
            self._drsWidget = DrsWidget( self._canvas, self._error )
            self._drsWidget.draw()

    #########################################
    ##  Button Callbacks
    #########################################

    def destroy(self, *e):
        self._autostep = 0
        if self._top is None: return
        self._top.destroy()
        self._top = None

    def prev(self, *e):
        selection = self._readingList.curselection()
        readingListSize = self._readingList.size()

        # there are readings
        if readingListSize > 0:
            # if one reading is currently selected
            if len(selection) == 1:
                index = int(selection[0])

                # if it's on (or before) the first item
                if index <= 0:
                    self._select_previous_example()
                else:
                    self._readingList_store_selection(index-1)

            else:
                #select its first reading
                self._readingList_store_selection(readingListSize-1)

        else:
            self._select_previous_example()


    def _select_previous_example(self):
        #if the current example is not the first example
        if self._curExample > 0:
            self._exampleList_store_selection(self._curExample-1)
        else:
            #go to the last example
            self._exampleList_store_selection(len(self._examples)-1)

    def next(self, *e):
        selection = self._readingList.curselection()
        readingListSize = self._readingList.size()

        # if there are readings
        if readingListSize > 0:
            # if one reading is currently selected
            if len(selection) == 1:
                index = int(selection[0])

                # if it's on (or past) the last item
                if index >= (readingListSize-1):
                    self._select_next_example()
                else:
                    self._readingList_store_selection(index+1)

            else:
                #select its first reading
                self._readingList_store_selection(0)

        else:
            self._select_next_example()

    def _select_next_example(self):
        #if the current example is not the last example
        if self._curExample < len(self._examples)-1:
            self._exampleList_store_selection(self._curExample+1)
        else:
            #go to the first example
            self._exampleList_store_selection(0)


    def about(self, *e):
        ABOUT = ("NLTK Discourse Representation Theory (DRT) Glue Semantics Demo\n"+
                 "Written by Daniel H. Garrette")
        TITLE = 'About: NLTK DRT Glue Demo'
        try:
            from tkMessageBox import Message
            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def postscript(self, *e):
        self._autostep = 0
        self._cframe.print_to_file()

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle(): return
        self._top.mainloop(*args, **kwargs)

    def resize(self, size=None):
        if size is not None: self._size.set(size)
        size = self._size.get()
        self._font.configure(size=-(abs(size)))
        self._boldfont.configure(size=-(abs(size)))
        self._sysfont.configure(size=-(abs(size)))
        self._bigfont.configure(size=-(abs(size+2)))
        self._redraw()

    def _toggle_remove_duplicates(self):
        self._glue.remove_duplicates = not self._glue.remove_duplicates

        self._exampleList.selection_clear(0, 'end')
        self._readings = []
        self._populate_readingListbox()
        self._readingCache = [None for ex in self._examples]
        self._curExample = -1
        self._error = None

        self._drs = None
        self._redraw()


    def _exampleList_select(self, event):
        selection = self._exampleList.curselection()
        if len(selection) != 1: return
        self._exampleList_store_selection(int(selection[0]))

    def _exampleList_store_selection(self, index):
        self._curExample = index
        example = self._examples[index]

        self._exampleList.selection_clear(0, 'end')
        if example:
            cache = self._readingCache[index]
            if cache:
                if isinstance(cache, list):
                    self._readings = cache
                    self._error = None
                else:
                    self._readings = []
                    self._error = cache
            else:
                try:
                    self._readings = self._glue.parse_to_meaning(example)
                    self._error = None
                    self._readingCache[index] = self._readings
                except Exception, e:
                    self._readings = []
                    self._error = DrtVariableExpression(Variable('Error: ' + str(e)))
                    self._readingCache[index] = self._error

                    #add a star to the end of the example
                    self._exampleList.delete(index)
                    self._exampleList.insert(index, ('  %s *' % example))
                    self._exampleList.config(height=min(len(self._examples), 25), width=40)

            self._populate_readingListbox()

            self._exampleList.selection_set(index)

            self._drs = None
            self._redraw()
def main():
    settings_file = "settings.yaml"
    photos = []
    gauth = GoogleAuth(settings_file=settings_file)
    gauth.CommandLineAuth()
    drive = GoogleDrive(gauth)

    print "All files in root:"
    # Auto-iterate through all files that matches this query
    file_list = drive.ListFile({
        'q': "'root' in parents and trashed=false"
    }).GetList()

    print "List folders"
    for file1 in file_list:
        #print 'title: %s, id: %s' % (file1['title'], file1['id'])
        #print 'mime: %s' % (file1['mimeType'])
        if file1['mimeType'] == "application/vnd.google-apps.folder":
            if file1['title'] == "Google Photos":
                print "Found your photos:"
                print 'Folder: %s, Id: %s' % (file1['title'], file1['id'])
                found = True

    if found == False:
        print "Error, no Google Photos folder found"
        sys.exit()

    # Google Photos folder id =1Q4Xk107tDLn4SdoHOqZwy5AGyvIm2bNO1uubxlMqx34
    # (found above)
    #folder_id="1Q4Xk107tDLn4SdoHOqZwy5AGyvIm2bNO1uubxlMqx34"
    #title: 2016, id: 1efl45Zs9_cFLEXzRERqqxIQp3Q
    folder_id = "1efl45Zs9_cFLEXzRERqqxIQp3Q"  #
    print "List files in folder 2016"

    _q = {'q': "'{}' in parents and trashed=false".format(folder_id)}
    photolist = drive.ListFile(_q).GetList()
    for file1 in photolist:
        #print 'title: %s, id: %s' % (file1['title'], file1['id'])
        #print 'mime: %s' % (file1['mimeType'])
        if file1['mimeType'] == "image/jpeg":
            imageurl = file1['title']
            imageid = file1['id']
            #print 'title: %s' % (file1['title'])
    print "Open " + str(imageurl) + " id: " + str(imageid)

    # Download and show an image
    myFile = drive.CreateFile({'id': imageid})
    myFile.GetContentFile(imageurl)
    print '%s downloaded ' % (imageurl) + " and it looks like this:"
    # Create fullscreen window
    root = Tk()
    root.overrideredirect(True)
    root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(),
                                       root.winfo_screenheight()))
    # Keyboard input
    root.bind('<Key>', keyinput)
    # Screen size?
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    #print str(screen_width) + "-" + str(screen_height)

    image = Image.open(imageurl)
    width, height = image.size
    #print str(width) + "-" + str(height)
    image = image.resize((screen_width, screen_height), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(image)

    panel = Label(root, image=img)
    panel.pack(side="bottom", fill="both", expand="yes")
    root.mainloop()
    time.sleep(10)
def sunfounder_client(ip, key):
        #!/usr/bin/env python
        # -*- coding: utf-8 -*-
        from Tkinter import Tk, Button, Label, Scale, HORIZONTAL

        print "Connecting to IP", ip

        ctrl_cmd = ['forward', 'backward', 'left', 'right', 'stop', 'read cpu_temp', 'home', 'distance', 'x+', 'x-', 'y+', 'y-', 'xy_home']

        top = Tk()   # Create a top window
        top.title('Sunfounder Raspberry Pi Smart Video Car')

        HOST = ip    # Server(Raspberry Pi) IP address
        PORT = 21567
        BUFSIZ = 1024             # buffer size
        ADDR = (HOST, PORT)

        tcpCliSock = socket(AF_INET, SOCK_STREAM)   # Create a socket
        tcpCliSock.connect(ADDR)                    # Connect with the server
        # =============================================================================
        # The function is to send the command forward to the server, so as to make the 
        # car move forward.
        # ============================================================================= 
        def forward_fun(event):
                print "\nUser command = forward"
                print "Encrypted command = ",crypto.AES_encrypt('forward',key)[2]
                tcpCliSock.send(str(crypto.AES_encrypt('forward',key)))

        def backward_fun(event):
                print '\nUser command = backward'
                print "Encrypted command = ",crypto.AES_encrypt('backward',key)[2]
                tcpCliSock.send(str(crypto.AES_encrypt('backward',key)))

        def left_fun(event):
                print '\nUser command = left'
                print "Encrypted command = ",crypto.AES_encrypt('left',key)[2]
                tcpCliSock.send(str(crypto.AES_encrypt('left',key)))

        def right_fun(event):
                print '\nUser command = right'
                print "Encrypted command = ",crypto.AES_encrypt('right',key)[2]
                tcpCliSock.send(str(crypto.AES_encrypt('right',key)))

        def stop_fun(event):
                print '\nUser command = stop'
                print "Encrypted command = ",crypto.AES_encrypt('stop',key)[2]
                tcpCliSock.send(str(crypto.AES_encrypt('stop',key)))

        def home_fun(event):
                print '\nUser command = home'
                print "Encrypted command = ",crypto.AES_encrypt('home',key)[2]
                tcpCliSock.send(str(crypto.AES_encrypt('home',key)))

        def x_increase(event):
                print '\nUser command = x+'
                print "Encrypted command = ",crypto.AES_encrypt('x+',key)[2]
                tcpCliSock.send(str(crypto.AES_encrypt('x+',key)))

        def x_decrease(event):
                print '\nUser command = x-'
                print "Encrypted command = ",crypto.AES_encrypt('x-',key)[2]
                tcpCliSock.send(str(crypto.AES_encrypt('x-',key)))

        def y_increase(event):
                print '\nUser command = y+'
                print "Encrypted command = ",crypto.AES_encrypt('y+',key)[2]
                tcpCliSock.send(str(crypto.AES_encrypt('y+',key)))

        def y_decrease(event):
                print '\nUser command = y-'
                print "Encrypted command = ",crypto.AES_encrypt('y-',key)[2]
                tcpCliSock.send(str(crypto.AES_encrypt('y-',key)))

        def xy_home(event):
                print '\nUser command = xy_home'
                print "Encrypted command = ",crypto.AES_encrypt('xy_home',key)[2]
                tcpCliSock.send(str(crypto.AES_encrypt('xy_home',key)))

        # =============================================================================
        # Exit the GUI program and close the network connection between the client 
        # and server.
        # =============================================================================
        def quit_fun(event):
                print "\nShutting down program..."
                top.quit()
                tcpCliSock.send(str(crypto.AES_encrypt('stop',key)))
                tcpCliSock.close()

        # =============================================================================
        # Create buttons
        # =============================================================================
        Btn0 = Button(top, width=5, text='Forward')
        Btn1 = Button(top, width=5, text='Backward')
        Btn2 = Button(top, width=5, text='Left')
        Btn3 = Button(top, width=5, text='Right')
        Btn4 = Button(top, width=5, text='Quit')
        Btn5 = Button(top, width=5, height=2, text='Home')

        # =============================================================================
        # Buttons layout
        # =============================================================================
        Btn0.grid(row=0,column=1)
        Btn1.grid(row=2,column=1)
        Btn2.grid(row=1,column=0)
        Btn3.grid(row=1,column=2)
        Btn4.grid(row=3,column=2)
        Btn5.grid(row=1,column=1)

        # =============================================================================
        # Bind the buttons with the corresponding callback function.
        # =============================================================================
        Btn0.bind('<ButtonPress-1>', forward_fun)  # When button0 is pressed down, call the function forward_fun().
        Btn1.bind('<ButtonPress-1>', backward_fun)
        Btn2.bind('<ButtonPress-1>', left_fun)
        Btn3.bind('<ButtonPress-1>', right_fun)
        Btn0.bind('<ButtonRelease-1>', stop_fun)   # When button0 is released, call the function stop_fun().
        Btn1.bind('<ButtonRelease-1>', stop_fun)
        Btn2.bind('<ButtonRelease-1>', stop_fun)
        Btn3.bind('<ButtonRelease-1>', stop_fun)
        Btn4.bind('<ButtonRelease-1>', quit_fun)
        Btn5.bind('<ButtonRelease-1>', home_fun)

        # =============================================================================
        # Create buttons
        # =============================================================================
        Btn07 = Button(top, width=5, text='X+', bg='red')
        Btn08 = Button(top, width=5, text='X-', bg='red')
        Btn09 = Button(top, width=5, text='Y-', bg='red')
        Btn10 = Button(top, width=5, text='Y+', bg='red')
        Btn11 = Button(top, width=5, height=2, text='HOME', bg='red')

        # =============================================================================
        # Buttons layout
        # =============================================================================
        Btn07.grid(row=1,column=5)
        Btn08.grid(row=1,column=3)
        Btn09.grid(row=2,column=4)
        Btn10.grid(row=0,column=4)
        Btn11.grid(row=1,column=4)

        # =============================================================================
        # Bind button events
        # =============================================================================
        Btn07.bind('<ButtonPress-1>', x_increase)
        Btn08.bind('<ButtonPress-1>', x_decrease)
        Btn09.bind('<ButtonPress-1>', y_decrease)
        Btn10.bind('<ButtonPress-1>', y_increase)
        Btn11.bind('<ButtonPress-1>', xy_home)
        #Btn07.bind('<ButtonRelease-1>', home_fun)
        #Btn08.bind('<ButtonRelease-1>', home_fun)
        #Btn09.bind('<ButtonRelease-1>', home_fun)
        #Btn10.bind('<ButtonRelease-1>', home_fun)
        #Btn11.bind('<ButtonRelease-1>', home_fun)

        # =============================================================================
        # Bind buttons on the keyboard with the corresponding callback function to 
        # control the car remotely with the keyboard.
        # =============================================================================
        top.bind('<KeyPress-a>', left_fun)   # Press down key 'A' on the keyboard and the car will turn left.
        top.bind('<KeyPress-d>', right_fun) 
        top.bind('<KeyPress-s>', backward_fun)
        top.bind('<KeyPress-w>', forward_fun)
        top.bind('<KeyPress-h>', home_fun)
        top.bind('<KeyRelease-a>', home_fun) # Release key 'A' and the car will turn back.
        top.bind('<KeyRelease-d>', home_fun)
        top.bind('<KeyRelease-s>', stop_fun)
        top.bind('<KeyRelease-w>', stop_fun)

        spd = 50

        def changeSpeed(ev=None):
                tmp = 'speed'
                global spd
                spd = speed.get()
                data = tmp + str(spd)  # Change the integers into strings and combine them with the string 'speed'.  
                #print 'sendData = %s' % data
                print '\nUser command = ', data
                print "Encrypted command = ",crypto.AES_encrypt(data,key)[2]

                tcpCliSock.send(str(crypto.AES_encrypt(data,key)))  # Send the speed data to the server(Raspberry Pi)

        label = Label(top, text='Speed:', fg='red')  # Create a label
        label.grid(row=6, column=0)                  # Label layout

        speed = Scale(top, from_=0, to=100, orient=HORIZONTAL, command=changeSpeed)  # Create a scale
        speed.set(50)
        speed.grid(row=6, column=1)

        def main():
                top.mainloop()

        if __name__ == '__main__':
                main()
Example #45
0
                canv.delete(rects[i][j])
                rects[i][j]=canv.create_rectangle(w*i/n, h*j/n, w*(i+1)/n, h*(j+1)/n, fill="lightblue", outline="lightblue")
            else: new_grid[i][j]=grid[i][j]
    for i in range(len(new_grid)):
        for j in range(len(new_grid[i])):
            grid[i][j]=new_grid[i][j]
    canv.after(20, tick, grid, rects)
w, h = 600, 600
n, m = 20, 20
paused = True
grid=[]; new_grid=[]; rects=[]
root = Tk()
canv = Canvas(root, width=w, height=h, bg="white")
##for i in range(n+1):canv.create_line(w*i/n,0,w*i/n,h, fill = "lightblue")
##for i in range(m+1):canv.create_line(0,h*i/m,w,h*i/m, fill = "lightblue")
for i in range(n):
    grid.append([])
    rects.append([])
    for j in range(m):
        grid[i].append(0)
        rects[i].append(canv.create_rectangle(w*i/n, h*j/n, w*(i+1)/n, h*(j+1)/n, fill="white", outline="lightblue"))

for (i, j) in [(0, 1), (0, 2), (1, 0), (1, 1), (2, 1)]:
    grid[i][j]=1
    canv.delete(rects[i][j])
    rects[i][j]=canv.create_rectangle(w*i/n, h*j/n, w*(i+1)/n, h*(j+1)/n, fill="lightblue", outline="lightblue")

canv.pack()
root.bind('<1>', lambda e: left(e, grid, rects))
root.bind('<space>', begin)
root.mainloop()
Example #46
0
class Visualiser(Thread):
    """Superclass of both the realtime and offline VTK visualisers
    """
    def __init__(self, source):
        Thread.__init__(self)

        self.source = source

        # Structures for Height Based quantities
        self.height_quantities = []
        self.height_zScales = {}
        self.height_dynamic = {}
        self.height_offset = {}
        self.height_opacity = {}
        self.height_wireframe = {}

        # Structures for colouring quantities
        self.colours_height = {}

        # Structures used for VTK
        self.vtk_actors = {}
        self.vtk_axesSet = False
        self.vtk_drawAxes = False
        self.vtk_mappers = {}
        self.vtk_polyData = {}

        # A list of operations to be performed on the cube axes. Type: [(func, (args))]
        self.conf_axesAlterations = []
        # A list of all polygons to overlay. Type: [([coords], height, (colour)]
        self.conf_overlaidPolygons = []
        # A list of alterations to be performed on the Tk root. Type: [(func, (args))]
        self.conf_tkAlterations = []

    def run(self):
        self.vtk_renderer = vtkRenderer()
        self.setup_gui()
        self.setup_grid()

        # Handle any deferred configuration
        # Overlaid polygons
        for args in self.conf_overlaidPolygons:
            self.overlay_polygon_internal(*args)
        # Draw (and maybe alter) the axes
        if self.vtk_drawAxes:
            self.vtk_axes = vtkCubeAxesActor2D()
            # Perform all of the alterations required, by applying func to the vtk_axes instance (with the given args).
            for func, args in self.conf_axesAlterations:
                func(*((self.vtk_axes, ) + args))
        # Alter the Tk root as necessary.
        for func, args in self.conf_tkAlterations:
            func(*((self.tk_root, ) + args))
        # Finished with deferred configuration.

        # Draw Height Quantities
        for q in self.height_quantities:
            self.update_height_quantity(q, self.height_dynamic[q])
            self.draw_height_quantity(q)

        self.tk_root.mainloop()

    def redraw_quantities(self):
        """Redraw all dynamic quantities.
        """
        # Height quantities
        for q in self.height_quantities:
            if (self.height_dynamic[q]):
                self.update_height_quantity(q, self.height_dynamic[q])
                self.draw_height_quantity(q)
        if self.vtk_drawAxes is True:
            self.draw_axes()

    # --- Axes --- #

    def render_axes(self):
        """Intstruct the visualiser to render cube axes around the render.
        """
        self.vtk_drawAxes = True

    def draw_axes(self):
        """Update the 3D bounds on the axes and add them to the pipeline if not yet connected.
        """
        self.vtk_axes.SetBounds(self.get_3d_bounds())
        if not self.vtk_axesSet:
            self.vtk_axesSet = True
            self.vtk_axes.SetCamera(self.vtk_renderer.GetActiveCamera())
            self.vtk_renderer.AddActor(self.vtk_axes)
            self.vtk_renderer.ResetCamera(self.get_3d_bounds())

    def alter_axes(self, func, args):
        """Attempt to apply the function 'func' with args tuple 'args' to the
        vtkCubeAxesActor2D instance set up by render_axes. This is done this way to ensure
        the axes setup is handled in the visualiser thread.

        Example call:
        from vtk import vtkCubeAxesActor2D
        alter_axes(vtkCubeAxesActor2D.SetNumberOfPoints, (5,))
        """
        self.conf_axesAlterations.append((func, args))

    # --- Height Based Rendering --- #

    def setup_grid(self):
        """Create the vtkCellArray instance that represents the
        triangles. Subclasses are expected to override this function
        to read from their source as appropriate. The vtkCellArray should
        be stored to self.vtk_cells.
        """
        pass

    def render_quantity_height(self,
                               quantityName,
                               zScale=1.0,
                               offset=0.0,
                               opacity=1.0,
                               dynamic=True,
                               wireframe=False):
        """Instruct the visualiser to render a quantity using the
        value at a point as its height.  The value at each point is
        multiplied by z_scale and is added to offset, and if
        dynamic=False, the quantity is not recalculated on each
        update.
        """
        self.height_quantities.append(quantityName)
        self.height_zScales[quantityName] = zScale
        self.height_offset[quantityName] = offset
        self.height_dynamic[quantityName] = dynamic
        self.height_opacity[quantityName] = opacity
        self.height_wireframe[quantityName] = wireframe

    def update_height_quantity(self, quantityName, dynamic=True):
        """Create a vtkPolyData object and store it in
        self.vtk_polyData[quantityName]. Subclasses are expected to override this
        function.
        """
        pass

    def get_3d_bounds(self):
        """Get the minimum and maximum bounds for the x, y and z directions.
        Return as a list of double in the order (xmin, xmax, ymin, ymax, zmin, zmax),
        suitable for passing to vtkCubeAxesActor2D::SetRanges(). Subclasses are expected
        to override this function.
        """
        pass

    def store_height_quantity(self, quantityName, fileName=None):

        if fileName == None:
            fileName = quantityName + '.vtk'

        quantity_polyData = self.vtk_polyData[quantityName]

        import vtk
        w = vtk.vtkPolyDataWriter()
        #print quantity_polyData
        w.SetInput(quantity_polyData)
        w.SetFileName(fileName)
        w.Write()

    def draw_height_quantity(self, quantityName):
        """Use the vtkPolyData and prepare/update the rest of the VTK
        rendering pipeline.
        """
        if self.vtk_mappers.has_key(quantityName):
            mapper = self.vtk_mappers[quantityName]
        else:
            mapper = self.vtk_mappers[quantityName] = vtkPolyDataMapper()
        mapper.SetInput(self.vtk_polyData[quantityName])
        mapper.Update()

        if not self.vtk_actors.has_key(quantityName):
            actor = self.vtk_actors[quantityName] = vtkActor()
            actor.GetProperty().SetOpacity(self.height_opacity[quantityName])
            if self.height_wireframe[quantityName]:
                actor.GetProperty().SetRepresentationToWireframe()
            actor.SetMapper(mapper)
            self.vtk_renderer.AddActor(actor)
        else:
            actor = self.vtk_actors[quantityName]

        if self.colours_height.has_key(quantityName):
            colour = self.colours_height[quantityName]
            if type(colour) == TupleType:
                if type(colour[0]) == FunctionType:
                    # It's a function, so take colour[1] as the
                    # lower bound on the scalar range and
                    # colour[2] as the upper bound on the scalar
                    # range.
                    scalars = vtkFloatArray()

                    map(scalars.InsertNextValue,
                        colour[0](self.build_quantity_dict()))
                    self.vtk_polyData[quantityName].GetPointData().SetScalars(
                        scalars)
                    mapper.SetScalarRange(colour[1:])
                    mapper.Update()
                else:
                    # It's a 3-tuple representing an RGB value.
                    actor.GetProperty().SetColor(colour)
            else:
                actor.GetProperty().SetColor(0.5, 0.5, 0.5)
        else:
            actor.GetProperty().SetColor(0.5, 0.5, 0.5)

    # --- Colour Coding --- #

    def build_quantity_dict(self):
        """Build and return a dictionary mapping quantity name->Numeric array of vertex
        values for that quantity. Subclasses are expected to override
        this function."""
        pass

    def colour_height_quantity(self, quantityName, colour=(0.5, 0.5, 0.5)):
        """Add colouring to a height based quantity.

        The colour parameter can be one of the following:
        - a 3-tuple of values in [0,1] to specify R, G, B values
        - a 3-tuple of values:
          - a function that takes a dictionary mapping quantity name->Numeric array of vertex values.
            This function returns a list of vertex values to be used in the colour coding.
          - a float for the lower bound on the colouring
          - a float for the upper bound on the colouring
        """
        self.colours_height[quantityName] = colour

    # --- Overlaid Polygons --- #

    def overlay_polygon(self, coords, height=0.0, colour=(1.0, 0.0, 0.0)):
        """Add a polygon to the output of the visualiser.

        coords is a list of 2-tuples representing x and y coordinates.
        These are triangulated by vtkDelaunay2D.

        height is the z-value given to all points.

        colour is the colour of the polygon, as a 3-tuple representing
        r, g, b values between 0 and 1."""
        self.conf_overlaidPolygons.append((coords, height, colour))

    def overlay_polygon_internal(self, coords, height, colour):
        """Add a polygon to the output of the visualiser.

        coords is a list of 2-tuples representing x and y coordinates.
        These are triangulated by vtkDelaunay2D.

        height is the z-value given to all points.

        colour is the colour of the polygon, as a 3-tuple representing
        r, g, b values between 0 and 1.

        This function should not be called from outside the visualiser thread.
        Use overlay_polygon instead.
    
        """
        points = vtkPoints()
        for coord in coords:
            points.InsertNextPoint(coord[0], coord[1], height)
        profile = vtkPolyData()
        profile.SetPoints(points)
        delny = vtkDelaunay2D()
        delny.SetInput(profile)
        mesh = vtkPolyDataMapper()
        mesh.SetInput(delny.GetOutput())
        actor = vtkActor()
        actor.SetMapper(mesh)
        actor.GetProperty().SetColor(colour)
        self.vtk_renderer.AddActor(actor)

    # --- Vector Fields --- #

    # --- GUI Setup --- #

    def setup_gui(self):
        self.tk_root = Tk()
        self.tk_root.title("Visualisation")
        self.tk_root.after(100, self.redraw)
        self.tk_root.bind("<Destroy>", self.destroyed)
        self.tk_root.grid_rowconfigure(0, weight=1)
        self.tk_root.grid_columnconfigure(0, weight=1)

        self.tk_renderWidget = vtkTkRenderWidget(self.tk_root,
                                                 width=400,
                                                 height=400)
        self.tk_renderWidget.grid(row=0, column=0, sticky=N + S + E + W)
        self.tk_controlFrame = Frame(self.tk_root)
        self.tk_controlFrame.grid(row=1, column=0, sticky=E + W)
        self.tk_controlFrame.grid_rowconfigure(0, weight=1)
        self.tk_controlFrame.grid_columnconfigure(0, weight=1)

        self.tk_quit = Button(self.tk_controlFrame,
                              text="Quit",
                              command=self.shutdown)
        self.tk_quit.grid(row=0, column=0, sticky=E + W)
        self.tk_renderWidget.GetRenderWindow().AddRenderer(self.vtk_renderer)

    def alter_tkroot(self, func, args):
        """Apply func, with arguments tuple args to the root tk window for this visualiser.
        """
        self.conf_tkAlterations.append((func, args))

    # --- GUI Events --- #

    def destroyed(self, event):
        if event.widget == self.tk_root:
            self.shutdown()

    def redraw(self):
        self.tk_renderWidget.GetRenderWindow().Render()
        self.tk_root.update_idletasks()
        self.tk_root.after(100, self.redraw)

    def shutdown(self):
        self.tk_root.withdraw()
        self.tk_root.destroy()
Example #47
0
class RecursiveDescentApp(object):
    """
    A graphical tool for exploring the recursive descent parser.  The tool
    displays the parser's tree and the remaining text, and allows the
    user to control the parser's operation.  In particular, the user
    can expand subtrees on the frontier, match tokens on the frontier
    against the text, and backtrack.  A "step" button simply steps
    through the parsing process, performing the operations that
    ``RecursiveDescentParser`` would use.
    """
    def __init__(self, grammar, sent, trace=0):
        self._sent = sent
        self._parser = SteppingRecursiveDescentParser(grammar, trace)

        # Set up the main window.
        self._top = Tk()
        self._top.title('Recursive Descent Parser Application')

        # Set up key bindings.
        self._init_bindings()

        # Initialize the fonts.
        self._init_fonts(self._top)

        # Animations.  animating_lock is a lock to prevent the demo
        # from performing new operations while it's animating.
        self._animation_frames = IntVar(self._top)
        self._animation_frames.set(5)
        self._animating_lock = 0
        self._autostep = 0

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_feedback(self._top)
        self._init_grammar(self._top)
        self._init_canvas(self._top)

        # Initialize the parser.
        self._parser.initialize(self._sent)

        # Resize callback
        self._canvas.bind('<Configure>', self._configure)

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = tkFont.Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget('size'))

        self._boldfont = tkFont.Font(family='helvetica', weight='bold',
                                    size=self._size.get())
        self._font = tkFont.Font(family='helvetica',
                                    size=self._size.get())
        if self._size.get() < 0: big = self._size.get()-2
        else: big = self._size.get()+2
        self._bigfont = tkFont.Font(family='helvetica', weight='bold',
                                    size=big)

    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill='both', side='left', padx=2)
        self._prodlist_label = Label(self._prodframe, font=self._boldfont,
                                     text='Available Expansions')
        self._prodlist_label.pack()
        self._prodlist = Listbox(self._prodframe, selectmode='single',
                                 relief='groove', background='white',
                                 foreground='#909090', font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._prodlist.pack(side='right', fill='both', expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert('end', ('  %s' % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe,
                                   orient='vertical')
            self._prodlist.config(yscrollcommand = listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a production, apply it.
        self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select)

    def _init_bindings(self):
        # Key bindings are a good thing.
        self._top.bind('<Control-q>', self.destroy)
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Escape>', self.destroy)
        self._top.bind('e', self.expand)
        #self._top.bind('<Alt-e>', self.expand)
        #self._top.bind('<Control-e>', self.expand)
        self._top.bind('m', self.match)
        self._top.bind('<Alt-m>', self.match)
        self._top.bind('<Control-m>', self.match)
        self._top.bind('b', self.backtrack)
        self._top.bind('<Alt-b>', self.backtrack)
        self._top.bind('<Control-b>', self.backtrack)
        self._top.bind('<Control-z>', self.backtrack)
        self._top.bind('<BackSpace>', self.backtrack)
        self._top.bind('a', self.autostep)
        #self._top.bind('<Control-a>', self.autostep)
        self._top.bind('<Control-space>', self.autostep)
        self._top.bind('<Control-c>', self.cancel_autostep)
        self._top.bind('<space>', self.step)
        self._top.bind('<Delete>', self.reset)
        self._top.bind('<Control-p>', self.postscript)
        #self._top.bind('<h>', self.help)
        #self._top.bind('<Alt-h>', self.help)
        self._top.bind('<Control-h>', self.help)
        self._top.bind('<F1>', self.help)
        #self._top.bind('<g>', self.toggle_grammar)
        #self._top.bind('<Alt-g>', self.toggle_grammar)
        #self._top.bind('<Control-g>', self.toggle_grammar)
        self._top.bind('<Control-g>', self.edit_grammar)
        self._top.bind('<Control-t>', self.edit_sentence)

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill='none', side='bottom', padx=3, pady=2)
        Button(buttonframe, text='Step',
               background='#90c0d0', foreground='black',
               command=self.step,).pack(side='left')
        Button(buttonframe, text='Autostep',
               background='#90c0d0', foreground='black',
               command=self.autostep,).pack(side='left')
        Button(buttonframe, text='Expand', underline=0,
               background='#90f090', foreground='black',
               command=self.expand).pack(side='left')
        Button(buttonframe, text='Match', underline=0,
               background='#90f090', foreground='black',
               command=self.match).pack(side='left')
        Button(buttonframe, text='Backtrack', underline=0,
               background='#f0a0a0', foreground='black',
               command=self.backtrack).pack(side='left')
        # Replace autostep...
#         self._autostep_button = Button(buttonframe, text='Autostep',
#                                        underline=0, command=self.autostep)
#         self._autostep_button.pack(side='left')

    def _configure(self, event):
        self._autostep = 0
        (x1, y1, x2, y2) = self._cframe.scrollregion()
        y2 = event.height - 6
        self._canvas['scrollregion'] = '%d %d %d %d' % (x1,y1,x2,y2)
        self._redraw()

    def _init_feedback(self, parent):
        self._feedbackframe = feedbackframe = Frame(parent)
        feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3)
        self._lastoper_label = Label(feedbackframe, text='Last Operation:',
                                     font=self._font)
        self._lastoper_label.pack(side='left')
        lastoperframe = Frame(feedbackframe, relief='sunken', border=1)
        lastoperframe.pack(fill='x', side='right', expand=1, padx=5)
        self._lastoper1 = Label(lastoperframe, foreground='#007070',
                                background='#f0f0f0', font=self._font)
        self._lastoper2 = Label(lastoperframe, anchor='w', width=30,
                                foreground='#004040', background='#f0f0f0',
                                font=self._font)
        self._lastoper1.pack(side='left')
        self._lastoper2.pack(side='left', fill='x', expand=1)

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(parent, background='white',
                                   #width=525, height=250,
                                   closeenough=10,
                                   border=2, relief='sunken')
        self._cframe.pack(expand=1, fill='both', side='top', pady=2)
        canvas = self._canvas = self._cframe.canvas()

        # Initially, there's no tree or text
        self._tree = None
        self._textwidgets = []
        self._textline = None

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Reset Parser', underline=0,
                             command=self.reset, accelerator='Del')
        filemenu.add_command(label='Print to Postscript', underline=0,
                             command=self.postscript, accelerator='Ctrl-p')
        filemenu.add_command(label='Exit', underline=1,
                             command=self.destroy, accelerator='Ctrl-x')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label='Edit Grammar', underline=5,
                             command=self.edit_grammar,
                             accelerator='Ctrl-g')
        editmenu.add_command(label='Edit Text', underline=5,
                             command=self.edit_sentence,
                             accelerator='Ctrl-t')
        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label='Step', underline=1,
                             command=self.step, accelerator='Space')
        rulemenu.add_separator()
        rulemenu.add_command(label='Match', underline=0,
                             command=self.match, accelerator='Ctrl-m')
        rulemenu.add_command(label='Expand', underline=0,
                             command=self.expand, accelerator='Ctrl-e')
        rulemenu.add_separator()
        rulemenu.add_command(label='Backtrack', underline=0,
                             command=self.backtrack, accelerator='Ctrl-b')
        menubar.add_cascade(label='Apply', underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(label="Show Grammar", underline=0,
                                 variable=self._show_grammar,
                                 command=self._toggle_grammar)
        viewmenu.add_separator()
        viewmenu.add_radiobutton(label='Tiny', variable=self._size,
                                 underline=0, value=10, command=self.resize)
        viewmenu.add_radiobutton(label='Small', variable=self._size,
                                 underline=0, value=12, command=self.resize)
        viewmenu.add_radiobutton(label='Medium', variable=self._size,
                                 underline=0, value=14, command=self.resize)
        viewmenu.add_radiobutton(label='Large', variable=self._size,
                                 underline=0, value=18, command=self.resize)
        viewmenu.add_radiobutton(label='Huge', variable=self._size,
                                 underline=0, value=24, command=self.resize)
        menubar.add_cascade(label='View', underline=0, menu=viewmenu)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=0)
        animatemenu.add_radiobutton(label="Slow Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=10, accelerator='-')
        animatemenu.add_radiobutton(label="Normal Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=5, accelerator='=')
        animatemenu.add_radiobutton(label="Fast Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=2, accelerator='+')
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)


        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label='About', underline=0,
                             command=self.about)
        helpmenu.add_command(label='Instructions', underline=0,
                             command=self.help, accelerator='F1')
        menubar.add_cascade(label='Help', underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    #########################################
    ##  Helper
    #########################################

    def _get(self, widget, treeloc):
        for i in treeloc: widget = widget.subtrees()[i]
        if isinstance(widget, TreeSegmentWidget):
            widget = widget.node()
        return widget

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        canvas = self._canvas

        # Delete the old tree, widgets, etc.
        if self._tree is not None:
            self._cframe.destroy_widget(self._tree)
        for twidget in self._textwidgets:
            self._cframe.destroy_widget(twidget)
        if self._textline is not None:
            self._canvas.delete(self._textline)

        # Draw the tree.
        helv = ('helvetica', -self._size.get())
        bold = ('helvetica', -self._size.get(), 'bold')
        attribs = {'tree_color': '#000000', 'tree_width': 2,
                   'node_font': bold, 'leaf_font': helv,}
        tree = self._parser.tree()
        self._tree = tree_to_treesegment(canvas, tree, **attribs)
        self._cframe.add_widget(self._tree, 30, 5)

        # Draw the text.
        helv = ('helvetica', -self._size.get())
        bottom = y = self._cframe.scrollregion()[3]
        self._textwidgets = [TextWidget(canvas, word, font=self._font)
                             for word in self._sent]
        for twidget in self._textwidgets:
            self._cframe.add_widget(twidget, 0, 0)
            twidget.move(0, bottom-twidget.bbox()[3]-5)
            y = min(y, twidget.bbox()[1])

        # Draw a line over the text, to separate it from the tree.
        self._textline = canvas.create_line(-5000, y-5, 5000, y-5, dash='.')

        # Highlight appropriate nodes.
        self._highlight_nodes()
        self._highlight_prodlist()

        # Make sure the text lines up.
        self._position_text()


    def _redraw_quick(self):
        # This should be more-or-less sufficient after an animation.
        self._highlight_nodes()
        self._highlight_prodlist()
        self._position_text()

    def _highlight_nodes(self):
        # Highlight the list of nodes to be checked.
        bold = ('helvetica', -self._size.get(), 'bold')
        for treeloc in self._parser.frontier()[:1]:
            self._get(self._tree, treeloc)['color'] = '#20a050'
            self._get(self._tree, treeloc)['font'] = bold
        for treeloc in self._parser.frontier()[1:]:
            self._get(self._tree, treeloc)['color'] = '#008080'

    def _highlight_prodlist(self):
        # Highlight the productions that can be expanded.
        # Boy, too bad tkinter doesn't implement Listbox.itemconfig;
        # that would be pretty useful here.
        self._prodlist.delete(0, 'end')
        expandable = self._parser.expandable_productions()
        untried = self._parser.untried_expandable_productions()
        productions = self._productions
        for index in range(len(productions)):
            if productions[index] in expandable:
                if productions[index] in untried:
                    self._prodlist.insert(index, ' %s' % productions[index])
                else:
                    self._prodlist.insert(index, ' %s (TRIED)' %
                                          productions[index])
                self._prodlist.selection_set(index)
            else:
                self._prodlist.insert(index, ' %s' % productions[index])

    def _position_text(self):
        # Line up the text widgets that are matched against the tree
        numwords = len(self._sent)
        num_matched = numwords - len(self._parser.remaining_text())
        leaves = self._tree_leaves()[:num_matched]
        xmax = self._tree.bbox()[0]
        for i in range(0, len(leaves)):
            widget = self._textwidgets[i]
            leaf = leaves[i]
            widget['color'] = '#006040'
            leaf['color'] = '#006040'
            widget.move(leaf.bbox()[0] - widget.bbox()[0], 0)
            xmax = widget.bbox()[2] + 10

        # Line up the text widgets that are not matched against the tree.
        for i in range(len(leaves), numwords):
            widget = self._textwidgets[i]
            widget['color'] = '#a0a0a0'
            widget.move(xmax - widget.bbox()[0], 0)
            xmax = widget.bbox()[2] + 10

        # If we have a complete parse, make everything green :)
        if self._parser.currently_complete():
            for twidget in self._textwidgets:
                twidget['color'] = '#00a000'

        # Move the matched leaves down to the text.
        for i in range(0, len(leaves)):
            widget = self._textwidgets[i]
            leaf = leaves[i]
            dy = widget.bbox()[1] - leaf.bbox()[3] - 10.0
            dy = max(dy, leaf.parent().node().bbox()[3] - leaf.bbox()[3] + 10)
            leaf.move(0, dy)

    def _tree_leaves(self, tree=None):
        if tree is None: tree = self._tree
        if isinstance(tree, TreeSegmentWidget):
            leaves = []
            for child in tree.subtrees(): leaves += self._tree_leaves(child)
            return leaves
        else:
            return [tree]

    #########################################
    ##  Button Callbacks
    #########################################

    def destroy(self, *e):
        self._autostep = 0
        if self._top is None: return
        self._top.destroy()
        self._top = None

    def reset(self, *e):
        self._autostep = 0
        self._parser.initialize(self._sent)
        self._lastoper1['text'] = 'Reset Application'
        self._lastoper2['text'] = ''
        self._redraw()

    def autostep(self, *e):
        if self._animation_frames.get() == 0:
            self._animation_frames.set(2)
        if self._autostep:
            self._autostep = 0
        else:
            self._autostep = 1
            self._step()

    def cancel_autostep(self, *e):
        #self._autostep_button['text'] = 'Autostep'
        self._autostep = 0

    # Make sure to stop auto-stepping if we get any user input.
    def step(self, *e): self._autostep = 0; self._step()
    def match(self, *e): self._autostep = 0; self._match()
    def expand(self, *e): self._autostep = 0; self._expand()
    def backtrack(self, *e): self._autostep = 0; self._backtrack()

    def _step(self):
        if self._animating_lock: return

        # Try expanding, matching, and backtracking (in that order)
        if self._expand(): pass
        elif self._parser.untried_match() and self._match(): pass
        elif self._backtrack(): pass
        else:
            self._lastoper1['text'] = 'Finished'
            self._lastoper2['text'] = ''
            self._autostep = 0

        # Check if we just completed a parse.
        if self._parser.currently_complete():
            self._autostep = 0
            self._lastoper2['text'] += '    [COMPLETE PARSE]'

    def _expand(self, *e):
        if self._animating_lock: return
        old_frontier = self._parser.frontier()
        rv = self._parser.expand()
        if rv is not None:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = rv
            self._prodlist.selection_clear(0, 'end')
            index = self._productions.index(rv)
            self._prodlist.selection_set(index)
            self._animate_expand(old_frontier[0])
            return 1
        else:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = '(all expansions tried)'
            return 0

    def _match(self, *e):
        if self._animating_lock: return
        old_frontier = self._parser.frontier()
        rv = self._parser.match()
        if rv is not None:
            self._lastoper1['text'] = 'Match:'
            self._lastoper2['text'] = rv
            self._animate_match(old_frontier[0])
            return 1
        else:
            self._lastoper1['text'] = 'Match:'
            self._lastoper2['text'] = '(failed)'
            return 0

    def _backtrack(self, *e):
        if self._animating_lock: return
        if self._parser.backtrack():
            elt = self._parser.tree()
            for i in self._parser.frontier()[0]:
                elt = elt[i]
            self._lastoper1['text'] = 'Backtrack'
            self._lastoper2['text'] = ''
            if isinstance(elt, Tree):
                self._animate_backtrack(self._parser.frontier()[0])
            else:
                self._animate_match_backtrack(self._parser.frontier()[0])
            return 1
        else:
            self._autostep = 0
            self._lastoper1['text'] = 'Finished'
            self._lastoper2['text'] = ''
            return 0

    def about(self, *e):
        ABOUT = ("NLTK Recursive Descent Parser Application\n"+
                 "Written by Edward Loper")
        TITLE = 'About: Recursive Descent Parser Application'
        try:
            from tkMessageBox import Message
            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def help(self, *e):
        self._autostep = 0
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(self._top, 'Help: Recursive Descent Parser Application',
                     (__doc__ or '').strip(), width=75, font='fixed')
        except:
            ShowText(self._top, 'Help: Recursive Descent Parser Application',
                     (__doc__ or '').strip(), width=75)

    def postscript(self, *e):
        self._autostep = 0
        self._cframe.print_to_file()

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle(): return
        self._top.mainloop(*args, **kwargs)

    def resize(self, size=None):
        if size is not None: self._size.set(size)
        size = self._size.get()
        self._font.configure(size=-(abs(size)))
        self._boldfont.configure(size=-(abs(size)))
        self._sysfont.configure(size=-(abs(size)))
        self._bigfont.configure(size=-(abs(size+2)))
        self._redraw()

    #########################################
    ##  Expand Production Selection
    #########################################

    def _toggle_grammar(self, *e):
        if self._show_grammar.get():
            self._prodframe.pack(fill='both', side='left', padx=2,
                                 after=self._feedbackframe)
            self._lastoper1['text'] = 'Show Grammar'
        else:
            self._prodframe.pack_forget()
            self._lastoper1['text'] = 'Hide Grammar'
        self._lastoper2['text'] = ''

#     def toggle_grammar(self, *e):
#         self._show_grammar = not self._show_grammar
#         if self._show_grammar:
#             self._prodframe.pack(fill='both', expand='y', side='left',
#                                  after=self._feedbackframe)
#             self._lastoper1['text'] = 'Show Grammar'
#         else:
#             self._prodframe.pack_forget()
#             self._lastoper1['text'] = 'Hide Grammar'
#         self._lastoper2['text'] = ''

    def _prodlist_select(self, event):
        selection = self._prodlist.curselection()
        if len(selection) != 1: return
        index = int(selection[0])
        old_frontier = self._parser.frontier()
        production = self._parser.expand(self._productions[index])

        if production:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = production
            self._prodlist.selection_clear(0, 'end')
            self._prodlist.selection_set(index)
            self._animate_expand(old_frontier[0])
        else:
            # Reset the production selections.
            self._prodlist.selection_clear(0, 'end')
            for prod in self._parser.expandable_productions():
                index = self._productions.index(prod)
                self._prodlist.selection_set(index)

    #########################################
    ##  Animation
    #########################################

    def _animate_expand(self, treeloc):
        oldwidget = self._get(self._tree, treeloc)
        oldtree = oldwidget.parent()
        top = not isinstance(oldtree.parent(), TreeSegmentWidget)

        tree = self._parser.tree()
        for i in treeloc:
            tree = tree[i]

        widget = tree_to_treesegment(self._canvas, tree,
                                     node_font=self._boldfont,
                                     leaf_color='white',
                                     tree_width=2, tree_color='white',
                                     node_color='white',
                                     leaf_font=self._font)
        widget.node()['color'] = '#20a050'

        (oldx, oldy) = oldtree.node().bbox()[:2]
        (newx, newy) = widget.node().bbox()[:2]
        widget.move(oldx-newx, oldy-newy)

        if top:
            self._cframe.add_widget(widget, 0, 5)
            widget.move(30-widget.node().bbox()[0], 0)
            self._tree = widget
        else:
            oldtree.parent().replace_child(oldtree, widget)

        # Move the children over so they don't overlap.
        # Line the children up in a strange way.
        if widget.subtrees():
            dx = (oldx + widget.node().width()/2 -
                  widget.subtrees()[0].bbox()[0]/2 -
                  widget.subtrees()[0].bbox()[2]/2)
            for subtree in widget.subtrees(): subtree.move(dx, 0)

        self._makeroom(widget)

        if top:
            self._cframe.destroy_widget(oldtree)
        else:
            oldtree.destroy()

        colors = ['gray%d' % (10*int(10*x/self._animation_frames.get()))
                  for x in range(self._animation_frames.get(),0,-1)]

        # Move the text string down, if necessary.
        dy = widget.bbox()[3] + 30 - self._canvas.coords(self._textline)[1]
        if dy > 0:
            for twidget in self._textwidgets: twidget.move(0, dy)
            self._canvas.move(self._textline, 0, dy)

        self._animate_expand_frame(widget, colors)

    def _makeroom(self, treeseg):
        """
        Make sure that no sibling tree bbox's overlap.
        """
        parent = treeseg.parent()
        if not isinstance(parent, TreeSegmentWidget): return

        index = parent.subtrees().index(treeseg)

        # Handle siblings to the right
        rsiblings = parent.subtrees()[index+1:]
        if rsiblings:
            dx = treeseg.bbox()[2] - rsiblings[0].bbox()[0] + 10
            for sibling in rsiblings: sibling.move(dx, 0)

        # Handle siblings to the left
        if index > 0:
            lsibling = parent.subtrees()[index-1]
            dx = max(0, lsibling.bbox()[2] - treeseg.bbox()[0] + 10)
            treeseg.move(dx, 0)

        # Keep working up the tree.
        self._makeroom(parent)

    def _animate_expand_frame(self, widget, colors):
        if len(colors) > 0:
            self._animating_lock = 1
            widget['color'] = colors[0]
            for subtree in widget.subtrees():
                if isinstance(subtree, TreeSegmentWidget):
                    subtree.node()['color'] = colors[0]
                else:
                    subtree['color'] = colors[0]
            self._top.after(50, self._animate_expand_frame,
                            widget, colors[1:])
        else:
            widget['color'] = 'black'
            for subtree in widget.subtrees():
                if isinstance(subtree, TreeSegmentWidget):
                    subtree.node()['color'] = 'black'
                else:
                    subtree['color'] = 'black'
            self._redraw_quick()
            widget.node()['color'] = 'black'
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_backtrack(self, treeloc):
        # Flash red first, if we're animating.
        if self._animation_frames.get() == 0: colors = []
        else: colors = ['#a00000', '#000000', '#a00000']
        colors += ['gray%d' % (10*int(10*x/(self._animation_frames.get())))
                   for x in range(1, self._animation_frames.get()+1)]

        widgets = [self._get(self._tree, treeloc).parent()]
        for subtree in widgets[0].subtrees():
            if isinstance(subtree, TreeSegmentWidget):
                widgets.append(subtree.node())
            else:
                widgets.append(subtree)

        self._animate_backtrack_frame(widgets, colors)

    def _animate_backtrack_frame(self, widgets, colors):
        if len(colors) > 0:
            self._animating_lock = 1
            for widget in widgets: widget['color'] = colors[0]
            self._top.after(50, self._animate_backtrack_frame,
                            widgets, colors[1:])
        else:
            for widget in widgets[0].subtrees():
                widgets[0].remove_child(widget)
                widget.destroy()
            self._redraw_quick()
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_match_backtrack(self, treeloc):
        widget = self._get(self._tree, treeloc)
        node = widget.parent().node()
        dy = (1.0 * (node.bbox()[3] - widget.bbox()[1] + 14) /
              max(1, self._animation_frames.get()))
        self._animate_match_backtrack_frame(self._animation_frames.get(),
                                            widget, dy)

    def _animate_match(self, treeloc):
        widget = self._get(self._tree, treeloc)

        dy = ((self._textwidgets[0].bbox()[1] - widget.bbox()[3] - 10.0) /
              max(1, self._animation_frames.get()))
        self._animate_match_frame(self._animation_frames.get(), widget, dy)

    def _animate_match_frame(self, frame, widget, dy):
        if frame > 0:
            self._animating_lock = 1
            widget.move(0, dy)
            self._top.after(10, self._animate_match_frame,
                            frame-1, widget, dy)
        else:
            widget['color'] = '#006040'
            self._redraw_quick()
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_match_backtrack_frame(self, frame, widget, dy):
        if frame > 0:
            self._animating_lock = 1
            widget.move(0, dy)
            self._top.after(10, self._animate_match_backtrack_frame,
                            frame-1, widget, dy)
        else:
            widget.parent().remove_child(widget)
            widget.destroy()
            self._animating_lock = 0
            if self._autostep: self._step()

    def edit_grammar(self, *e):
        CFGEditor(self._top, self._parser.grammar(), self.set_grammar)

    def set_grammar(self, grammar):
        self._parser.set_grammar(grammar)
        self._productions = list(grammar.productions())
        self._prodlist.delete(0, 'end')
        for production in self._productions:
            self._prodlist.insert('end', (' %s' % production))

    def edit_sentence(self, *e):
        sentence = " ".join(self._sent)
        title = 'Edit Text'
        instr = 'Enter a new sentence to parse.'
        EntryDialog(self._top, sentence, instr, self.set_sentence, title)

    def set_sentence(self, sentence):
        self._sent = sentence.split() #[XX] use tagged?
        self.reset()
def main():

    class Example(Frame):
      
        def __init__(self, parent):
            Frame.__init__(self, parent)    
            self.parent = parent
            self.initUI()
            
        def initUI(self):
            w = self.parent.winfo_screenwidth()/1
            h = self.parent.winfo_screenheight()/1
            sw = self.parent.winfo_screenwidth()
            sh = self.parent.winfo_screenheight()
            x = (sw - w)/2
            y = (sh - h)/2
            self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
            self.parent.title("Cool Positioning")
            self.pack(fill=BOTH, expand=1)
            Style().configure("TFrame", background="#000")     
         
    def changeImage(event):
##        print "clicked at", event.x, event.y, "typed ", event.char
        if event.char == "1":
            print event.char
            myImg = resizeImg(Image.open("bardejov.jpg"), root.winfo_screenwidth())
            myImage = ImageTk.PhotoImage(myImg)
            label = Label(root, image=myImage)
            label.image = myImage
            xLabel = (root.winfo_screenwidth() - myImg.size[0])/2
            yLabel = (root.winfo_screenheight() - myImg.size[1])/2
            label.place(x=xLabel, y=yLabel)

        if event.char == "2":
            print event.char
            myImg = resizeImg(Image.open("rotunda.jpg"), root.winfo_screenwidth())
            myImage = ImageTk.PhotoImage(myImg)
            label = Label(root, image=myImage)
            label.image = myImage
            xLabel = (root.winfo_screenwidth() - myImg.size[0])/2
            yLabel = (root.winfo_screenheight() - myImg.size[1])/2
            label.place(x=xLabel, y=yLabel)

        if event.char == "3":
            print event.char
            myImg = resizeImg(Image.open("mincol.jpg"), root.winfo_screenwidth())
            myImage = ImageTk.PhotoImage(myImg)
            label = Label(root, image=myImage)
            label.image = myImage
            xLabel = (root.winfo_screenwidth() - myImg.size[0])/2
            yLabel = (root.winfo_screenheight() - myImg.size[1])/2
            label.place(x=xLabel, y=yLabel)

    def resizeImg(img, finalWidth):
        finalHeight = int(round((finalWidth * img.size[1])/img.size[0]))
        resizedImage = img.resize((finalWidth, finalHeight), Image.ANTIALIAS)
        print("final width",resizedImage.size[0],"final height",resizedImage.size[1])
        return resizedImage
        
    root = Tk()   
    app = Example(root)
    
    # This is how to display the image, needs to be done once in the main function
    # this way label object and all its friends are defined
    myImg = resizeImg(Image.open("bardejov.jpg"), root.winfo_screenwidth())
    myImage = ImageTk.PhotoImage(myImg)
    label = Label(root, image=myImage)
    label.image = myImage
    xLabel = (root.winfo_screenwidth() - myImg.size[0])/2
    yLabel = (root.winfo_screenheight() - myImg.size[1])/2
    label.place(x=xLabel, y=yLabel)
    
    root.bind("<Key>", changeImage)
    root.bind("<Escape>", lambda e: e.widget.quit())    
    root.mainloop()
Example #49
0
def setUpCanvas():
    root = Tk()
    root.title("Comma Gets a Cure")
    canvas = Canvas(root, width=640, height=480, bg="white")
    canvas.pack(expand=YES, fill=BOTH)
    root.bind("<Right>", highlight)
    root.bind("<q>", quit)
    root.bind("<Left>", dehighlight)
    root.bind("<space>", play)
    root.bind("<d>", delete)
    root.bind("<Delete>", delete)
    root.bind("<Down>", lambda evt: [highlight(None) for i in range(5)])
    root.bind("<Up>", lambda evt: [dehighlight(None) for i in range(5)])
    return root, canvas
Example #50
0
class TreeView(object):
    def __init__(self, *trees):
        from math import sqrt, ceil

        self._trees = trees

        self._top = Tk()
        self._top.title('NLTK')
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Control-q>', self.destroy)

        cf = self._cframe = CanvasFrame(self._top)
        self._top.bind('<Control-p>', self._cframe.print_to_file)

        # Size is variable.
        self._size = IntVar(self._top)
        self._size.set(12)
        bold = ('helvetica', -self._size.get(), 'bold')
        helv = ('helvetica', -self._size.get())

        # Lay the trees out in a square.
        self._width = int(ceil(sqrt(len(trees))))
        self._widgets = []
        for i in range(len(trees)):
            widget = TreeWidget(cf.canvas(), trees[i], node_font=bold,
                                leaf_color='#008040', node_color='#004080',
                                roof_color='#004040', roof_fill='white',
                                line_color='#004040', draggable=1,
                                leaf_font=helv)
            widget.bind_click_trees(widget.toggle_collapsed)
            self._widgets.append(widget)
            cf.add_widget(widget, 0, 0)

        self._layout()
        self._cframe.pack(expand=1, fill='both')
        self._init_menubar()

    def _layout(self):
        i = x = y = ymax = 0
        width = self._width
        for i in range(len(self._widgets)):
            widget = self._widgets[i]
            (oldx, oldy) = widget.bbox()[:2]
            if i % width == 0:
                y = ymax
                x = 0
            widget.move(x-oldx, y-oldy)
            x = widget.bbox()[2] + 10
            ymax = max(ymax, widget.bbox()[3] + 10)

    def _init_menubar(self):
        menubar = Menu(self._top)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Print to Postscript', underline=0,
                             command=self._cframe.print_to_file,
                             accelerator='Ctrl-p')
        filemenu.add_command(label='Exit', underline=1,
                             command=self.destroy, accelerator='Ctrl-x')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        zoommenu = Menu(menubar, tearoff=0)
        zoommenu.add_radiobutton(label='Tiny', variable=self._size,
                                 underline=0, value=10, command=self.resize)
        zoommenu.add_radiobutton(label='Small', variable=self._size,
                                 underline=0, value=12, command=self.resize)
        zoommenu.add_radiobutton(label='Medium', variable=self._size,
                                 underline=0, value=14, command=self.resize)
        zoommenu.add_radiobutton(label='Large', variable=self._size,
                                 underline=0, value=28, command=self.resize)
        zoommenu.add_radiobutton(label='Huge', variable=self._size,
                                 underline=0, value=50, command=self.resize)
        menubar.add_cascade(label='Zoom', underline=0, menu=zoommenu)

        self._top.config(menu=menubar)

    def resize(self, *e):
        bold = ('helvetica', -self._size.get(), 'bold')
        helv = ('helvetica', -self._size.get())
        xspace = self._size.get()
        yspace = self._size.get()
        for widget in self._widgets:
            widget['node_font'] = bold
            widget['leaf_font'] = helv
            widget['xspace'] = xspace
            widget['yspace'] = yspace
            if self._size.get() < 20: widget['line_width'] = 1
            elif self._size.get() < 30: widget['line_width'] = 2
            else: widget['line_width'] = 3
        self._layout()

    def destroy(self, *e):
        if self._top is None: return
        self._top.destroy()
        self._top = None

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle(): return
        self._top.mainloop(*args, **kwargs)
Example #51
0
        if "CASEDIR" not in environ:
            environ["CASEDIR"] = "distri/opensuse"
        pat = environ["CASEDIR"] + "/needles/%s.%s"
        shutil.copyfile(png, pat % (options.new, "png"))
        filename = pat % (options.new, "json")
    json.dump(needle,
              open(filename, "w"),
              sort_keys=True,
              indent=4,
              separators=(",", ": "))
    print("saved %s" % filename)
    master.quit()


master.bind("<Shift-Up>", resize)
master.bind("<Shift-Down>", resize)
master.bind("<Shift-Left>", resize)
master.bind("<Shift-Right>", resize)
master.bind("<Up>", move)
master.bind("<Down>", move)
master.bind("<Left>", move)
master.bind("<Right>", move)
master.bind("+", increment)
master.bind("-", increment)
master.bind("s", save_quit)
master.bind("q", quit)
master.bind("<Escape>", quit)
master.bind("<Tab>", switch)
master.bind("<Insert>", addrect)
master.bind("<Delete>", delrect)
Example #52
0
class Visualiser(object):
    '''
    Generic Offline Visualiser. Subclasses need to be used that specify
    how to handle a data source.
    '''
    
    ### Public functions ###

    def __init__(self,
                 title="Visualisation",
                 width=400,
                 height=400,
                 recording=False,
                 recordPattern=None,
                 paused=False,
                 source=None):
        '''
        Constructor.

        Params:
        title: string - Title of the visualisation window
        width: int - Width of the visualisation window
        height: int - Height of the visualisation window
        recording: boolean - Start with recording enabled?
        recordPattern: string - Pattern for recorded images,
          e.g., cylinders%05g.png
        paused: boolean - Start with playback paused?
        source:- The data source to read.
          What is required here varies by visualiser.
        '''

        # Visualisation options
        self.vis_features = []
        self.vis_frame = 0
        self.vis_frameStep = 1
        self.vis_jumping = False
        self.vis_recording = recording
        self.vis_recordPattern = recordPattern
        self.vis_paused = paused
        self.vis_source = source

        # VTK structures
        self.vtk_cells = vtkCellArray()
        self.vtk_renderer = vtkRenderer()

        # Tk structures
        self.tk_root = Tk()
        self.tk_root.title(title)
        self.tk_root.grid_rowconfigure(0, weight=1)
        self.tk_root.grid_columnconfigure(0, weight=3)
        self.tk_root.bind('<Destroy>', self.destroyed)
        if not self.vis_paused: self.tk_root.after(100, self.animate)            

        self.tk_renderWidget = vtkTkRenderWidget(self.tk_root,
                                                 width=width,
                                                 height=height)
        self.tk_renderWidget.grid(row=0, column=0, sticky=N+S+E+W)
        self.tk_renderWidget.GetRenderWindow().AddRenderer(self.vtk_renderer)

        self.tk_featureFrame = Frame(self.tk_root)
        self.tk_featureFrame.grid(row=0, column=1, rowspan=2)
        Label(self.tk_featureFrame, text='Features:').grid(row=0, column=0)

        self.tk_controlFrame = Frame(self.tk_root)
        self.tk_controlFrame.grid(row=1, column=0)

        self.tk_quit = Button(self.tk_controlFrame, text="Quit",
                              command=self.shutdown)
        self.tk_quit.grid(row=0, column=0, columnspan=2)

        def pause():
            if self.vis_paused:
                self.tk_pause.config(text='Pause')
                self.tk_root.after(100, self.animate)
            else:
                self.tk_pause.config(text='Resume')
            self.vis_paused ^= True
        self.tk_pause = Button(self.tk_controlFrame, text="Pause", command=pause)
        self.tk_pause.grid(row=0, column=2, columnspan=2)

        if self.vis_recordPattern is not None:
            def record():
                if self.vis_recording:
                    self.tk_record.config(text='Start Recording')
                else:
                    self.tk_record.config(text='Stop Recording')
                self.vis_recording ^= True
            self.tk_record = Button(self.tk_controlFrame, text="Start Recording", command=record)
            self.tk_record.grid(row=0, column=4, columnspan=2)
            if self.vis_recording:
                self.tk_record.config(text="Stop Recording")

        def make_seek_button(label, column, frame):
            def jump():
                self.jumpTo(frame)
            b = Button(self.tk_controlFrame,
                       text=label,
                       command=jump)
            b.grid(row=1, column=column, sticky=W+E)
            return b
        self.tk_seek_start = make_seek_button("|<", 0, 0)
        self.tk_seek_back10 = make_seek_button("<<", 1,
                                               lambda: self.vis_frame - 10)
        self.tk_seek_back1 = make_seek_button("<", 2,
                                              lambda: self.vis_frame - 1)
        self.tk_seek_forward1 = make_seek_button(">", 3,
                                                 lambda: self.vis_frame + 1)
        self.tk_seek_forward10 = make_seek_button(">>", 4,
                                                  lambda: self.vis_frame + 10)
        self.tk_seek_end = make_seek_button(">|", 5,
                                            self.getMaxFrameNumber)

        Label(self.tk_controlFrame, text='Frame').grid(row=2, column=0,
                                                       sticky=W+E)
        def changeFrame(frame):
            if not self.vis_jumping:
                self.vis_jumping = True
                self.jumpTo(self.tk_frame.get())
                self.vis_jumping = False
        self.tk_frame = Scale(self.tk_controlFrame, command=changeFrame,
                              from_=0, to=0, orient=HORIZONTAL)
        self.tk_frame.grid(row=2, column=1, columnspan=2, sticky=W+E)

        Label(self.tk_controlFrame, text='Step').grid(row=2, column=3,
                                                     sticky=W+E)
        def changeFrameStep(step):
            self.vis_frameStep = int(step)
        self.tk_frameStep = Scale(self.tk_controlFrame, command=changeFrameStep,
                                  from_=1, to=1, orient=HORIZONTAL)
        self.tk_frameStep.grid(row=2, column=4, columnspan=2, sticky=W+E)

        self.setupGrid()

    def add_feature(self, feature):
        '''Add a feature to this visualiser'''
        self.vis_features.append(feature)
        feature.button(self.tk_featureFrame).grid(row=len(self.vis_features),
                                                  column=0, sticky=W+E)
        feature.visualiser = self

    def run(self):
        '''Start the visualiser'''
        self.redraw()
        self.tk_root.mainloop()

    ### Private funcitions ###

    def resetSliders(self):
        '''
        Recalculate the upper bound on the frame and frameStep
        sliders.
        '''
        maxFrame = self.getMaxFrameNumber()
        self.tk_frame.config(to=maxFrame)
        self.tk_frameStep.config(to=maxFrame)

    def jumpTo(self, frame):
        '''
        Jump to a given frame. If frame is a function, jump to the
        return value of frame().
        '''
        oldFrame = self.vis_frame
        if hasattr(frame, '__call__'):
            self.vis_frame = frame()
        else:
            self.vis_frame = frame

        maxFrame = self.getMaxFrameNumber()

        if self.vis_frame < 0:
            self.vis_frame = 0
        elif self.vis_frame > maxFrame:
            self.vis_frame = maxFrame
            self.vis_paused = True
            self.tk_pause.config(text='Resume')

        self.tk_frame.set(self.vis_frame)
        self.redraw(oldFrame != self.vis_frame)

    def redraw(self, update=False):
        self.resetSliders()
        for feature in [ f for f in self.vis_features if not f.dynamic ]:
            feature.draw(self.vtk_renderer)
        if update:
            for feature in [ f for f in self.vis_features if f.dynamic]:
                f.redraw(self.vtk_renderer)
        self.tk_renderWidget.GetRenderWindow().Render()
        self.tk_root.update_idletasks()

    ### Gui events ###

    def destroyed(self, event):
        if event.widget == self.tk_root:
            self.shutdown()

    def shutdown(self):
        self.tk_root.withdraw()
        self.tk_root.destroy()

    def animate(self):
        if not self.vis_paused:
            self.jumpTo(self.vis_frame + self.vis_frameStep)
            if self.vis_recording and self.vis_recordPattern is not None:
                self.save_image()
            self.tk_root.after(100, self.animate)

    def save_image(self):
        extmap = {'.jpg' : vtkJPEGWriter,
                  '.jpeg' : vtkJPEGWriter,
                  '.png' : vtkPNGWriter,
                  '.pnm' : vtkPNMWriter}
        _, ext = splitext(self.vis_recordPattern)
        try: writer = extmap[ext.lower()]()
        except KeyError:
            print 'ERROR: Can\'t handle %s extension. Recording disabled.' % ext
            self.vis_recordPattern = None
            return

        win = self.vtk_renderer.GetRenderWindow()
        w2i = vtkWindowToImageFilter()
        w2i.SetInput(win)
        w2i.Update()
        writer.SetInput(w2i.GetOutput())
        writer.SetFileName(self.vis_recordPattern % self.vis_frame)
        win.Render()
        writer.Write()

    ### Things subclasses need to override ###

    def setupGrid(self):
        '''
        Populate the vtkCellArray instance at
        self.vtk_cells. Subclasses are required to override this
        function to read from their source as appropriate.
        '''
        raise NotImplementedError('Subclass needs to override Visualiser::setupGrid!')

    def getMaxFrameNumber(self):
        '''
        Return the maximum frame number. This will need to be defined
        by a subclass.
        '''
        raise NotImplementedError('Subclass needs to override Visualiser::getMaxFrameNumber!')

    def getQuantityPoints(self, quantityName, dynamic=True, frameNumber=0):
        '''
        Return the points of a quantity at a given frame as a list
        [float]. Subclasses need to override this.
        '''
        raise NotImplementedError('Subclass needs to override Visualiser::getQuantityPoints!')

    def getQuantityDict(self):
        '''
        Return the values of all quantities at a given time as a
        dictionary. Sublclasses need to override this.
        '''
        raise NotImplementedError('Subclass needs to override Visualiser::getQuantityDict!')
Example #53
0
class Game:
    def __init__(self):
        self.root = Tk()
        self.frame1 = None
        self.frame2 = None
        self.w = None
        self.scoreC = None
        self.score = 0
        self.hor = True
        self.upid = self.downid = self.rightid = self.leftid = 0
        self.head = -1
        self.time = 700

    def home(self):
        self.frame1 = Frame(self.root, width=750, height=350, padx=250, bg="black")
        self.frame2 = Frame(self.root, height=250, width=750, bg="black", padx=25)
        self.root.wm_minsize(width=750, height=666)
        self.root.configure(bg="black")
        self.frame1.pack_propagate(0)
        self.frame1.update()
        self.frame1.configure(pady=self.frame1.cget("height") / 2.5)
        logo = PhotoImage(file="Game_Logo.gif")
        starth = Button(self.frame1, text="Hard", bg="orange", padx=25, pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(40))
        startm = Button(self.frame1, text="Medium", bg="teal", padx=25, pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(60))
        starte = Button(self.frame1, text="Easy", bg="orange", padx=25, pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(75))
        self.frame2.pack_propagate(0)
        exp = """        This is a game in which
        the arrow keys are used
        to move the snake around
        and to get points"""
        exf = Font(family="comic sans MS", size=20)
        Label(self.frame2, image=logo, bg="black", text=exp, padx=10).pack(side="right")
        Label(self.frame2, fg="white", bg="black", text=exp, justify="left", font=exf).pack(side="left")
        starte.grid(row=0, columnspan=2)
        startm.grid(row=0, columnspan=2, column=4, padx=18)
        starth.grid(row=0, columnspan=2, column=8)
        head = Font(family="comic sans MS", size=30)
        self.H=Label(self.root, text="SNAKES", font=head, fg="orange", bg="black", pady=10)
        self.H.pack()
        self.frame2.pack(expand=True)
        self.frame1.pack(expand=True)
        self.root.mainloop()

    def callgame(self, time):
        self.time = time
        self.game()

    def calldown(self, key):
        if self.hor:
            self.w.after_cancel(self.leftid)
            self.w.after_cancel(self.rightid)
            self.down(0)

    def callup(self, key):
        if self.hor:
            self.w.after_cancel(self.leftid)
            self.w.after_cancel(self.rightid)
            self.up(0)

    def callright(self, key):
        if not self.hor:
            self.w.after_cancel(self.upid)
            self.w.after_cancel(self.downid)
            self.right(0)

    def callleft(self, key):
        if not self.hor:
            self.w.after_cancel(self.upid)
            self.w.after_cancel(self.downid)
            self.left(0)

    def game(self):
        self.score = 0
        self.w = Canvas(self.root, width=750, height=500, relief="flat", highlightbackground="grey",
                        highlightthickness=10)
        self.frame1.destroy()
        self.frame2.destroy()
        self.root.configure(width=1000, padx=10)
        self.root.pack_propagate(0)
        self.w.configure(background="black")
        self.w.pack(side="left")
        self.w.create_line(300, 250, 450, 250, width=10, fill="teal")
        self.scoreC = Label(self.root, text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35,
                            font=Font(family="comic sans MS", size=25))
        self.head = self.w.create_line(450, 250, 455, 250, width=10, fill="white")
        self.scoreC.pack(side="top")
        self.root.bind("<Up>", self.callup)
        self.root.bind("<Down>", self.calldown)
        self.root.bind("<Right>", self.callright)
        self.root.bind("<Left>", self.callleft)
        self.createFood()
        self.right(0)

    def down(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-1] += 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-3] -= 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] + 5, width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = False
            if not end:
                self.downid = self.w.after(self.time, self.down, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def up(self, i):
        crd = self.w.coords(1)
        if len(crd)>0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-1] -= 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-3] += 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] - 5, width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = False
            if not end:
                self.upid = self.w.after(self.time, self.up, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def right(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-2] += 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-4] -= 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] + 5, crd[-1], width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = True
            if not end:
                self.rightid = self.w.after(self.time, self.right, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def left(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-2] -= 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-4] += 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] - 5, crd[-1], width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = True
            if not end:
                self.leftid = self.w.after(self.time, self.left, i)
            else:

                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def createFood(self):
        # self.w.delete(self.food) #deleting old food.
        crd = self.w.coords(1)
        ext = []
        for i in crd:
            ext.append(i)
            for j in range(-50, 50):
                ext.append(i + j)
        randx = random.randrange(20, 730)
        randy = random.randrange(20, 480)
        while randx not in ext and randy not in ext:
            randx = random.randrange(20, 730)
            randy = random.randrange(20, 480)
        self.food = self.w.create_line(randx, randy, randx + 12, randy, width=10, fill="yellow")

    def checkEaten(self):
        headcoords = self.w.coords(self.head)
        foodcoords = self.w.coords(self.food)
        # self.w.delete(self.food)
        flag = False
        # print(headcoords[-4])
        # print(foodcoords[-4])
        # print(foodcoords[-2])
        if int(headcoords[-4]) in range(int(foodcoords[-4]) - 7, int(foodcoords[-2]) + 7) and int(
                headcoords[-3]) in range(int(foodcoords[-1]) - 10, int(foodcoords[-1] + 10)):
            flag = True
        if flag:
            self.grow()
            self.score += 10
            self.scoreC.configure(text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35,
                                  font=Font(family="comic sans MS", size=25))
            self.w.delete(self.food)
            self.createFood()

    def grow(self):
        crd = self.w.coords(1)
        if crd[0] != crd[2]:  # horizontal condition
            if crd[0] < crd[2]:
                crd[0] -= 20
            else:
                crd[0] += 20
            self.w.coords(1, *crd)
        else:
            if crd[3] < crd[1]:
                crd[1] += 20
            else:
                crd[1] -= 20
            self.w.coords(1, *crd)

    def end(self):
        crd = self.w.coords(1)
        h = self.w.coords(self.head)
        a = 0
        while a < len(crd) - 2:
            if crd[a] == crd[a + 2]:
                if (h[0] == crd[a] and crd[a + 1] < h[1] < crd[a + 3]) or (
                        h[0] == crd[a]  and crd[a + 1] > h[1] > crd[a + 3]):
                    return True
            else:
                if (h[1] == crd[a + 1] and crd[a] < h[0] < crd[a + 2]) or (h[1] == crd[a + 1] and crd[a] > h[0] > crd[a + 2]):
                    return True
            a += 2
        if (h[0] == 0 and 0 < h[1] < 500) or (h[1] == 0 and 0 < h[0] < 750) or (h[1] == 510 and 0 < h[0] < 750) or (h[0] == 760 and 0<h[1]<500):
            return True
        return False


    def callhome(self):
        self.w.destroy()
        self.start.destroy()
        self.H.destroy()
        self.scoreC.destroy()
        self.home()
Example #54
-1
def guiLogin(title, default_username="", default_password=""):
    from Tkinter import Tk, N, S, W, E, StringVar
    import ttk

    root = Tk()

    root.title(title)

    mainframe = ttk.Frame(root, padding="3 3 12 12")
    mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
    mainframe.columnconfigure(0, weight=1)
    mainframe.rowconfigure(0, weight=1)

    username = StringVar()
    username.set(default_username)
    password = StringVar()
    password.set(default_password)

    def done(*args):
        root.destroy()

    ttk.Label(mainframe, text="Username:"******"Password:"******"*")
    pass_entry.grid(column=2, row=2, sticky=(W, E))

    ttk.Button(mainframe, text="Login", command=done).grid(column=2, row=3, sticky=W)

    for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=2)

    username_entry.focus()
    root.bind('<Return>', done)
    root.bind('<Escape>', lambda event: root.destroy())

    root.lift()
    root.call('wm', 'attributes', '.', '-topmost', True)
    root.after_idle(root.call, 'wm', 'attributes', '.', '-topmost', False)

    root.mainloop()

    return username.get(), password.get()
Example #55
-1
def guiLogin():
    root = Tk()

    root.title("Enter Lastpass login")

    mainframe = ttk.Frame(root, padding="3 3 12 12")
    mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
    mainframe.columnconfigure(0, weight=1)
    mainframe.rowconfigure(0, weight=1)

    username = StringVar()
    password = StringVar()
    ret = []

    def done(*args):
        ret.append((username.get(), password.get()))
        root.destroy()

    ttk.Label(mainframe, text="Username:"******"Password:"******"Login", command=done).grid(column=2, row=3, sticky=W)

    for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=2)

    username_entry.focus()
    root.bind('<Return>', done)
    root.bind('<Escape>', lambda event: root.destroy())

    root.lift()
    root.call('wm', 'attributes', '.', '-topmost', True)
    root.after_idle(root.call, 'wm', 'attributes', '.', '-topmost', False)

    root.mainloop()

    return ret and ret[-1] or None
Example #56
-2
class gephiController:
    def __init__(self, data, appCallback=None, minValue=0.0, maxValue=1.0, logScale=False):
        self.data = data
        numBins = len(data)-1
        
        self.master = Tk()
        self.master.geometry("%dx%d%+d%+d" % (WIDTH,HEIGHT,50,50))
        self.master.resizable(False, False)
        
        self.histogram = histogramWidget(self.master,0,0,WIDTH,HEIGHT,self.data,logScale=logScale,callback=self.callApp)
        
        self.current = numBins
        self.currentValue = self.data[maxValue][0]
        
        self.appCallback = appCallback
        if self.appCallback != None:
            self.master.bind("<<appCallback>>",self.runAppCall)
        self.master.bind("<<Update>>",self.runUpdate)
    
    def mainloop(self):
        self.master.mainloop()
    
    def runUpdate(self, event):
        self.histogram.update(self.current)
    
    def runAppCall(self,event):
        self.appCallback(self.currentValue)
    
    def callApp(self, value):
        self.currentValue = value
        self.master.event_generate("<<appCallback>>",when="tail")
    
    def update(self, current):
        self.current = current
        self.master.event_generate("<<Update>>",when="tail")
Example #57
-4
class ConcordanceSearchView(object):
    _BACKGROUND_COLOUR='#FFF' #white

    #Colour of highlighted results
    _HIGHLIGHT_WORD_COLOUR='#F00' #red
    _HIGHLIGHT_WORD_TAG='HL_WRD_TAG'

    _HIGHLIGHT_LABEL_COLOUR='#C0C0C0' # dark grey
    _HIGHLIGHT_LABEL_TAG='HL_LBL_TAG'


    #Percentage of text left of the scrollbar position
    _FRACTION_LEFT_TEXT=0.30

    def __init__(self):
        self.model = ConcordanceSearchModel()
        self.model.add_listener(self)
        self.top = Tk()
        self._init_top(self.top)
        self._init_menubar()
        self._init_widgets(self.top)
        self._bind_event_handlers()
        self.load_corpus(self.model.DEFAULT_CORPUS)

    def _init_top(self, top):
        top.geometry('950x680+50+50')
        top.title('NLTK Concordance Search')
        top.bind('<Control-q>', self.destroy)
        top.minsize(950,680)

    def _init_widgets(self, parent):
        self.main_frame = Frame(parent, dict(background=self._BACKGROUND_COLOUR, padx=1, pady=1, border=1))
        self._init_corpus_select(self.main_frame)
        self._init_query_box(self.main_frame)
        self._init_results_box(self.main_frame)
        self._init_paging(self.main_frame)
        self._init_status(self.main_frame)
        self.main_frame.pack(fill='both', expand=True)

    def _init_menubar(self):
        self._result_size = IntVar(self.top)
        self._cntx_bf_len = IntVar(self.top)
        self._cntx_af_len = IntVar(self.top)
        menubar = Menu(self.top)

        filemenu = Menu(menubar, tearoff=0, borderwidth=0)
        filemenu.add_command(label='Exit', underline=1,
                             command=self.destroy, accelerator='Ctrl-q')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        rescntmenu = Menu(editmenu, tearoff=0)
        rescntmenu.add_radiobutton(label='20', variable=self._result_size,
                                   underline=0, value=20,
                                   command=self.set_result_size)
        rescntmenu.add_radiobutton(label='50', variable=self._result_size,
                                   underline=0, value=50,
                                   command=self.set_result_size)
        rescntmenu.add_radiobutton(label='100', variable=self._result_size,
                                   underline=0, value=100,
                                   command=self.set_result_size)
        rescntmenu.invoke(1)
        editmenu.add_cascade(label='Result Count', underline=0, menu=rescntmenu)

        cntxmenu = Menu(editmenu, tearoff=0)
        cntxbfmenu = Menu(cntxmenu, tearoff=0)
        cntxbfmenu.add_radiobutton(label='60 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0, value=60,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.add_radiobutton(label='80 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0, value=80,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.add_radiobutton(label='100 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0, value=100,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.invoke(1)
        cntxmenu.add_cascade(label='Before', underline=0, menu=cntxbfmenu)

        cntxafmenu = Menu(cntxmenu, tearoff=0)
        cntxafmenu.add_radiobutton(label='70 characters',
                                   variable=self._cntx_af_len,
                                   underline=0, value=70,
                                   command=self.set_cntx_af_len)
        cntxafmenu.add_radiobutton(label='90 characters',
                                   variable=self._cntx_af_len,
                                   underline=0, value=90,
                                   command=self.set_cntx_af_len)
        cntxafmenu.add_radiobutton(label='110 characters',
                                   variable=self._cntx_af_len,
                                   underline=0, value=110,
                                   command=self.set_cntx_af_len)
        cntxafmenu.invoke(1)
        cntxmenu.add_cascade(label='After', underline=0, menu=cntxafmenu)

        editmenu.add_cascade(label='Context', underline=0, menu=cntxmenu)

        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        self.top.config(menu=menubar)

    def set_result_size(self, **kwargs):
        self.model.result_count = self._result_size.get()

    def set_cntx_af_len(self, **kwargs):
        self._char_after = self._cntx_af_len.get()

    def set_cntx_bf_len(self, **kwargs):
        self._char_before = self._cntx_bf_len.get()

    def _init_corpus_select(self, parent):
        innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
        self.var = StringVar(innerframe)
        self.var.set(self.model.DEFAULT_CORPUS)
        Label(innerframe, justify=LEFT, text=' Corpus: ',
              background=self._BACKGROUND_COLOUR, padx = 2, pady = 1, border = 0).pack(side='left')

        other_corpora = self.model.CORPORA.keys().remove(self.model.DEFAULT_CORPUS)
        om = OptionMenu(innerframe, self.var, self.model.DEFAULT_CORPUS, command=self.corpus_selected, *self.model.non_default_corpora())
        om['borderwidth'] = 0
        om['highlightthickness'] = 1
        om.pack(side='left')
        innerframe.pack(side='top', fill='x', anchor='n')

    def _init_status(self, parent):
        self.status = Label(parent, justify=LEFT, relief=SUNKEN, background=self._BACKGROUND_COLOUR, border=0, padx = 1, pady = 0)
        self.status.pack(side='top', anchor='sw')

    def _init_query_box(self, parent):
        innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
        another = Frame(innerframe, background=self._BACKGROUND_COLOUR)
        self.query_box = Entry(another, width=60)
        self.query_box.pack(side='left', fill='x', pady=25, anchor='center')
        self.search_button = Button(another, text='Search', command=self.search, borderwidth=1, highlightthickness=1)
        self.search_button.pack(side='left', fill='x', pady=25, anchor='center')
        self.query_box.bind('<KeyPress-Return>', self.search_enter_keypress_handler)
        another.pack()
        innerframe.pack(side='top', fill='x', anchor='n')

    def search_enter_keypress_handler(self, *event):
        self.search()

    def _init_results_box(self, parent):
        innerframe = Frame(parent)
        i1 = Frame(innerframe)
        i2 = Frame(innerframe)
        vscrollbar = Scrollbar(i1, borderwidth=1)
        hscrollbar = Scrollbar(i2, borderwidth=1, orient='horiz')
        self.results_box = Text(i1,
                                font=tkFont.Font(family='courier', size='16'),
                                state='disabled', borderwidth=1,
                                                            yscrollcommand=vscrollbar.set,
                                xscrollcommand=hscrollbar.set, wrap='none', width='40', height = '20', exportselection=1)
        self.results_box.pack(side='left', fill='both', expand=True)
        self.results_box.tag_config(self._HIGHLIGHT_WORD_TAG, foreground=self._HIGHLIGHT_WORD_COLOUR)
        self.results_box.tag_config(self._HIGHLIGHT_LABEL_TAG, foreground=self._HIGHLIGHT_LABEL_COLOUR)
        vscrollbar.pack(side='left', fill='y', anchor='e')
        vscrollbar.config(command=self.results_box.yview)
        hscrollbar.pack(side='left', fill='x', expand=True, anchor='w')
        hscrollbar.config(command=self.results_box.xview)
        #there is no other way of avoiding the overlap of scrollbars while using pack layout manager!!!
        Label(i2, text='   ', background=self._BACKGROUND_COLOUR).pack(side='left', anchor='e')
        i1.pack(side='top', fill='both', expand=True, anchor='n')
        i2.pack(side='bottom', fill='x', anchor='s')
        innerframe.pack(side='top', fill='both', expand=True)

    def _init_paging(self, parent):
        innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
        self.prev = prev = Button(innerframe, text='Previous', command=self.previous, width='10', borderwidth=1, highlightthickness=1, state='disabled')
        prev.pack(side='left', anchor='center')
        self.next = next = Button(innerframe, text='Next', command=self.next, width='10', borderwidth=1, highlightthickness=1, state='disabled')
        next.pack(side='right', anchor='center')
        innerframe.pack(side='top', fill='y')
        self.current_page = 0

    def previous(self):
        self.clear_results_box()
        self.freeze_editable()
        self.model.prev(self.current_page - 1)

    def next(self):
        self.clear_results_box()
        self.freeze_editable()
        self.model.next(self.current_page + 1)

    def about(self, *e):
        ABOUT = ("NLTK Concordance Search Demo\n")
        TITLE = 'About: NLTK Concordance Search Demo'
        try:
            from tkMessageBox import Message
            Message(message=ABOUT, title=TITLE, parent=self.main_frame).show()
        except:
            ShowText(self.top, TITLE, ABOUT)

    def _bind_event_handlers(self):
        self.top.bind(CORPUS_LOADED_EVENT, self.handle_corpus_loaded)
        self.top.bind(SEARCH_TERMINATED_EVENT, self.handle_search_terminated)
        self.top.bind(SEARCH_ERROR_EVENT, self.handle_search_error)
        self.top.bind(ERROR_LOADING_CORPUS_EVENT, self.handle_error_loading_corpus)

    def handle_error_loading_corpus(self, event):
        self.status['text'] = 'Error in loading ' + self.var.get()
        self.unfreeze_editable()
        self.clear_all()
        self.freeze_editable()

    def handle_corpus_loaded(self, event):
        self.status['text'] = self.var.get() + ' is loaded'
        self.unfreeze_editable()
        self.clear_all()
        self.query_box.focus_set()

    def handle_search_terminated(self, event):
        #todo: refactor the model such that it is less state sensitive
        results = self.model.get_results()
        self.write_results(results)
        self.status['text'] = ''
        if len(results) == 0:
            self.status['text'] = 'No results found for ' + self.model.query
        else:
                self.current_page = self.model.last_requested_page
        self.unfreeze_editable()
        self.results_box.xview_moveto(self._FRACTION_LEFT_TEXT)


    def handle_search_error(self, event):
        self.status['text'] = 'Error in query ' + self.model.query
        self.unfreeze_editable()

    def corpus_selected(self, *args):
        new_selection = self.var.get()
        self.load_corpus(new_selection)

    def load_corpus(self, selection):
        if self.model.selected_corpus != selection:
            self.status['text'] = 'Loading ' + selection + '...'
            self.freeze_editable()
            self.model.load_corpus(selection)

    def search(self):
        self.current_page = 0
        self.clear_results_box()
        self.model.reset_results()
        query = self.query_box.get()
        if (len(query.strip()) == 0): return
        self.status['text']  = 'Searching for ' + query
        self.freeze_editable()
        self.model.search(query, self.current_page + 1, )


    def write_results(self, results):
        self.results_box['state'] = 'normal'
        row = 1
        for each in results:
            sent, pos1, pos2 = each[0].strip(), each[1], each[2]
            if len(sent) != 0:
                if (pos1 < self._char_before):
                    sent, pos1, pos2 = self.pad(sent, pos1, pos2)
                sentence = sent[pos1-self._char_before:pos1+self._char_after]
                if not row == len(results):
                    sentence += '\n'
                self.results_box.insert(str(row) + '.0', sentence)
                word_markers, label_markers = self.words_and_labels(sent, pos1, pos2)
                for marker in word_markers: self.results_box.tag_add(self._HIGHLIGHT_WORD_TAG, str(row) + '.' + str(marker[0]), str(row) + '.' + str(marker[1]))
                for marker in label_markers: self.results_box.tag_add(self._HIGHLIGHT_LABEL_TAG, str(row) + '.' + str(marker[0]), str(row) + '.' + str(marker[1]))
                row += 1
        self.results_box['state'] = 'disabled'

    def words_and_labels(self, sentence, pos1, pos2):
        search_exp = sentence[pos1:pos2]
        words, labels = [], []
        labeled_words = search_exp.split(' ')
        index = 0
        for each in labeled_words:
            if each == '':
                index += 1
            else:
                word, label = each.split('/')
                words.append((self._char_before + index, self._char_before + index + len(word)))
                index += len(word) + 1
                labels.append((self._char_before + index, self._char_before + index + len(label)))
                index += len(label)
            index += 1
        return words, labels

    def pad(self, sent, hstart, hend):
        if hstart >= self._char_before:
            return sent, hstart, hend
        d = self._char_before - hstart
        sent = ''.join([' '] * d) + sent
        return sent, hstart + d, hend + d

    def destroy(self, *e):
        if self.top is None: return
        self.top.destroy()
        self.top = None

    def clear_all(self):
        self.query_box.delete(0, END)
        self.model.reset_query()
        self.clear_results_box()

    def clear_results_box(self):
        self.results_box['state'] = 'normal'
        self.results_box.delete("1.0", END)
        self.results_box['state'] = 'disabled'

    def freeze_editable(self):
        self.query_box['state'] = 'disabled'
        self.search_button['state'] = 'disabled'
        self.prev['state'] = 'disabled'
        self.next['state'] = 'disabled'

    def unfreeze_editable(self):
        self.query_box['state'] = 'normal'
        self.search_button['state'] = 'normal'
        self.set_paging_button_states()

    def set_paging_button_states(self):
        if self.current_page == 0 or self.current_page == 1:
            self.prev['state'] = 'disabled'
        else:
            self.prev['state'] = 'normal'
        if self.model.has_more_pages(self.current_page):
            self.next['state'] = 'normal'
        else:
            self.next['state'] = 'disabled'

    def fire_event(self, event):
        #Firing an event so that rendering of widgets happen in the mainloop thread
        self.top.event_generate(event, when='tail')

    def mainloop(self, *args, **kwargs):
        if in_idle(): return
        self.top.mainloop(*args, **kwargs)