def initUI(self): self.parent.title("Rename file") self.pack(fill=BOTH, expand=1) originLabel = Label(self, text="File: " + self.filename) originLabel.grid(row=0, column=0, columnspan=2) renameLabel = Label(self, text="Rename to:") renameLabel.grid(row=1, column=0, columnspan=2) self.newName = StringVar() self.newName.set(self.filename) newName = Entry(self, textvariable=self.newName, width=80) endpos = self.filename.rfind('.') newName.selection_range(0, endpos if endpos > 0 else END) newName.grid(row=2, column=0, columnspan=2) newName.bind("<Return>", lambda event: self.doRename()) newName.bind("<Escape>", lambda event: self.parent.destroy()) newName.focus_set() okButton = Button(self, text="OK", command=self.doRename) okButton.grid(row=3, column=0) cancelButton = Button(self, text="Cancel", command=self.parent.destroy) cancelButton.grid(row=3, column=1)
def CreateWidgets(self): self.name = StringVar(self) self.fontSize = StringVar(self) self.frameMain = Frame(self, borderwidth=2, relief=SUNKEN) self.messageInfo = Label(self.frameMain, text=self.message) entryName = Entry(self.frameMain, textvariable=self.name, width=30) frameButtons = Frame(self) self.buttonOk = Button(frameButtons, text='Ok', command=self.Ok) self.buttonCancel = Button(frameButtons, text='Cancel', command=self.Cancel) entryName.focus_set() self.frameMain.pack(side=TOP, expand=True, fill=BOTH) self.messageInfo.pack(padx=5, pady=5) entryName.pack(padx=5, pady=5) frameButtons.pack(side=BOTTOM, fill=X) self.buttonOk.pack(padx=1, pady=5, side=RIGHT) self.buttonCancel.pack(pady=5, padx=5, side=RIGHT) if TTK: self.messageInfo['padding'] = 5 frameButtons['style'] = 'RootColor.TFrame' else: self.messageInfo.configure(padx=5, pady=5)
def save(squares): """ Handle the save key on the main window. """ def save_button_hit(): """ Save key (on local window) was hit. Save the file name entered. """ text_in = save_entry.get().strip() if len(text_in) == 0: showwarning('Error', 'File name specified is empty.') return outfile = os.path.join(savedir, text_in) with open(outfile, 'w') as fyle: for sqr_info in save_squares: fyle.write('%d:%d:%s\n' % tuple(save_squares[sqr_info])) top.destroy() top = Toplevel() top.geometry('180x80+800+200') top.title('Save a layout') save_squares = squares savedir = getdir() label1 = Label(top, text='File name') save_entry = Entry(top) label1.grid(row=0) save_entry.grid(row=0, column=1, columnspan=2) save_entry.focus_set() save_button = Button(top, text='SAVE', pady=3, command=save_button_hit) sspace = Label(top) sspace.grid(row=1) save_button.grid(row=2, column=1) top.mainloop()
class App: def __init__(self,parent): # Create frame, buttons, etc self.f = Frame(parent) self.f.pack(padx=15,pady=15) self.entry = Entry(self.f,text="Enter the search term") self.entry.pack(side= TOP,padx=10,pady=12) self.entry.bind("<Key>", self.key) self.entry.focus_set() self.exit = Button(self.f, text="Exit", command=self.f.quit) self.exit.pack(side=BOTTOM,padx=10,pady=10) self.button = Button(self.f, text="Search",command=self.search) self.button.pack(side=BOTTOM,padx=10,pady=10) def key(self, event): # If ENTER was pressed, search if event.char == '\r': self.search() def search(self): # If there's something to search, search! if self.entry.get() != '': self.button.config(text='Searching...', state=DISABLED) th = SearchThread(self, self.entry.get()) th.start() else: tkMessageBox.showinfo('Hey', 'You should type something in the search. That\'s the point, really...')
def search_user_window(): root.geometry('250x185') global userlabel, ranklabel, promlabel, skine, skinl, skinb, lastpromo, currerank, namelabel, promoterl, oldrankla, promotera, oldrankal userlabel = Label(root, text="") ranklabel = Label(root, text="") promlabel = Label(root, text="") promotera = Label(root, text="") oldrankal = Label(root, text="") namelabel = Label(root, text="Username:"******"Arial 9 bold") lastpromo = Label(root, text="Last Promo:", font="Arial 9 bold") currerank = Label(root, text="Current Rank:", font="Arial 9 bold") promoterl = Label(root, text="Promoter:", font="Arial 9 bold") oldrankla = Label(root, text="Old Rank:", font="Arial 9 bold") namelabel.grid(row=0, sticky=W) userlabel.grid(row=0, sticky=E) currerank.grid(row=1, sticky=W) ranklabel.grid(row=1, sticky=E) lastpromo.grid(row=2, sticky=W) promlabel.grid(row=2, sticky=E) promoterl.grid(row=3, sticky=W) promotera.grid(row=3, sticky=E) oldrankla.grid(row=4, sticky=W) oldrankal.grid(row=4, sticky=E) skine = Entry(root) skinl = Label(root, text="Type a username") skinb = Button(root, text="Search", command=search_user) skinl.place(relx=0.72, x=1, y=105, anchor=NE) skine.place(relx=0.76, x=1, y=130, anchor=NE) skinb.place(relx=0.6, x=1, y=155, anchor=NE) skine.focus_set()
def create_widgets(self): self.name = StringVar(self.parent) self.fontSize = StringVar(self.parent) self.frameMain = Frame(self, borderwidth=2, relief=SUNKEN) self.frameMain.pack(side=TOP, expand=TRUE, fill=BOTH) self.messageInfo = Message(self.frameMain, anchor=W, justify=LEFT, padx=5, pady=5, text=self.message) #,aspect=200) entryName = Entry(self.frameMain, textvariable=self.name, width=30) entryName.focus_set() self.messageInfo.pack(padx=5, pady=5) #, expand=TRUE, fill=BOTH) entryName.pack(padx=5, pady=5) frameButtons = Frame(self, pady=2) frameButtons.pack(side=BOTTOM) self.buttonOk = Button(frameButtons, text='Ok', width=8, command=self.Ok) self.buttonOk.pack(side=LEFT, padx=5) self.buttonCancel = Button(frameButtons, text='Cancel', width=8, command=self.Cancel) self.buttonCancel.pack(side=RIGHT, padx=5)
def __init__(self, container, img=None, p=None): root = Tk() root.attributes('-topmost', 1) hint = '(Enter - submit, Esc - abort)' if img is None: root.wm_title('Address') hint = 'Please enter your Bitcoin address.\n' + hint else: root.wm_title('Captcha {0:g}'.format(p)) img = ImageTk.PhotoImage(img) root.img_reference = img image = Label(root, image=img, text=hint, compound='top') image.pack() entry = Entry(root) entry.bind('<Escape>', lambda _: root.destroy()) entry.bind( '<Return>', lambda _: (container.setdefault(0, (entry.get())), root.destroy())) entry.pack() entry.focus_set() root.update_idletasks() xp = (root.winfo_screenwidth() / 2) - (root.winfo_width() / 2) - 8 yp = (root.winfo_screenheight() / 2) - (root.winfo_height() / 2) - 20 root.geometry('+%d+%d' % (xp, yp)) root.mainloop()
def get_name(self): frame = DraggableFrame(self._root) frame.pack(side=TOP, fill=BOTH, expand=YES) frame.columnconfigure(0, weight=1) frame.columnconfigure(4, weight=1) frame.rowconfigure(0, weight=1) frame.rowconfigure(4, weight=1) w = self._set_frame_geo(frame, 0.3, 0.3)[2] self._set_x_button(frame, w, self._close_get_name) Label(frame, text="Name:").grid(column=1, row=1) entry_style = SUNKEN if self._is_osx else FLAT entry = Entry(frame, exportselection=0, relief=entry_style, textvariable=self._name) entry.grid(column=2, row=1) entry.focus_set() error_label = Label(frame, fg='red') error_label.grid(column=1, row=2, columnspan=3) ok_cmd = partial(self._validate_name, error_label) FlatButton(frame, text='OK', width=20, font=("calibri", 15), command=ok_cmd).grid(column=1, row=3, columnspan=3) self._root.bind('<Return>', ok_cmd) self._root.bind('<Escape>', self._close_get_name) self._run() return self._name.get() if self._name else self._name
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)))
class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """lauch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """lauches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='')
class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='')
def input_input_text(self, e, **kwargs): var = StringVar(master=self.frame) self.master.serialized[e.name] = lambda: var.get() if e.value is not None: var.set(e.value) w = Entry(self.frame, textvariable=var, **kwargs) self.pack_element(w) w.focus_set() return w
class TkList(List): def __init__(self, file, tk): List.__init__(self, file) # Create the frame with list items self.frame = Frame(tk, padx = 0, pady = 10, bd = 0) self.frame.pack() # Create the field to input new list items self.input = Entry(tk, width = 32, bd = 1, insertborderwidth = 1, relief = FLAT) self.input.pack(anchor = N, pady = 4, side = LEFT, fill = X) self.input.focus_set() self.input.bind('<Return>', lambda l: self.add_item(self.input.get())) # Create an add button to the input field Button(tk, text = "+", relief = FLAT, command = lambda: self.add_item(self.input.get())).pack(anchor = N, side = RIGHT) # Update the list frame self.update() def add_item(self, text): List.add_item(self, text) # Clear input field self.input.delete(0, END) # Update the list frame self.update() def remove_item(self, text): List.remove_item(self, text) # Update the list frame self.update() def checkbox(self, text): # Return a button that will remove the list item return Button(self.frame, text = "-", relief = FLAT, command = lambda: self.remove_item(text)) def update(self): # Remove previous list items for child in self.frame.winfo_children(): child.destroy() # Draw each item in the list i = 0 for item in self.list: self.checkbox(item).grid(row = i) Label(self.frame, text = item).grid(row = i, column = 1) i = i + 1 # Save the list List.save_list(self)
class AuthDialog(Popup): message = _('Enter username and password\nfor "%(method)s" at "%(realm)s"') def __init__(self, parent, deferred, method, realm, addnl=None): self.deferred = deferred self.method = method self.realm = realm self._saveOK = False Popup.__init__(self, parent, addnl) def _saveBoolean(self, *value): self._saveOK = not self._saveOK def getResult(self): return (self.uentry.get(), self.pentry.get(), self._saveOK) def body(self): print "auth body" from Tkinter import NW, E, W, Frame, Label, Button, Entry, Checkbutton defargs = { 'padx':5, 'pady':5, 'sticky':W } self.top = Frame(self) self.top.grid(row=1,column=1,sticky=NW) msg = self.message % { 'realm':self.realm, 'method':self.method } self.label = Label(self.top, text=msg, justify='center') self.label.grid(row=1, column=1, columnspan=4, **defargs) self.ulabel = Label(self.top, text=_('User Name')+':', justify='left') self.ulabel.grid(row=2, column=1, columnspan=2, **defargs) self.uentry = Entry(self.top) self.uentry.grid(row=2, column=3, columnspan=2, **defargs) self.uentry.focus_set() self.plabel = Label(self.top, text=_('Password')+':', justify='left') self.plabel.grid(row=3, column=1, columnspan=2, **defargs) self.pentry = Entry(self.top, show="*") self.pentry.grid(row=3, column=3, columnspan=2, **defargs) self._saveOk = False self.saveCheck = Checkbutton(self.top, command=self._saveBoolean) self.saveCheck.grid(row=4, column=1, columnspan=1, **defargs) self.savelabel = Label(self.top, text=_('Save this username and password')) self.savelabel.grid(row=4, column=2, columnspan=3, **defargs) defargs['sticky'] = W self.cancelb = Button(self.top, text=_('Cancel'), command=self.cancel) self.cancelb.grid(row=5, column=3, columnspan=1, **defargs) self.okb = Button(self.top, text=_('OK'), command=self.selected) self.okb.grid(row=5, column=4, columnspan=1, **defargs)
class tester(tk.Frame): def __init__(self, parent): self.parent = parent self.frame = tk.Frame(self.parent) self.canvas = tk.Canvas(parent, width=100, height=100) self.canvas.pack() self.key_dict = {} self.game_over = False #keep track of keypress self.c = 0 self.input_box(parent) B = tk.Button(parent, text="playback states", command=self.start) B.pack() def start(self): try: # Bind entry to any keypress self.entry.bind("<Key>", self.click) # while self.c<5: # if time.time()-start >=2: # print('start thread') # inp = Process(target = self.input_box) # inp.start() # inp.join() #dont make killed process a zombie # inp.terminate() # start = time.time() # self.c+=1 except: print("Error: unable to start thread") def input_box(self, parent): self.entry = Entry() self.entry.focus_set() self.entry.pack() def click(self, key): # print the key that was pressed print(key.char) self.clear_entry() def clear_entry(self): self.entry.delete(0, "end") root.update()
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)))
class FileTypeWindow(object): """Window that lets user type in file types and begin processing. """ BUTTON_FILE_TYPE = 1 def __init__(self, parent, directory): self.parent = parent self.directory = directory self.label1 = Label(self.parent, text="File Types") self.label1.pack(side=LEFT) self.entry1 = Entry(self.parent, bd=5) self.entry1.pack(side=RIGHT) self.entry1.focus_set() self.button_file_type = Button(self.parent, text="Go!", command=lambda: self.on_button_clicked( self.BUTTON_FILE_TYPE)) self.button_file_type.pack(side=RIGHT) def on_button_clicked(self, button_id): """Callback for when any button is clicked. Args: button_id: An identifier for the button. """ if button_id == self.BUTTON_FILE_TYPE: self.button_file_type_clicked() def button_file_type_clicked(self): """Recursively remove folders not containing one of the chosen file types. """ entry = self.entry1 file_types = entry.get() self.parent.destroy() process(file_types, self.directory)
def __init__(self, parent, config): Frame.__init__(self, parent) self.loggedIn = None self.config = config self.pack(fill=BOTH, expand=1, padx=10, pady=10) self.bind("<Return>", self.login) self.message = StringVar() l = Label(self, textvariable=self.message) l.pack() l = Label(self, text="Email:") l.pack(anchor=W, pady=(10, 0)) self.email = StringVar() self.email.set(self.config.get("credentials", "email")) e = Entry(self, textvariable=self.email, width=40, font=("Helvetica", 16)) e.pack(fill=X) e.focus_set() e.icursor(END) e.selection_range(0, END) l = Label(self, text="Password:"******"credentials", "password")) e = Entry(self, show="*", textvariable=self.password, font=("Helvetica", 16)) e.pack(fill=X) self.submit = Button(self, text="Login", command=self.login) self.submit.pack(ipady=10, pady=10, fill=X)
class BrakeFrame(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initialize() def initialize(self): self.grid() self.entryVariable = StringVar() self.entry = Entry(self, textvariable=self.entryVariable) self.entry.grid(column=0,row=0,sticky='EW') self.entry.bind("<Return>", self.OnPressEnter) button = Button(self,text="Set Brake", command=self.OnButtonClick) button.grid(column=1,row=0) self.labelVariable = StringVar() label = Label(self,textvariable=self.labelVariable, anchor="w",fg="white",bg="red") label.grid(column=0,row=1,columnspan=1,sticky='EW') self.labelVariable.set("Start..") onButton = Button(self,text="Brake On", command=self.BrakeOn) onButton.grid(column=0,row=3) offButton = Button(self,text="Brake Off", command=self.BrakeOff) offButton.grid(column=1,row=3) self.brakeVariable = StringVar() brakeState = Label(self,textvariable=self.brakeVariable, anchor="w",fg="white",bg="red") brakeState.grid(column=0,row=2,columnspan=1,sticky='EW') self.brakeVariable.set("Start..") self.grid_columnconfigure(0,weight=1) self.update() #self.geometry(self.geometry()) # caused busy wait? self.entry.focus_set() #self.entry.selection_range(0, Tkinter.END) def OnButtonClick(self): brakePos = int(self.entryVariable.get()) brake.SetPositionMM(brakePos) self.labelVariable.set("Brake set: " + str(brakePos) ) self.entry.focus_set() self.entry.selection_range(0, END) def OnPressEnter(self,event): brakePos = int(self.entryVariable.get()) brake.SetPositionMM(brakePos) self.labelVariable.set("Brake set: " + str(brakePos) ) self.entry.focus_set() self.entry.selection_range(0, END) def BrakeOn(self): self.brakeVariable.set("Brake: ON") brake.SetFullOn() def BrakeOff(self): self.brakeVariable.set("Brake: OFF") brake.SetOff()
class TreeNode: def __init__(self, canvas, parent, item): self.canvas = canvas self.parent = parent self.item = item self.state = 'collapsed' self.selected = False self.children = [] self.x = self.y = None self.iconimages = {} # cache of PhotoImage instances for icons def destroy(self): for c in self.children[:]: self.children.remove(c) c.destroy() self.parent = None def geticonimage(self, name): try: return self.iconimages[name] except KeyError: pass file, ext = os.path.splitext(name) ext = ext or ".gif" fullname = os.path.join(ICONDIR, file + ext) image = PhotoImage(master=self.canvas, file=fullname) self.iconimages[name] = image return image def select(self, event=None): if self.selected: return self.deselectall() self.selected = True self.canvas.delete(self.image_id) self.drawicon() self.drawtext() def deselect(self, event=None): if not self.selected: return self.selected = False self.canvas.delete(self.image_id) self.drawicon() self.drawtext() def deselectall(self): if self.parent: self.parent.deselectall() else: self.deselecttree() def deselecttree(self): if self.selected: self.deselect() for child in self.children: child.deselecttree() def flip(self, event=None): if self.state == 'expanded': self.collapse() else: self.expand() self.item.OnDoubleClick() return "break" def expand(self, event=None): if not self.item._IsExpandable(): return if self.state != 'expanded': self.state = 'expanded' self.update() self.view() def collapse(self, event=None): if self.state != 'collapsed': self.state = 'collapsed' self.update() def view(self): top = self.y - 2 bottom = self.lastvisiblechild().y + 17 height = bottom - top visible_top = self.canvas.canvasy(0) visible_height = self.canvas.winfo_height() visible_bottom = self.canvas.canvasy(visible_height) if visible_top <= top and bottom <= visible_bottom: return x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion']) if top >= visible_top and height <= visible_height: fraction = top + height - visible_height else: fraction = top fraction = float(fraction) / y1 self.canvas.yview_moveto(fraction) def lastvisiblechild(self): if self.children and self.state == 'expanded': return self.children[-1].lastvisiblechild() else: return self def update(self): if self.parent: self.parent.update() else: oldcursor = self.canvas['cursor'] self.canvas['cursor'] = "watch" self.canvas.update() self.canvas.delete(ALL) # XXX could be more subtle self.draw(7, 2) x0, y0, x1, y1 = self.canvas.bbox(ALL) self.canvas.configure(scrollregion=(0, 0, x1, y1)) self.canvas['cursor'] = oldcursor def draw(self, x, y): # XXX This hard-codes too many geometry constants! self.x, self.y = x, y self.drawicon() self.drawtext() if self.state != 'expanded': return y + 17 # draw children if not self.children: sublist = self.item._GetSubList() if not sublist: # _IsExpandable() was mistaken; that's allowed return y + 17 for item in sublist: child = self.__class__(self.canvas, self, item) self.children.append(child) cx = x + 20 cy = y + 17 cylast = 0 for child in self.children: cylast = cy self.canvas.create_line(x + 9, cy + 7, cx, cy + 7, fill="gray50") cy = child.draw(cx, cy) if child.item._IsExpandable(): if child.state == 'expanded': iconname = "minusnode" callback = child.collapse else: iconname = "plusnode" callback = child.expand image = self.geticonimage(iconname) id = self.canvas.create_image(x + 9, cylast + 7, image=image) # XXX This leaks bindings until canvas is deleted: self.canvas.tag_bind(id, "<1>", callback) self.canvas.tag_bind(id, "<Double-1>", lambda x: None) id = self.canvas.create_line( x + 9, y + 10, x + 9, cylast + 7, ##stipple="gray50", # XXX Seems broken in Tk 8.0.x fill="gray50") self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2 return cy def drawicon(self): if self.selected: imagename = (self.item.GetSelectedIconName() or self.item.GetIconName() or "openfolder") else: imagename = self.item.GetIconName() or "folder" image = self.geticonimage(imagename) id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image) self.image_id = id self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) def drawtext(self): textx = self.x + 20 - 1 texty = self.y - 1 labeltext = self.item.GetLabelText() if labeltext: id = self.canvas.create_text(textx, texty, anchor="nw", text=labeltext) self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) x0, y0, x1, y1 = self.canvas.bbox(id) textx = max(x1, 200) + 10 text = self.item.GetText() or "<no text>" try: self.entry except AttributeError: pass else: self.edit_finish() try: label = self.label except AttributeError: # padding carefully selected (on Windows) to match Entry widget: self.label = Label(self.canvas, text=text) if not TTK: self.label.configure(bd=0, padx=2, pady=2) theme = idleConf.GetOption('main', 'Theme', 'name') if self.selected: self.label.configure(idleConf.GetHighlight(theme, 'hilite')) else: self.label.configure(idleConf.GetHighlight(theme, 'normal')) id = self.canvas.create_window(textx, texty, anchor="nw", window=self.label) self.label.bind("<1>", self.select_or_edit) self.label.bind("<Double-1>", self.flip) self.text_id = id def select_or_edit(self, event=None): if self.selected and self.item.IsEditable(): self.edit(event) else: self.select(event) def edit(self, event=None): self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0) self.entry.insert(0, self.label['text']) self.entry.selection_range(0, END) self.entry.pack(ipadx=5) self.entry.focus_set() self.entry.bind("<Return>", self.edit_finish) self.entry.bind("<Escape>", self.edit_cancel) def edit_finish(self, event=None): try: entry = self.entry del self.entry except AttributeError: return text = entry.get() entry.destroy() if text and text != self.item.GetText(): self.item.SetText(text) text = self.item.GetText() self.label['text'] = text self.drawtext() self.canvas.focus_set() def edit_cancel(self, event=None): try: entry = self.entry del self.entry except AttributeError: return entry.destroy() self.drawtext() self.canvas.focus_set()
class GuiMainWindow(Frame): def __init__(self, master): Frame.__init__(self, master) self.serial_num = StringVar() self.gpioPin = StringVar() self.serial_num_smt = StringVar() self.master = master self.results = StringVar() self.debug_mode = BooleanVar() self.__initUi() #=========================================================================== # Initialize and reset GUI #=========================================================================== def __initUi(self): self.master.title('GPIO Test') self.pack(fill=BOTH, expand=1) Style().configure("TFrame", background="#333") # Status of Test frame self.status_frame = LabelFrame(self, text='Status', relief=RIDGE, width=235, height=100) self.status_frame.place(x=20, y=20) self.path_frame_1 = LabelFrame(self, text='GPIO Pin (between 0 and 27)', relief=RIDGE, height=60, width=235) self.path_frame_1.place(x=20, y=150) self.entry_1 = Entry(self.path_frame_1, bd=5, textvariable=self.gpioPin) self.entry_1.place(x=20, y=5) self.entry_1.focus_set() # TEST RESULTS LABEL w = Label(self.status_frame, textvariable=self.results) w.place(x=50, y=50) # Toggle Button self.toggleButton = Button(self, text="Toggle", command=self.toggle, height=4, width=20, background='green') self.toggleButton.place(x=20, y=250) self.toggleButton.bind('<Return>', lambda e: self.hi()) self.isHi = False gpio_ns_init() def toggle(self): pin = self.entry_1.get() if pin == "": self.status_frame.config(text="Invalid pin!", bg=STATUS_ERROR_COLOR) return validPin = re.match('^[0-9]{1,2}$', pin) if not validPin or (int(pin) < 4 or int(pin) > 27): self.status_frame.config(text="Invalid pin!", bg=STATUS_ERROR_COLOR) return if self.isHi: self.status_frame.config(text='Pin is low', bg=STATUS_OK_COLOR) self.isHi = False self.toggleButton['text'] = "Set Hi" gpio_ns_write(int(pin), GPIO_LO) else: self.isHi = True self.status_frame.config(text='Pin is hi', bg=STATUS_OK_COLOR) self.toggleButton['text'] = "Set Low" gpio_ns_write(int(pin), GPIO_HI)
class TreeNode: def __init__(self, canvas, parent, item): self.canvas = canvas self.parent = parent self.item = item self.state = 'collapsed' self.selected = False self.children = [] self.x = self.y = None self.iconimages = {} # cache of PhotoImage instances for icons def destroy(self): for c in self.children[:]: self.children.remove(c) c.destroy() self.parent = None def geticonimage(self, name): try: return self.iconimages[name] except KeyError: pass file, ext = os.path.splitext(name) ext = ext or ".gif" fullname = os.path.join(ICONDIR, file + ext) image = PhotoImage(master=self.canvas, file=fullname) self.iconimages[name] = image return image def select(self, event=None): if self.selected: return self.deselectall() self.selected = True self.canvas.delete(self.image_id) self.drawicon() self.drawtext() def deselect(self, event=None): if not self.selected: return self.selected = False self.canvas.delete(self.image_id) self.drawicon() self.drawtext() def deselectall(self): if self.parent: self.parent.deselectall() else: self.deselecttree() def deselecttree(self): if self.selected: self.deselect() for child in self.children: child.deselecttree() def flip(self, event=None): if self.state == 'expanded': self.collapse() else: self.expand() self.item.OnDoubleClick() return "break" def expand(self, event=None): if not self.item._IsExpandable(): return if self.state != 'expanded': self.state = 'expanded' self.update() self.view() def collapse(self, event=None): if self.state != 'collapsed': self.state = 'collapsed' self.update() def view(self): top = self.y - 2 bottom = self.lastvisiblechild().y + 17 height = bottom - top visible_top = self.canvas.canvasy(0) visible_height = self.canvas.winfo_height() visible_bottom = self.canvas.canvasy(visible_height) if visible_top <= top and bottom <= visible_bottom: return x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion']) if top >= visible_top and height <= visible_height: fraction = top + height - visible_height else: fraction = top fraction = float(fraction) / y1 self.canvas.yview_moveto(fraction) def lastvisiblechild(self): if self.children and self.state == 'expanded': return self.children[-1].lastvisiblechild() else: return self def update(self): if self.parent: self.parent.update() else: oldcursor = self.canvas['cursor'] self.canvas['cursor'] = "watch" self.canvas.update() self.canvas.delete(ALL) # XXX could be more subtle self.draw(7, 2) x0, y0, x1, y1 = self.canvas.bbox(ALL) self.canvas.configure(scrollregion=(0, 0, x1, y1)) self.canvas['cursor'] = oldcursor def draw(self, x, y): # XXX This hard-codes too many geometry constants! dy = 20 self.x, self.y = x, y self.drawicon() self.drawtext() if self.state != 'expanded': return y + dy # draw children if not self.children: sublist = self.item._GetSubList() if not sublist: # _IsExpandable() was mistaken; that's allowed return y+17 for item in sublist: child = self.__class__(self.canvas, self, item) self.children.append(child) cx = x+20 cy = y + dy cylast = 0 for child in self.children: cylast = cy self.canvas.create_line(x+9, cy+7, cx, cy+7, fill="gray50") cy = child.draw(cx, cy) if child.item._IsExpandable(): if child.state == 'expanded': iconname = "minusnode" callback = child.collapse else: iconname = "plusnode" callback = child.expand image = self.geticonimage(iconname) id = self.canvas.create_image(x+9, cylast+7, image=image) # XXX This leaks bindings until canvas is deleted: self.canvas.tag_bind(id, "<1>", callback) self.canvas.tag_bind(id, "<Double-1>", lambda x: None) id = self.canvas.create_line(x+9, y+10, x+9, cylast+7, ##stipple="gray50", # XXX Seems broken in Tk 8.0.x fill="gray50") self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2 return cy def drawicon(self): if self.selected: imagename = (self.item.GetSelectedIconName() or self.item.GetIconName() or "openfolder") else: imagename = self.item.GetIconName() or "folder" image = self.geticonimage(imagename) id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image) self.image_id = id self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) def drawtext(self): textx = self.x+20-1 texty = self.y-4 labeltext = self.item.GetLabelText() if labeltext: id = self.canvas.create_text(textx, texty, anchor="nw", text=labeltext) self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) x0, y0, x1, y1 = self.canvas.bbox(id) textx = max(x1, 200) + 10 text = self.item.GetText() or "<no text>" try: self.entry except AttributeError: pass else: self.edit_finish() try: self.label except AttributeError: # padding carefully selected (on Windows) to match Entry widget: self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2) theme = idleConf.CurrentTheme() if self.selected: self.label.configure(idleConf.GetHighlight(theme, 'hilite')) else: self.label.configure(idleConf.GetHighlight(theme, 'normal')) id = self.canvas.create_window(textx, texty, anchor="nw", window=self.label) self.label.bind("<1>", self.select_or_edit) self.label.bind("<Double-1>", self.flip) self.text_id = id def select_or_edit(self, event=None): if self.selected and self.item.IsEditable(): self.edit(event) else: self.select(event) def edit(self, event=None): self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0) self.entry.insert(0, self.label['text']) self.entry.selection_range(0, END) self.entry.pack(ipadx=5) self.entry.focus_set() self.entry.bind("<Return>", self.edit_finish) self.entry.bind("<Escape>", self.edit_cancel) def edit_finish(self, event=None): try: entry = self.entry del self.entry except AttributeError: return text = entry.get() entry.destroy() if text and text != self.item.GetText(): self.item.SetText(text) text = self.item.GetText() self.label['text'] = text self.drawtext() self.canvas.focus_set() def edit_cancel(self, event=None): try: entry = self.entry del self.entry except AttributeError: return entry.destroy() self.drawtext() self.canvas.focus_set()
class GUI(Tk): def __init__(self, parent): '''Constructor''' Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): '''Sets the parameters of the view and displays it''' self.grid() self.fullscreen() self.update() def fullscreen(self): '''Sets the view to fullscreen''' self.geometry("%dx%d+0+0" % (self.winfo_screenwidth(), self.winfo_screenheight())) self.overrideredirect(1) # Removes borders self.resizable(False, False) self.configure(background = "black") self.focus_set() def createPrompt(self, startFunction, endFunction): ''' Writes instructions for the participant and keybinds starting and ending functions Args: startFunction(): the function that iterates when the user presses <<ENTER>> endFunction(): the function that closes the program and saves the session data upon pressing <<ESCAPE>> ''' self.labelVariable = StringVar() self.label = Label(self, textvariable=self.labelVariable, anchor="center", fg="white", bg="black", font="Arial 24 bold", wraplength=1100) self.label.grid(column=0, row=0, padx=20, pady=20) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.setLabel(self.loadIntro(), startFunction) self.bind("<Escape>", endFunction) def createEntryBox(self): '''Creates an area for the participant to enter a response''' self.entryVariable = StringVar() self.entry = Entry(self, textvariable=self.entryVariable, font="Arial 24", bd = 0, fg="white", bg="black", insertbackground = "white", justify = "center") self.entry.grid(column=0, row=1, sticky = 'EW') self.grid_rowconfigure(0, weight=0) self.grid_rowconfigure(1, weight=0) self.entry.focus_set() self.entryVariable.set("") def loadIntro(self): '''Loads text from INTRO.txt''' currentPath = os.path.dirname(os.path.realpath(__file__)) file = open(currentPath + "\..\intro.txt") intro = file.readlines() intro += "\n\nWhen you are ready, press ENTER to continue." file.close() return ''.join(intro) def setLabel(self, message, newFunction): '''Changes the text that is displayed on screen Args: message (str): The text to be displayed newFunction(): Executes when the user presses <<ENTER>> ''' self.labelVariable.set(message) self.bind("<Return>", newFunction) def greyScreen(self): '''Displays a grey screen between trials to give the participant a short break. Purely aesthetic. ''' GREY = "#888888" self.configure(background=GREY) self.label.configure(fg=GREY, bg=GREY) self.entry.configure(fg=GREY, bg=GREY, insertbackground=GREY) self.update() sleep(1.5) self.configure(background="black") self.label.configure(fg="white", bg="black") self.entry.configure(fg="white", bg="black", insertbackground="white") self.update()
class Homunculus_Vocabulary(Homunculus): def get_row(self, cut_off=0): result = self.grid_row - cut_off self.grid_row += 1 return result def __init__(self, params): self.grid_row = 0 Homunculus.__init__(self, params[0]) self.title(settings.HOMUNCULUS_VERSION + settings.HMC_TITLE_VOCABULARY) self.mode = params[0] clipboard_text = params[1] if self.mode == settings.QTYPE_SET: self.geometry("640x480+" + str(int(self.winfo_screenwidth() / 2 - 320)) + "+" + str(int(self.winfo_screenheight() / 2 - 240))) self.instructions = "Add/Modify Word" Label(self, text=self.instructions, name="pathlabel").grid(row=self.get_row(), column=1, sticky=tk.E) wf_row = self.get_row() Label(self, text="(W)ord:", name="wordlabel").grid(row=wf_row, column=0, sticky=tk.W) self.word_box = Entry(self, name="word_box") self.word_box.grid(row=wf_row, column=1, sticky=tk.W) if clipboard_text != None: self.word_box.insert(0, clipboard_text) p_row = self.get_row() Label(self, text="(P)ronunciation:", name="pronunciationlabel").grid(row=p_row, column=0, sticky=tk.W) self.pronunciation_box = Entry(self, name="pronunciation_box") self.pronunciation_box.grid(row=p_row, column=1, sticky=tk.W) self.force_add_var = tk.IntVar() self.force_add_var.set(True) self.force_add = Checkbutton(self, text="Force Add", variable=self.force_add_var).grid(row=self.get_row(), column=0, sticky=tk.W) Label(self, text="Options", name="optionslabel").grid(row=self.get_row(), column=1, sticky=tk.E) self.word_state = [] cb_number = 1 for state in [("Word added by user", 0x00000001), ("Can't be deleted", 0x00000008), ("Usually cap next (like period)", 0x00000010), ("Always cap next (like Cap Next)", 0x00000020), ("Uppercase next (All Caps Next)", 0x00000040), ("Lowercase next (No Caps Next)", 0x00000080), ("No space following (left paren)", 0x00000100), ("Two spaces following (period)", 0x00000200), ("No spaces between words (numbers)", 0x00000400), ("Capitalization mode on (Caps On)", 0x00000800), ("Uppercase mode on (All Caps On)", 0x00001000), ("Lowercase mode on (No Caps On)", 0x00002000), ("Space betw words off (No Space On)", 0x00004000), ("Restore normal spacing (No Space Off)", 0x00008000), ("Suppress period (...)", 0x00020000), ("No formatting (like Cap)", 0x00040000), ("No reset spacing (like Cap)", 0x00080000), ("No reset caps (close quote)", 0x00100000), ("No space preceeding (comma)", 0x00200000), ("Restore normal caps (Caps Off)", 0x00400000), ("Follow with new line (New-Line)", 0x00800000), ("Follow with new-p (New-Paragraph)", 0x01000000), ("Don't cap in title (like and)", 0x02000000), ("Follow with extra space (space)", 0x08000000), ("Word added by vocab builder.", 0x40000000) ]: cb_row = 0 # self.get_row() cb_col = 0 row_cut_off = 14 col2_inc = -1 word_state_var = tk.IntVar() if cb_number == 1: word_state_var.set(True) if cb_number < row_cut_off: cb_row = cb_row = self.get_row() else : cb_row = cb_row = self.get_row(row_cut_off + col2_inc) cb_col = 2 col2_inc += 1 Checkbutton(self, text="(" + str(cb_number) + ")", variable=word_state_var).grid(row=cb_row, column=cb_col + 1, sticky=tk.W) cb_number += 1 Label(self, text=state[0], name="cb_label" + str(cb_number)).grid(row=cb_row, column=cb_col, sticky=tk.W) self.word_state.append((word_state_var, state[1])) elif self.mode == settings.QTYPE_REM: self.geometry("300x100+" + str(int(self.winfo_screenwidth() / 2 - 150)) + "+" + str(int(self.winfo_screenheight() / 2 - 50))) self.instructions = "Delete Word" Label(self, text=self.instructions, name="pathlabel").grid(row=self.get_row(), column=1, sticky=tk.E) wf_row = self.get_row() Label(self, text="(W)ord:", name="wordlabel").grid(row=wf_row, column=0, sticky=tk.W) self.word_box = Entry(self, name="word_box") self.word_box.grid(row=wf_row, column=1, sticky=tk.W) def xmlrpc_get_message(self): if self.completed: response = {"mode": self.mode} word = self.word_box.get() if len(word) == 0: self.xmlrpc_kill() response["word"] = word if self.mode == settings.QTYPE_SET: pronunciation = self.pronunciation_box.get() if len(pronunciation) == 0: pronunciation = "" response["pronunciation"] = pronunciation response["force"] = self.force_add_var.get() word_info = 0x00000000 for ws in self.word_state: if ws[0].get() == 1: word_info += ws[1] response["word_info"] = word_info Timer(1, self.xmlrpc_kill).start() self.after(10, self.withdraw) return response else: return None def xmlrpc_do_action(self, action, details=None): '''acceptable keys are numbers and w and p''' if action == "check": for box_index in details: if box_index >= 1 and box_index <= 25: if self.word_state[box_index - 1][0].get() == 0: self.word_state[box_index - 1][0].set(True) else: self.word_state[box_index - 1][0].set(False) elif action == "focus": if details == "word": self.word_box.focus_set() elif details == "pronunciation": self.pronunciation_box.focus_set()
class GetKeysDialog(Toplevel): def __init__(self,parent,title,action,currentKeySequences,_htest=False): """ action - string, the name of the virtual event these keys will be mapped to currentKeys - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest """ Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.resizable(height=FALSE,width=FALSE) self.title(title) self.transient(parent) self.grab_set() self.protocol("WM_DELETE_WINDOW", self.Cancel) self.parent = parent self.action=action self.currentKeySequences=currentKeySequences self.result='' self.keyString=StringVar(self) self.keyString.set('') self.SetModifiersForPlatform() # set self.modifiers, self.modifier_label self.modifier_vars = [] for modifier in self.modifiers: variable = StringVar(self) variable.set('') self.modifier_vars.append(variable) self.advanced = False self.CreateWidgets() self.LoadFinalKeyList() self.withdraw() #hide while setting geometry self.update_idletasks() self.geometry( "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width()/2 - self.winfo_reqwidth()/2), parent.winfo_rooty() + ((parent.winfo_height()/2 - self.winfo_reqheight()/2) if not _htest else 150) ) ) #centre dialog over parent (or below htest box) self.deiconify() #geometry set, unhide self.wait_window() def CreateWidgets(self): frameMain = Frame(self,borderwidth=2,relief=SUNKEN) frameMain.pack(side=TOP,expand=TRUE,fill=BOTH) frameButtons=Frame(self) frameButtons.pack(side=BOTTOM,fill=X) self.buttonOK = Button(frameButtons,text='OK', width=8,command=self.OK) self.buttonOK.grid(row=0,column=0,padx=5,pady=5) self.buttonCancel = Button(frameButtons,text='Cancel', width=8,command=self.Cancel) self.buttonCancel.grid(row=0,column=1,padx=5,pady=5) self.frameKeySeqBasic = Frame(frameMain) self.frameKeySeqAdvanced = Frame(frameMain) self.frameControlsBasic = Frame(frameMain) self.frameHelpAdvanced = Frame(frameMain) self.frameKeySeqAdvanced.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5) self.frameKeySeqBasic.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5) self.frameKeySeqBasic.lift() self.frameHelpAdvanced.grid(row=1,column=0,sticky=NSEW,padx=5) self.frameControlsBasic.grid(row=1,column=0,sticky=NSEW,padx=5) self.frameControlsBasic.lift() self.buttonLevel = Button(frameMain,command=self.ToggleLevel, text='Advanced Key Binding Entry >>') self.buttonLevel.grid(row=2,column=0,stick=EW,padx=5,pady=5) labelTitleBasic = Label(self.frameKeySeqBasic, text="New keys for '"+self.action+"' :") labelTitleBasic.pack(anchor=W) labelKeysBasic = Label(self.frameKeySeqBasic,justify=LEFT, textvariable=self.keyString,relief=GROOVE,borderwidth=2) labelKeysBasic.pack(ipadx=5,ipady=5,fill=X) self.modifier_checkbuttons = {} column = 0 for modifier, variable in zip(self.modifiers, self.modifier_vars): label = self.modifier_label.get(modifier, modifier) check=Checkbutton(self.frameControlsBasic, command=self.BuildKeyString, text=label,variable=variable,onvalue=modifier,offvalue='') check.grid(row=0,column=column,padx=2,sticky=W) self.modifier_checkbuttons[modifier] = check column += 1 labelFnAdvice=Label(self.frameControlsBasic,justify=LEFT, text=\ "Select the desired modifier keys\n"+ "above, and the final key from the\n"+ "list on the right.\n\n" + "Use upper case Symbols when using\n" + "the Shift modifier. (Letters will be\n" + "converted automatically.)") labelFnAdvice.grid(row=1,column=0,columnspan=4,padx=2,sticky=W) self.listKeysFinal=Listbox(self.frameControlsBasic,width=15,height=10, selectmode=SINGLE) self.listKeysFinal.bind('<ButtonRelease-1>',self.FinalKeySelected) self.listKeysFinal.grid(row=0,column=4,rowspan=4,sticky=NS) scrollKeysFinal=Scrollbar(self.frameControlsBasic,orient=VERTICAL, command=self.listKeysFinal.yview) self.listKeysFinal.config(yscrollcommand=scrollKeysFinal.set) scrollKeysFinal.grid(row=0,column=5,rowspan=4,sticky=NS) self.buttonClear=Button(self.frameControlsBasic, text='Clear Keys',command=self.ClearKeySeq) self.buttonClear.grid(row=2,column=0,columnspan=4) labelTitleAdvanced = Label(self.frameKeySeqAdvanced,justify=LEFT, text="Enter new binding(s) for '"+self.action+"' :\n"+ "(These bindings will not be checked for validity!)") labelTitleAdvanced.pack(anchor=W) self.entryKeysAdvanced=Entry(self.frameKeySeqAdvanced, textvariable=self.keyString) self.entryKeysAdvanced.pack(fill=X) labelHelpAdvanced=Label(self.frameHelpAdvanced,justify=LEFT, text="Key bindings are specified using Tkinter keysyms as\n"+ "in these samples: <Control-f>, <Shift-F2>, <F12>,\n" "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n" "Upper case is used when the Shift modifier is present!\n\n" + "'Emacs style' multi-keystroke bindings are specified as\n" + "follows: <Control-x><Control-y>, where the first key\n" + "is the 'do-nothing' keybinding.\n\n" + "Multiple separate bindings for one action should be\n"+ "separated by a space, eg., <Alt-v> <Meta-v>." ) labelHelpAdvanced.grid(row=0,column=0,sticky=NSEW) def SetModifiersForPlatform(self): """Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn't matter if the keyboard has these keys, it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering. """ if sys.platform == "darwin": self.modifiers = ['Shift', 'Control', 'Option', 'Command'] else: self.modifiers = ['Control', 'Alt', 'Shift'] self.modifier_label = {'Control': 'Ctrl'} # short name def ToggleLevel(self): if self.buttonLevel.cget('text')[:8]=='Advanced': self.ClearKeySeq() self.buttonLevel.config(text='<< Basic Key Binding Entry') self.frameKeySeqAdvanced.lift() self.frameHelpAdvanced.lift() self.entryKeysAdvanced.focus_set() self.advanced = True else: self.ClearKeySeq() self.buttonLevel.config(text='Advanced Key Binding Entry >>') self.frameKeySeqBasic.lift() self.frameControlsBasic.lift() self.advanced = False def FinalKeySelected(self,event): self.BuildKeyString() def BuildKeyString(self): keyList = modifiers = self.GetModifiers() finalKey = self.listKeysFinal.get(ANCHOR) if finalKey: finalKey = self.TranslateKey(finalKey, modifiers) keyList.append(finalKey) self.keyString.set('<' + string.join(keyList,'-') + '>') def GetModifiers(self): modList = [variable.get() for variable in self.modifier_vars] return [mod for mod in modList if mod] def ClearKeySeq(self): self.listKeysFinal.select_clear(0,END) self.listKeysFinal.yview(MOVETO, '0.0') for variable in self.modifier_vars: variable.set('') self.keyString.set('') def LoadFinalKeyList(self): #these tuples are also available for use in validity checks self.functionKeys=('F1','F2','F2','F4','F5','F6','F7','F8','F9', 'F10','F11','F12') self.alphanumKeys=tuple(string.ascii_lowercase+string.digits) self.punctuationKeys=tuple('~!@#%^&*()_-+={}[]|;:,.<>/?') self.whitespaceKeys=('Tab','Space','Return') self.editKeys=('BackSpace','Delete','Insert') self.moveKeys=('Home','End','Page Up','Page Down','Left Arrow', 'Right Arrow','Up Arrow','Down Arrow') #make a tuple of most of the useful common 'final' keys keys=(self.alphanumKeys+self.punctuationKeys+self.functionKeys+ self.whitespaceKeys+self.editKeys+self.moveKeys) self.listKeysFinal.insert(END, *keys) def TranslateKey(self, key, modifiers): "Translate from keycap symbol to the Tkinter keysym" translateDict = {'Space':'space', '~':'asciitilde','!':'exclam','@':'at','#':'numbersign', '%':'percent','^':'asciicircum','&':'ampersand','*':'asterisk', '(':'parenleft',')':'parenright','_':'underscore','-':'minus', '+':'plus','=':'equal','{':'braceleft','}':'braceright', '[':'bracketleft',']':'bracketright','|':'bar',';':'semicolon', ':':'colon',',':'comma','.':'period','<':'less','>':'greater', '/':'slash','?':'question','Page Up':'Prior','Page Down':'Next', 'Left Arrow':'Left','Right Arrow':'Right','Up Arrow':'Up', 'Down Arrow': 'Down', 'Tab':'Tab'} if key in translateDict.keys(): key = translateDict[key] if 'Shift' in modifiers and key in string.ascii_lowercase: key = key.upper() key = 'Key-' + key return key def OK(self, event=None): if self.advanced or self.KeysOK(): # doesn't check advanced string yet self.result=self.keyString.get() self.destroy() def Cancel(self, event=None): self.result='' self.destroy() def KeysOK(self): '''Validity check on user's 'basic' keybinding selection. Doesn't check the string produced by the advanced dialog because 'modifiers' isn't set. ''' keys = self.keyString.get() keys.strip() finalKey = self.listKeysFinal.get(ANCHOR) modifiers = self.GetModifiers() # create a key sequence list for overlap check: keySequence = keys.split() keysOK = False title = 'Key Sequence Error' if not keys: tkMessageBox.showerror(title=title, parent=self, message='No keys specified.') elif not keys.endswith('>'): tkMessageBox.showerror(title=title, parent=self, message='Missing the final Key') elif (not modifiers and finalKey not in self.functionKeys + self.moveKeys): tkMessageBox.showerror(title=title, parent=self, message='No modifier key(s) specified.') elif (modifiers == ['Shift']) \ and (finalKey not in self.functionKeys + self.moveKeys + ('Tab', 'Space')): msg = 'The shift modifier by itself may not be used with'\ ' this key symbol.' tkMessageBox.showerror(title=title, parent=self, message=msg) elif keySequence in self.currentKeySequences: msg = 'This key combination is already in use.' tkMessageBox.showerror(title=title, parent=self, message=msg) else: keysOK = True return keysOK
class editPool(Frame): font_decorations = ("italic", "bold", "subscript", "superscript") font_decorations_to_names = { "italic": _("italic"), "bold": _("bold"), "subscript": _("subscript"), "superscript": _("superscript"), } font_decorations_to_html = {"italic": "i", "bold": "b", "subscript": "sub", "superscript": "sup"} def __init__(self, master, buttons=("interpret", "asis"), **kw): Frame.__init__(self, master, **kw) self.text = "" self.interpret = 1 self.editPool = Entry(self, width=50, state="disabled", font="Helvetica 12") self.editPool.pack(side="left") self.editPool.bind("<Return>", self._interpretButtonPressed) self.editPool.bind("<Escape>", self._cancel) self.editPool.bind("<Control-s>", lambda e: self._tag_it("sub")) self.editPool.bind("<Control-S>", lambda e: self._tag_it("sup")) self.editPool.bind("<Control-i>", lambda e: self._tag_it("i")) self.editPool.bind("<Control-b>", lambda e: self._tag_it("b")) self.editPool.bind("<KeyPress>", self._key) if "interpret" in buttons: pix = Store.app.request("pixmap", name="interpret") self.interpretButton = Button( self, text=_("Interpret"), image=pix, command=self._interpretButtonPressed, state="disabled", bd=config.border_width, ) Store.app.balloon.bind(self.interpretButton, _("Interpret text (where applicable)")) self.interpretButton.pack(side="left") else: self.interpretButton = None if "asis" in buttons: pix = Store.app.request("pixmap", name="asis") self.setButton = Button( self, image=pix, text=_("As is"), command=self._setButtonPressed, state="disabled", bd=config.border_width, ) Store.app.balloon.bind(self.setButton, _("Leave text as is - do not interpret")) self.setButton.pack(side="left") else: self.setButton = None pix = Store.app.request("pixmap", name="subnum") self.numbersToSubButton = Button( self, image=pix, text=_("Sub numbers"), command=self._numbersToSubButtonPressed, state="disabled", bd=config.border_width, ) Store.app.balloon.bind(self.numbersToSubButton, _("Convert numbers to subscript")) self.numbersToSubButton.pack(side="left") # text decoration decorFrame = Frame(self) decorFrame.pack(padx=5, side="left") for i in self.font_decorations: pix = Store.app.request("pixmap", name=i) self.__dict__[i] = Button( self, image=pix, command=misc.lazy_apply(self._tag_it, (self.font_decorations_to_html[i],)), state="disabled", text=self.font_decorations_to_names[i], bd=config.border_width, ) Store.app.balloon.bind(self.__dict__[i], self.font_decorations_to_names[i]) self.__dict__[i].pack(side="left") # special characters pix = Store.app.request("pixmap", name="specialchar") self.specialCharButton = Button( self, image=pix, text=_("Special Character"), command=self._specialCharButtonPressed, state="disabled", bd=config.border_width, ) Store.app.balloon.bind(self.specialCharButton, _("Insert a special character")) self.specialCharButton.pack(side="left") self.active = False def _interpretButtonPressed(self, *e): t = self.editPool.get() if string.lower(t) in groups_table: self._setText(t) # self._setText( groups_table[ string.lower(t)]['text']) # self.editPool.insert(0, self.text) else: self._setText(t) self.text = re.sub("\\\\n", "\n", self.text) self._quit() def _setButtonPressed(self, *e): self._setText(self.editPool.get()) self.interpret = 0 self._quit() def _numbersToSubButtonPressed(self, *e): self._setText(re.sub("\d+", "<sub>\g<0></sub>", self.editPool.get())) self._quit() def _cancel(self, e): self._setText(None) self.active = False self._quit() def _quit(self): self.grab_release() self._disable() self._normaly_terminated = 1 self.active = False self.quit() def _disable(self): self.interpretButton.configure(state="disabled") self.numbersToSubButton.configure(state="disabled") self.setButton.configure(state="disabled") self.editPool.configure(state="disabled") self.italic.configure(state="disabled") self.bold.configure(state="disabled") self.superscript.configure(state="disabled") self.subscript.configure(state="disabled") self.specialCharButton.configure(state="disabled") def _enable(self): self.interpretButton.configure(state="normal") self.numbersToSubButton.configure(state="normal") self.setButton.configure(state="normal") self.editPool.configure(state="normal") self.italic.configure(state="normal") self.bold.configure(state="normal") self.superscript.configure(state="normal") self.subscript.configure(state="normal") self.specialCharButton.configure(state="normal") def _setText(self, text): self.text = text self._update() def _update(self): self.editPool.delete(0, last="end") if self.text: self.editPool.insert(0, self.text) def activate(self, text=None, select=1): """activates edit_pool and returns inserted value (None if cancel occured), if parameter text is None it preserves the old one, use text='' to delete old text""" self.active = True self.interpret = 1 self.focus_set() self.grab_set() self._enable() # this is because I need to distinguish whether the mainloop was terminated "from inside" # or from outside (this most of the time means the application was killed and the widgets are no longer available) self._normaly_terminated = 0 if text != None: self._setText(text) self.editPool.focus_set() if select: self.editPool.selection_range(0, "end") self.mainloop() if self._normaly_terminated: return self.text else: return None def _tag_it(self, tag): if self.editPool.selection_present(): self.editPool.insert(Tkinter.SEL_FIRST, "<%s>" % tag) self.editPool.insert(Tkinter.SEL_LAST, "</%s>" % tag) else: self.editPool.insert(Tkinter.INSERT, "<%s></%s>" % (tag, tag)) self.editPool.icursor(self.editPool.index(Tkinter.INSERT) - len(tag) - 3) def _key(self, event): if len(event.keysym) > 1 and event.keysym in keysyms: if self.editPool.selection_present(): self.editPool.delete("anchor", "insert") self.editPool.insert("insert", unicode(keysyms[event.keysym])) return "break" def _specialCharButtonPressed(self): dialog = special_character_menu(self._insertText) dialog.post(self.specialCharButton.winfo_rootx(), self.specialCharButton.winfo_rooty()) def _insertText(self, text): if text != None: self.editPool.insert(Tkinter.INSERT, text) self.grab_set()
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)
# -- Build UI -- # Create window window = Tkinter.Tk() window.minsize(200, 250) window.title("BLE Scanner") # Create time label timeLabel = Label(text='Enter scan duration:') timeLabel.pack() # Create time entry box e = Entry(window) e.pack() e.focus_set() # Create start button startButton = Button(window, text='Start Scanning', command=lambda: startScan()) startButton.config(height=2, width=20) startButton.pack() # Create stop button stopButton = Button(window, text='Stop Scanning', command=lambda: stopScan()) stopButton.config(height=2, width=20) stopButton.pack() # Create time label graphLabel = Label(text='Enter log file to graph:')
class editPool(Frame): font_decorations = ('italic', 'bold', 'subscript', 'superscript') font_decorations_to_names = { 'italic': _('italic'), 'bold': _('bold'), 'subscript': _('subscript'), 'superscript': _('superscript') } font_decorations_to_html = { 'italic': 'i', 'bold': 'b', 'subscript': 'sub', 'superscript': 'sup' } def __init__(self, master, buttons=('interpret', 'asis'), **kw): Frame.__init__(self, master, **kw) self.text = '' self.interpret = 1 self.editPool = Entry(self, width=50, state='disabled', font="Helvetica 12") self.editPool.pack(side='left') self.editPool.bind('<Return>', self._interpretButtonPressed) self.editPool.bind('<Escape>', self._cancel) self.editPool.bind('<Control-s>', lambda e: self._tag_it("sub")) self.editPool.bind('<Control-S>', lambda e: self._tag_it("sup")) self.editPool.bind('<Control-i>', lambda e: self._tag_it("i")) self.editPool.bind('<Control-b>', lambda e: self._tag_it("b")) self.editPool.bind("<KeyPress>", self._key) if 'interpret' in buttons: pix = Store.app.request('pixmap', name='interpret') self.interpretButton = Button(self, text=_('Interpret'), image=pix, command=self._interpretButtonPressed, state='disabled', bd=config.border_width) Store.app.balloon.bind(self.interpretButton, _('Interpret text (where applicable)')) self.interpretButton.pack(side='left') else: self.interpretButton = None if 'asis' in buttons: pix = Store.app.request('pixmap', name='asis') self.setButton = Button(self, image=pix, text=_('As is'), command=self._setButtonPressed, state='disabled', bd=config.border_width) Store.app.balloon.bind(self.setButton, _('Leave text as is - do not interpret')) self.setButton.pack(side='left') else: self.setButton = None pix = Store.app.request('pixmap', name='subnum') self.numbersToSubButton = Button( self, image=pix, text=_('Sub numbers'), command=self._numbersToSubButtonPressed, state='disabled', bd=config.border_width) Store.app.balloon.bind(self.numbersToSubButton, _('Convert numbers to subscript')) self.numbersToSubButton.pack(side='left') # text decoration decorFrame = Frame(self) decorFrame.pack(padx=5, side="left") for i in self.font_decorations: pix = Store.app.request('pixmap', name=i) self.__dict__[i] = Button( self, image=pix, command=misc.lazy_apply(self._tag_it, (self.font_decorations_to_html[i], )), state='disabled', text=self.font_decorations_to_names[i], bd=config.border_width) Store.app.balloon.bind(self.__dict__[i], self.font_decorations_to_names[i]) self.__dict__[i].pack(side="left") # special characters pix = Store.app.request('pixmap', name='specialchar') self.specialCharButton = Button(self, image=pix, text=_('Special Character'), command=self._specialCharButtonPressed, state='disabled', bd=config.border_width) Store.app.balloon.bind(self.specialCharButton, _('Insert a special character')) self.specialCharButton.pack(side='left') self.active = False def _interpretButtonPressed(self, *e): t = self.editPool.get() if string.lower(t) in groups_table: self._setText(t) #self._setText( groups_table[ string.lower(t)]['text']) #self.editPool.insert(0, self.text) else: self._setText(t) self.text = re.sub("\\\\n", "\n", self.text) self._quit() def _setButtonPressed(self, *e): self._setText(self.editPool.get()) self.interpret = 0 self._quit() def _numbersToSubButtonPressed(self, *e): self._setText(re.sub("\d+", '<sub>\g<0></sub>', self.editPool.get())) self._quit() def _cancel(self, e): self._setText(None) self.active = False self._quit() def _quit(self): self.grab_release() self._disable() self._normaly_terminated = 1 self.active = False self.quit() def _disable(self): self.interpretButton.configure(state='disabled') self.numbersToSubButton.configure(state='disabled') self.setButton.configure(state='disabled') self.editPool.configure(state='disabled') self.italic.configure(state='disabled') self.bold.configure(state='disabled') self.superscript.configure(state='disabled') self.subscript.configure(state='disabled') self.specialCharButton.configure(state='disabled') def _enable(self): self.interpretButton.configure(state='normal') self.numbersToSubButton.configure(state='normal') self.setButton.configure(state='normal') self.editPool.configure(state='normal') self.italic.configure(state='normal') self.bold.configure(state='normal') self.superscript.configure(state='normal') self.subscript.configure(state='normal') self.specialCharButton.configure(state='normal') def _setText(self, text): self.text = text self._update() def _update(self): self.editPool.delete(0, last='end') if self.text: self.editPool.insert(0, self.text) def activate(self, text=None, select=1): """activates edit_pool and returns inserted value (None if cancel occured), if parameter text is None it preserves the old one, use text='' to delete old text""" self.active = True self.interpret = 1 self.focus_set() self.grab_set() self._enable() # this is because I need to distinguish whether the mainloop was terminated "from inside" # or from outside (this most of the time means the application was killed and the widgets are no longer available) self._normaly_terminated = 0 if text != None: self._setText(text) self.editPool.focus_set() if select: self.editPool.selection_range(0, 'end') self.mainloop() if self._normaly_terminated: return self.text else: return None def _tag_it(self, tag): if self.editPool.selection_present(): self.editPool.insert(Tkinter.SEL_FIRST, '<%s>' % tag) self.editPool.insert(Tkinter.SEL_LAST, '</%s>' % tag) else: self.editPool.insert(Tkinter.INSERT, '<%s></%s>' % (tag, tag)) self.editPool.icursor( self.editPool.index(Tkinter.INSERT) - len(tag) - 3) def _key(self, event): if len(event.keysym) > 1 and event.keysym in keysyms: if self.editPool.selection_present(): self.editPool.delete("anchor", "insert") self.editPool.insert('insert', unicode(keysyms[event.keysym])) return "break" def _specialCharButtonPressed(self): dialog = special_character_menu(self._insertText) dialog.post(self.specialCharButton.winfo_rootx(), self.specialCharButton.winfo_rooty()) def _insertText(self, text): if text != None: self.editPool.insert(Tkinter.INSERT, text) self.grab_set()
class TreeNode: def __init__(self, canvas, parent, item, menuList = []): self.canvas = canvas self.parent = parent self.item = item self.state = 'collapsed' self.selected = 0 self.children = {} self.kidKeys = [] self.x = self.y = None self.iconimages = {} # cache of PhotoImage instances for icons self.menuList = menuList self.menuVar = IntVar() self.menuVar.set(0) self._popupMenu = None self.image_id = None if self.menuList: if self.menuList[-1] == 'Separator': self.menuList = self.menuList[:-1] self._popupMenu = Menu(self.canvas, tearoff = 0) for i in range(len(self.menuList)): item = self.menuList[i] if item == 'Separator': self._popupMenu.add_separator() else: self._popupMenu.add_radiobutton( label = item, variable = self.menuVar, value = i, indicatoron = 0, command = self.popupMenuCommand) def destroy(self): for key in self.kidKeys: c = self.children[key] del self.children[key] c.destroy() self.parent = None def geticonimage(self, name): try: return self.iconimages[name] except KeyError: pass file, ext = os.path.splitext(name) ext = ext or ".gif" fullname = os.path.join(ICONDIR, file + ext) image = PhotoImage(master=self.canvas, file=fullname) self.iconimages[name] = image return image def select(self, event=None): if self.selected: return self.deselectall() self.selected = 1 if self.parent != None: if self.parent.state == 'expanded': self.canvas.delete(self.image_id) self.drawicon() self.drawtext() self.item.OnSelect(event) def deselect(self, event=None): if not self.selected: return self.selected = 0 if self.parent != None: if self.parent.state == 'expanded': self.canvas.delete(self.image_id) self.drawicon() self.drawtext() def deselectall(self): if self.parent: self.parent.deselectall() else: self.deselecttree() def deselecttree(self): if self.selected: self.deselect() for key in self.kidKeys: child = self.children[key] child.deselecttree() def flip(self, event=None): if self.state == 'expanded': self.collapse() else: self.expand() self.item.OnDoubleClick() return "break" def popupMenu(self, event=None): if self._popupMenu: self._popupMenu.post(event.widget.winfo_pointerx(), event.widget.winfo_pointery()) return "break" def popupMenuCommand(self): command = self.menuList[self.menuVar.get()] self.item.MenuCommand(command) if self.parent and (command != 'Update Explorer'): # Update parent to try to keep explorer up to date self.parent.update() def expand(self, event=None): if not self.item.IsExpandable(): return if self.state != 'expanded': self.state = 'expanded' self.update() self.view() def collapse(self, event=None): if self.state != 'collapsed': self.state = 'collapsed' self.update() def view(self): top = self.y - 2 bottom = self.lastvisiblechild().y + 17 height = bottom - top visible_top = self.canvas.canvasy(0) visible_height = self.canvas.winfo_height() visible_bottom = self.canvas.canvasy(visible_height) if visible_top <= top and bottom <= visible_bottom: return x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion']) if top >= visible_top and height <= visible_height: fraction = top + height - visible_height else: fraction = top fraction = float(fraction) / y1 self.canvas.yview_moveto(fraction) def reveal(self): # Make sure all parent nodes are marked as expanded parent = self.parent while parent: if parent.state == 'collapsed': parent.state = 'expanded' parent = parent.parent else: break # Redraw tree accordingly self.update() # Bring this item into view self.view() def lastvisiblechild(self): if self.kidKeys and self.state == 'expanded': return self.children[self.kidKeys[-1]].lastvisiblechild() else: return self def update(self): if self.parent: self.parent.update() else: oldcursor = self.canvas['cursor'] self.canvas['cursor'] = "watch" self.canvas.update() self.canvas.delete(Tkinter.ALL) # XXX could be more subtle self.draw(7, 2) x0, y0, x1, y1 = self.canvas.bbox(Tkinter.ALL) self.canvas.configure(scrollregion=(0, 0, x1, y1)) self.canvas['cursor'] = oldcursor def draw(self, x, y): # XXX This hard-codes too many geometry constants! self.x, self.y = x, y self.drawicon() self.drawtext() if self.state != 'expanded': return y+17 # draw children sublist = self.item._GetSubList() if not sublist: # IsExpandable() was mistaken; that's allowed return y+17 self.kidKeys = [] for item in sublist: key = item.GetKey() if self.children.has_key(key): child = self.children[key] else: child = TreeNode(self.canvas, self, item, self.menuList) self.children[key] = child self.kidKeys.append(key) # Remove unused children for key in self.children.keys(): if key not in self.kidKeys: del(self.children[key]) cx = x+20 cy = y+17 cylast = 0 for key in self.kidKeys: child = self.children[key] cylast = cy self.canvas.create_line(x+9, cy+7, cx, cy+7, fill="gray50") cy = child.draw(cx, cy) if child.item.IsExpandable(): if child.state == 'expanded': iconname = "minusnode" callback = child.collapse else: iconname = "plusnode" callback = child.expand image = self.geticonimage(iconname) id = self.canvas.create_image(x+9, cylast+7, image=image) # XXX This leaks bindings until canvas is deleted: self.canvas.tag_bind(id, "<1>", callback) self.canvas.tag_bind(id, "<Double-1>", lambda x: None) id = self.canvas.create_line(x+9, y+10, x+9, cylast+7, ##stipple="gray50", # XXX Seems broken in Tk 8.0.x fill="gray50") self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2 return cy def drawicon(self): if self.selected: imagename = (self.item.GetSelectedIconName() or self.item.GetIconName() or "openfolder") else: imagename = self.item.GetIconName() or "folder" image = self.geticonimage(imagename) id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image) self.image_id = id self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) self.canvas.tag_bind(id, "<3>", self.popupMenu) def drawtext(self, text=None): textx = self.x+20-1 texty = self.y-1 labeltext = self.item.GetLabelText() if labeltext: id = self.canvas.create_text(textx, texty, anchor="nw", text=labeltext) self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) x0, y0, x1, y1 = self.canvas.bbox(id) textx = max(x1, 200) + 10 if text==None: text = self.item.GetText() or "<no text>" try: self.entry except AttributeError: pass else: self.edit_finish() try: label = self.label except AttributeError: # padding carefully selected (on Windows) to match Entry widget: self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2) if self.selected: self.label.configure(fg="white", bg="darkblue") else: fg = self.item.GetTextFg() self.label.configure(fg=fg, bg="white") id = self.canvas.create_window(textx, texty, anchor="nw", window=self.label) self.label.bind("<1>", self.select_or_edit) self.label.bind("<Double-1>", self.flip) self.label.bind("<3>", self.popupMenu) # Update text if necessary if text != self.label['text']: self.label['text'] = text self.text_id = id def select_or_edit(self, event=None): if self.selected and self.item.IsEditable(): text = self.item.GetTextForEdit() self.label['text'] = text self.drawtext(text) self.edit(event) else: self.select(event) def edit(self, event=None): self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0) self.entry.insert(0, self.label['text']) self.entry.selection_range(0, Tkinter.END) self.entry.pack(ipadx=5) self.entry.focus_set() self.entry.bind("<Return>", self.edit_finish) self.entry.bind("<Escape>", self.edit_cancel) def edit_finish(self, event=None): try: entry = self.entry del self.entry except AttributeError: return text = entry.get() entry.destroy() if text and text != self.item.GetText(): self.item.SetText(text) text = self.item.GetText() self.label['text'] = text self.drawtext() self.canvas.focus_set() def edit_cancel(self, event=None): self.drawtext() self.canvas.focus_set() def find(self, searchKey): # Search for a node who's key matches the given key # Is it this node if searchKey == self.item.GetKey(): return self # Nope, check the children sublist = self.item._GetSubList() for item in sublist: key = item.GetKey() # Use existing child or create new TreeNode if none exists if self.children.has_key(key): child = self.children[key] else: child = TreeNode(self.canvas, self, item, self.menuList) # Update local list of children and keys self.children[key] = child self.kidKeys.append(key) # See if node is child (or one of child's descendants) retVal = child.find(searchKey) if retVal: return retVal # Not here return None
class SPIFrame(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initialize() def initialize(self): self.grid() self.entryVariable = StringVar() self.entry = Entry(self, textvariable=self.entryVariable) self.entry.grid(column=0,row=0,sticky='EW') self.entry.bind("<Return>", self.OnPressEnter) button = Button(self,text="SPI send", command=self.OnButtonClick) button.grid(column=1,row=0) #ramp = Button(self,text="RAMP", command=self.setlabvar) #ramp.grid(column=1,row=1) self.labelVariable = StringVar() label = Label(self,textvariable=self.labelVariable, anchor="w",fg="white",bg="blue") label.grid(column=0,row=1,columnspan=1,sticky='EW') self.labelVariable.set("Start..") self.slider = Scale(self, from_=0, to=80, orient=HORIZONTAL, command=self.setlabvar) self.slider.grid(column=0, row=2, columnspan=3, sticky='EW') self.PID = PIDTune(self) self.PID.grid(column=0, row=3, columnspan=3, sticky='EW') self.grid_columnconfigure(0,weight=1) self.update() #self.geometry(self.geometry()) # caused busy wait? self.entry.focus_set() #self.entry.selection_range(0, Tkinter.END) # caused busy wait? def setlabvar(self, val): val = self.slider.get() speed.SetAcceleration(val) accel = val; self.labelVariable.set("Duty set: " + str(val) ) def OnButtonClick(self): accel = int(self.entryVariable.get()) self.slider.set(accel) speed.SetAcceleration(accel) self.labelVariable.set("Duty set: " + str(accel) ) self.entry.focus_set() self.entry.selection_range(0, END) def OnPressEnter(self,event): accel = int(self.entryVariable.get()) self.slider.set(accel) speed.SetAcceleration(accel) self.labelVariable.set("Duty set: " + str(accel) ) self.entry.focus_set() self.entry.selection_range(0, END)
class GetHelpSourceDialog(Toplevel): def __init__(self, parent, title, menuItem='', filePath='', _htest=False): """Get menu entry and url/ local file location for Additional Help User selects a name for the Help resource and provides a web url or a local file as its source. The user can enter a url or browse for the file. _htest - bool, change box location when running htest """ Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.resizable(height=FALSE, width=FALSE) self.title(title) self.transient(parent) self.grab_set() self.protocol("WM_DELETE_WINDOW", self.Cancel) self.parent = parent self.result = None self.CreateWidgets() self.menu.set(menuItem) self.path.set(filePath) self.withdraw() #hide while setting geometry #needs to be done here so that the winfo_reqwidth is valid self.update_idletasks() #centre dialog over parent. below parent if running htest. self.geometry("+%d+%d" % (parent.winfo_rootx() + (parent.winfo_width() / 2 - self.winfo_reqwidth() / 2), parent.winfo_rooty() + ((parent.winfo_height() / 2 - self.winfo_reqheight() / 2) if not _htest else 150))) self.deiconify() #geometry set, unhide self.bind('<Return>', self.Ok) self.wait_window() def CreateWidgets(self): self.menu = StringVar(self) self.path = StringVar(self) self.fontSize = StringVar(self) self.frameMain = Frame(self, borderwidth=2, relief=GROOVE) self.frameMain.pack(side=TOP, expand=TRUE, fill=BOTH) labelMenu = Label(self.frameMain, anchor=W, justify=LEFT, text='Menu Item:') self.entryMenu = Entry(self.frameMain, textvariable=self.menu, width=30) self.entryMenu.focus_set() labelPath = Label(self.frameMain, anchor=W, justify=LEFT, text='Help File Path: Enter URL or browse for file') self.entryPath = Entry(self.frameMain, textvariable=self.path, width=40) self.entryMenu.focus_set() labelMenu.pack(anchor=W, padx=5, pady=3) self.entryMenu.pack(anchor=W, padx=5, pady=3) labelPath.pack(anchor=W, padx=5, pady=3) self.entryPath.pack(anchor=W, padx=5, pady=3) browseButton = Button(self.frameMain, text='Browse', width=8, command=self.browseFile) browseButton.pack(pady=3) frameButtons = Frame(self) frameButtons.pack(side=BOTTOM, fill=X) self.buttonOk = Button(frameButtons, text='OK', width=8, default=ACTIVE, command=self.Ok) self.buttonOk.grid(row=0, column=0, padx=5, pady=5) self.buttonCancel = Button(frameButtons, text='Cancel', width=8, command=self.Cancel) self.buttonCancel.grid(row=0, column=1, padx=5, pady=5) def browseFile(self): filetypes = [("HTML Files", "*.htm *.html", "TEXT"), ("PDF Files", "*.pdf", "TEXT"), ("Windows Help Files", "*.chm"), ("Text Files", "*.txt", "TEXT"), ("All Files", "*")] path = self.path.get() if path: dir, base = os.path.split(path) else: base = None if sys.platform[:3] == 'win': dir = os.path.join(os.path.dirname(sys.executable), 'Doc') if not os.path.isdir(dir): dir = os.getcwd() else: dir = os.getcwd() opendialog = tkFileDialog.Open(parent=self, filetypes=filetypes) file = opendialog.show(initialdir=dir, initialfile=base) if file: self.path.set(file) def MenuOk(self): "Simple validity check for a sensible menu item name" menuOk = True menu = self.menu.get() menu.strip() if not menu: tkMessageBox.showerror(title='Menu Item Error', message='No menu item specified', parent=self) self.entryMenu.focus_set() menuOk = False elif len(menu) > 30: tkMessageBox.showerror(title='Menu Item Error', message='Menu item too long:' '\nLimit 30 characters.', parent=self) self.entryMenu.focus_set() menuOk = False return menuOk def PathOk(self): "Simple validity check for menu file path" pathOk = True path = self.path.get() path.strip() if not path: #no path specified tkMessageBox.showerror(title='File Path Error', message='No help file path specified.', parent=self) self.entryPath.focus_set() pathOk = False elif path.startswith(('www.', 'http')): pass else: if path[:5] == 'file:': path = path[5:] if not os.path.exists(path): tkMessageBox.showerror( title='File Path Error', message='Help file path does not exist.', parent=self) self.entryPath.focus_set() pathOk = False return pathOk def Ok(self, event=None): if self.MenuOk() and self.PathOk(): self.result = (self.menu.get().strip(), self.path.get().strip()) if sys.platform == 'darwin': path = self.result[1] if path.startswith(('www', 'file:', 'http:')): pass else: # Mac Safari insists on using the URI form for local files self.result = list(self.result) self.result[1] = "file://" + path self.destroy() def Cancel(self, event=None): self.result = None self.destroy()
class Application(Frame): MAXWORDLEN = 20 DEFAULTWORDLEN = 3 MANDATORY1stCHAR=0 def __init__(self, master=None): Frame.__init__(self, master, padx=3, pady=3) self.dictionaryfile = None self.menubar = Menu() self.__createWidgets() self.menubar.add_cascade(label='File', menu=self.__File) self.menubar.add_cascade(label='Options', menu=self.__Options) self.menubar.add_command(label='About', command=self.__about) self.__params.grid(row=0, column=0, sticky=W) self.__res_pane = Frame() self.__res_pane.grid(row=2, column=0, sticky=E + W) self.__status = Label(anchor=W, relief=SUNKEN) self.__status.grid(row=3, column=0, sticky=E + W) self.osDictFile() self.matchobj = None if self.dictionaryfile is None: self.status('No dictionary defined!') master.config(menu=self.menubar) def __createWidgets(self): self.__params = Frame(padx=5, pady=5) Label(text='Letters: ', anchor=E).grid(row=0, column=0, sticky=E, in_=self.__params) self.__char_entry = Entry(width=10) self.__chk1st = Checkbutton(variable=self.MANDATORY1stCHAR, command=self.__CB) Label(text='First letter appears in every result ', anchor=W).grid( row=0, column=4, sticky=E, in_=self.__params) self.__char_entry.grid(row=0, column=1, columnspan=2, sticky=W, in_=self.__params) self.__chk1st.grid(row=0, column=3, sticky=W, in_=self.__params) Label(text='Minimum length of result words: ', anchor=E).grid( row=1, column=0, sticky=E, in_=self.__params) self.__word_length_ctrl = Spinbox(from_=1, to=Application.MAXWORDLEN, width=2) self.__word_length_ctrl.delete(0, END) self.__word_length_ctrl.insert(0, Application. DEFAULTWORDLEN) self.__word_length_ctrl.grid(row=1, column=1, in_=self.__params, sticky=W) self.__go_button = Button(text='Go', command=self.__findWords) self.__go_button.grid(row=1, column=2, sticky=E, in_=self.__params) self.__Options = Menu() self.__Options.add_command(label='Choose dictionary', command=self.__choosedict) self.__File = Menu() self.__File.add_command(label='Export as ODT (Open document text)', command=self.__export) self.__char_entry.focus_set() self.__char_entry.bind("<Return>", self.__keyPressEnter) def __CB(self): self.MANDATORY1stCHAR = not self.MANDATORY1stCHAR def __choosedict(self): try: self.dictionaryfile = tkFileDialog.askopenfile(mode='r').name self.status('') except AttributeError: pass def osDictFile(self): if 'linux' in sys.platform: self.dictionaryfile = '/usr/share/dict/words' def __about(self): AboutDialog(self) def status(self, text): self.__status.config(text=text) self.__status.update_idletasks() def __findWords(self): self.__res_pane.grid_forget() chars = self.__char_entry.get() minlen = int(self.__word_length_ctrl.get()) if len(chars) < minlen: tkMessageBox.showerror(title='Not enough letters', message='''Not enough letters given\n You must give at least as many letters as the minimum required word length''') return res = self.__getres(minlen, chars) self.__res_pane = ResultPane(res) self.__res_pane.grid(row=2, column=0, sticky=E + W) def __getres(self, minlen, chars): firstpass = True while True: try: self.matchobj = None if firstpass and self.dictionaryfile is None: self.matchobj = Match(minlen=minlen, chars=chars, statushandler=self.status, mand1st=self.MANDATORY1stCHAR) firstpass = False else: self.matchobj = Match(minlen=minlen, chars=chars, dict=self.dictionaryfile, statushandler=self.status, mand1st=self.MANDATORY1stCHAR) res = self.matchobj.wordMatch() return res except IOError: ans = tkMessageBox.askyesno(title='No Dictionary', message='''No dictionary file was found, would you like to choose a dictionary file? (No) aborts the application''') if ans: self.__choosedict() else: sys.exit() def __keyPressEnter(self, event): self.__findWords() def __export(self): options= {} options['defaultextension'] = '.odt' options['filetypes'] = [('all files', '.*'), ('Open Document Text', '.odt')] options['initialdir'] = expanduser('~') options['initialfile'] = self.__char_entry.get() f = asksaveasfilename(**options) outfile = Doc(self.matchobj) outfile.write(unicode(f, "utf-8"))
class HomunculusRecording(Homunculus): def get_row(self, cut_off=0): result = self.grid_row - cut_off self.grid_row += 1 return result def __init__(self, params): self.grid_row = 0 Homunculus.__init__(self, params[0]) self.title(settings.HOMUNCULUS_VERSION + settings.HMC_TITLE_RECORDING) self.geometry("640x480+" + str(int(self.winfo_screenwidth() / 2 - 320)) + "+" + str(int(self.winfo_screenheight() / 2 - 240))) self.instructions = "Macro Recording Options" Label(self, text=self.instructions, name="pathlabel").grid(row=self.get_row(), column=1, sticky=tk.E) wf_row = self.get_row() Label(self, text="Command Words:", name="wordlabel").grid(row=wf_row, column=0, sticky=tk.W) self.word_box = Entry(self, name="word_box") self.word_box.grid(row=wf_row, column=1, sticky=tk.W) self.repeatable = tk.IntVar() Checkbutton(self, text="Make Repeatable", variable=self.repeatable).grid(row=self.get_row(), column=0, sticky=tk.W) Label(self, text="Dictation History", name="optionslabel").grid(row=self.get_row(), column=1, sticky=tk.E) self.word_state = [] cb_number = 1 sentences = params[1].split("[s]") sentences.pop() for sentence in sentences: sentence_words = sentence.split("[w]") sentence_words.pop() display_sentence = " ".join(sentence_words) cb_row = 0 # self.get_row() cb_col = 0 row_cut_off = 14 col2_inc = -1 word_state_var = tk.IntVar() if cb_number == 1: word_state_var.set(True) if cb_number < row_cut_off: cb_row = cb_row = self.get_row() else: cb_row = cb_row = self.get_row(row_cut_off + col2_inc) cb_col = 2 col2_inc += 1 Checkbutton(self, text="(" + str(cb_number) + ")", variable=word_state_var).grid(row=cb_row, column=cb_col + 1, sticky=tk.W) self.word_state.append((word_state_var, cb_number)) cb_number += 1 Label(self, text=display_sentence, name="cb_label" + str(cb_number)).grid(row=cb_row, column=cb_col, sticky=tk.W) self.cb_max = cb_number def xmlrpc_get_message(self): if self.completed: response = {"mode": "recording"} word = self.word_box.get() if len(word) == 0: self.xmlrpc_kill() response["word"] = word response["repeatable"] = self.repeatable.get() selected_indices = [] for ws in self.word_state: if ws[0].get() == 1: selected_indices.append(ws[1] - 1) response["selected_indices"] = selected_indices Timer(1, self.xmlrpc_kill).start() self.after(10, self.withdraw) return response else: return None def check_boxes(self, details): for box_index in details: if box_index >= 1 and box_index <= self.cb_max: self.word_state[box_index - 1][0].set( self.word_state[box_index - 1][0].get() == 0) def check_range_of_boxes(self, details): box_index_from = details[0] - 1 box_index_to = details[1] - 1 for i in range(0, self.cb_max): if i <= self.cb_max: self.word_state[i][0].set(i >= box_index_from and i <= box_index_to) def xmlrpc_do_action(self, action, details=None): '''acceptable keys are numbers and w and p''' if action == "check": self.check_boxes(details) elif action == "focus": if details == "word": self.word_box.focus_set() elif action == "check_range": self.check_range_of_boxes(details) elif action == "exclude": box_index = details if box_index >= 1 and box_index <= self.cb_max: self.word_state[box_index - 1][0].set(False) elif action == "repeatable": self.repeatable.set(not self.repeatable.get())
class Studio(Frame): """The Studio class is a GUI for the digital library.""" _meter = None _grid = None _dual_box = None _auto_queue = None _entry = None _search_results = None _selected_cart = None def __init__(self): """Construct a Studio window.""" Frame.__init__(self) # make the window resizable top = self.master.winfo_toplevel() for row in range(2, GRID_ROWS + 2): for col in range(0, GRID_COLS): top.rowconfigure(row, weight=1) top.columnconfigure(col, weight=1) self.rowconfigure(row, weight=1) self.columnconfigure(col, weight=1) # initialize the title title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE) title.grid(row=0, column=0, columnspan=GRID_COLS) # initialize the meter self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data) self._meter.grid(row=1, column=0, columnspan=GRID_COLS) # initialize the cart grid self._grid = Grid(self, GRID_ROWS, GRID_COLS, True, self._cart_start, self._cart_stop, self._cart_end, self.add_cart) # initialize the dual box self._dual_box = DualBox(self) self._dual_box.grid(row=GRID_ROWS + 2, column=0, columnspan=4) # intialize the auto-queue control self._auto_queue = BooleanVar() self._auto_queue.set(False) control = Frame(self.master, bd=2, relief=Tkinter.SUNKEN) Checkbutton(control, text=TEXT_AUTOSLOT, variable=self._auto_queue, onvalue=True, offvalue=False).pack(anchor=Tkinter.NW) control.grid(row=GRID_ROWS + 2, column=4, columnspan=GRID_COLS - 4) # initialize the search box, button Label(control, font=FONT, text=TEXT_SEARCHBOX).pack(anchor=Tkinter.NW) self._entry = Entry(control, takefocus=True, width=45) self._entry.bind("<Return>", self.search) # self._entry.grid(row=GRID_ROWS + 3, column=0, columnspan=5) self._entry.pack(anchor=Tkinter.NW) self._entry.focus_set() button = Button(control, text=TEXT_SEARCH, command=self.search) # button.grid(row=GRID_ROWS + 3, column=5) button.pack(anchor=Tkinter.S) # begin the event loop self.master.protocol("WM_DELETE_WINDOW", self.master.destroy) self.master.title(TEXT_TITLE) self.master.mainloop() def _search_internal(self): """Search the digital library in a separate thread.""" query = self._entry.get() if len(query) >= 3: print "Searching library with query \"%s\"..." % query self._search_results = database.search_library(query) self._dual_box.fill(self._search_results) print "Found %d results." % len(self._search_results) def search(self, *args): """Search the digital library. :param args """ thread.start_new_thread(self._search_internal, ()) def select_cart(self, index): """Select a cart from the search results. :param index: index of cart in search results """ if index is not None: self._selected_cart = self._search_results[index] def add_cart(self, key): """Add the selected cart to the grid. :param key """ if not self._grid.has_cart(key) and self._selected_cart is not None: self._grid.set_cart(key, self._selected_cart) def _cart_start(self): """Start the meter when a cart starts.""" self._meter.start() def _cart_stop(self): """Reset the meter when a cart stops.""" self._meter.reset() def _cart_end(self, key): """Reset the meter when a cart ends. Also, if auto-queue is enabled, queue the next cart. :param key """ self._meter.reset() if self._auto_queue.get(): next_key = get_next_key(GRID_ROWS, GRID_COLS, key) if self._grid.has_cart(next_key): self._grid.start(next_key) def _get_meter_data(self): """Get meter data for the currently active cart.""" return self._grid.get_active_cell().get_cart().get_meter_data()
class MyPoti(Tkinter.Tk): def __init__(self, master): Tkinter.Tk.__init__(self,master) self.master = master self.initialize() def initialize(self): #create canvas with specified size and add w = Canvas(self, width=700, height=600) w.pack() #Declare two lists, one for front labels, anthoer for answer labels self.flabels = [] self.alabels = [] #Define x and y cordinates for lables self.flblx = 280 self.flbly = 40 self.alblx = 380 self.albly = 40 #Dummy list1 self.my_list = [] #Text to set on front lables self.str_label = ['POTI0', 'POTI1','POTI2','POTI3','POTI4'] #Trigger to check if we want to program or pause self.running = True #Define environment varibales for input text fields #We can change/update this during runtime self.entry_pot_var = Tkinter.StringVar() self.entry_res_var = Tkinter.StringVar() #Define text areas for input onr for poti selection and one for resistence value self.entry_pot = Entry(self,textvariable=self.entry_pot_var, validate="focusout") self.entry_res = Entry(self,textvariable=self.entry_res_var, validate="focusout") #Initial text to display on above text fields self.entry_pot_var.set("Enter Pot selection") self.entry_res_var.set("Enter resistor value - 2000 to 100000") #Set pot selection entry as highlighted self.entry_pot.selection_range(0,Tkinter.END) #self.entry_res.selection_range(0,Tkinter.END) #Set keyboard focus on pot text field self.entry_pot.focus_set() #Add pot text field to canvas self.entry_pot.pack() #ToDO #validate input for pot selection #self.entry_pot["validatecommand"] = (self.register(self.check_pot), "%P") #Add resistence text field to canvas self.entry_res.pack() #Create two text on the canvas with x and y coodrinates w.create_window(120, 40, window=self.entry_pot) w.create_window(120, 70,window=self.entry_res) #We declare 5 front lables and add them to canvas with x and y co ordinates for x in range(5): print self.str_label[x] self.label = Label(self, text=self.str_label[x], fg='white', bg='black') self.label.pack() self.flabels.append(self.label) #We declare 5 answer lables and add them to canvas with x and y co ordinates for x in range(5): self.label = Label(self, text='values', fg='white', bg='blue') self.label.pack() self.alabels.append(self.label) #Create front label in canvas for label in self.flabels: w.create_window(self.flblx,self.flbly,window=label) self.flbly = self.flbly + 19 #Create answer label in cavas for label in self.alabels: w.create_window(self.alblx,self.albly,window=label) self.albly = self.albly + 20 ### #Button definitions ### #Start button, and add callback to start_app function when this button is clicked self.start_button = Button(self, text="Set", height=2, width=10, command=self.start_app) self.start_button.pack() #Clear button, and add callback to clear_app function when this button is clicked self.clear_button = Button(self, text="Clear", height=2, width=10, command=self.clear_app, state="disabled") self.clear_button.pack() #Clear button, and add quit function of tkinter master when this button is clicked self.close_button = Button(self, text="Close", height=2, width=10, command=self.quit) self.close_button.pack() #Add buttons to canvas w.create_window(70, 170, window=self.start_button) w.create_window(190, 170, window=self.close_button) w.create_window(310, 170, window=self.clear_button) #Input validation for pot selection text field def check_pot(self, txt): print("POT validate!") #pot = self.entry_pot_var.get() if int(txt): if txt < 0 or txt > 4 : return False else: return True else: print("Not integer") self.entry_pot.focus_set() self.entry_pot.delete(0, END) return False #Input validation for resistence text field def check_res(self): print("Greetings!") def start_app(self): """ Start the application when start button pressed """ #Disable start button after presed global running self.running = True #self.start_button.config(state="disabled") self.clear_button.config(state="normal") print "Starting app!" #call update values function self.update_values() def clear_app(self): """ Clear the answer lable fields """ print "Clear" global running self.running = False self.start_button.config(state="normal") self.clear_button.config(state="disabled") for i in range(5): self.alabels[i].config(text=str("values")) #Clear the text fields and set default vaule self.entry_pot_var.set("Enter Pot selection") self.entry_res_var.set("Enter resistor value - 2000 to 100000") #set keyboard focus self.entry_pot.focus_set() def stop_app(self): """ Stop the app """ print "Stopping" self.quit() def update_values(self): """ Helper function to trigger label values after reading pot and res values """ #if self.running: # self.after(1000, self.update_values) #Read input value given for pot selection text field pot = self.entry_pot.get() ###if pot < 0 or pot > 4 : ### if int(pot) < 0 or int(pot) > 4 : tkMessageBox.showerror("wrong input","wrong input, pot selection must be 0-4, current selection: %s" % pot) return res = self.entry_res.get() #Read input value given for resistence text field res = self.entry_res.get() #call update text value function which converts values and send data to MCP self.update_text_values(pot, res) def update_text_values(self, pot, res): """ Update the answer lables values with resistence """ #resisitor to data conversion byte = 256 local_pot = 100000 local_res = 125 #rw = int(res) * 1000 #rw = int(rw) - int(local_res) #lev = float((rw * byte) / local_pot) #level =round(lev) #level = int(level) #level = int(res) - int(local_res) if float(res): level = float(res) - int(local_res) else: level = int(res) - int(local_res) level = (level * byte) / local_pot level = int(level) print(level) b = 0 if int(pot) == 0: b = "0001" "0001" "{0:08b}".format(level) if int(pot) == 1: b = "0001" "0001" "{0:08b}" '{0:016b}'.format(level) if int(pot) == 2: b = "0001" "0001" "{0:08b}" '{0:032b}'.format(level) if int(pot) == 3: b = "0001" "0001" "{0:08b}" '{0:048b}'.format(level) if int(pot) == 4: b = "0001" "0001" "{0:08b}" '{0:064b}'.format(level) print b #update answer label based on poti selection self.alabels[int(pot)].config(text=str(level)) for x in b: GPIO.output(SPI_SDI_PIN, int(x)) print(int(x)) GPIO.output(SPI_CLK_PIN, True) GPIO.output(SPI_CLK_PIN, False) GPIO.output(SPI_CS_PIN, True) self.update_idletasks()
class GetKeysDialog(Toplevel): def __init__(self, parent, title, action, currentKeySequences, _htest=False): """ action - string, the name of the virtual event these keys will be mapped to currentKeys - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest """ Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.resizable(height=FALSE, width=FALSE) self.title(title) self.transient(parent) self.grab_set() self.protocol("WM_DELETE_WINDOW", self.Cancel) self.parent = parent self.action = action self.currentKeySequences = currentKeySequences self.result = '' self.keyString = StringVar(self) self.keyString.set('') self.SetModifiersForPlatform( ) # set self.modifiers, self.modifier_label self.modifier_vars = [] for modifier in self.modifiers: variable = StringVar(self) variable.set('') self.modifier_vars.append(variable) self.advanced = False self.CreateWidgets() self.LoadFinalKeyList() self.withdraw() #hide while setting geometry self.update_idletasks() self.geometry("+%d+%d" % (parent.winfo_rootx() + (parent.winfo_width() / 2 - self.winfo_reqwidth() / 2), parent.winfo_rooty() + ((parent.winfo_height() / 2 - self.winfo_reqheight() / 2) if not _htest else 150)) ) #centre dialog over parent (or below htest box) self.deiconify() #geometry set, unhide self.wait_window() def CreateWidgets(self): frameMain = Frame(self, borderwidth=2, relief=SUNKEN) frameMain.pack(side=TOP, expand=TRUE, fill=BOTH) frameButtons = Frame(self) frameButtons.pack(side=BOTTOM, fill=X) self.buttonOK = Button(frameButtons, text='OK', width=8, command=self.OK) self.buttonOK.grid(row=0, column=0, padx=5, pady=5) self.buttonCancel = Button(frameButtons, text='Cancel', width=8, command=self.Cancel) self.buttonCancel.grid(row=0, column=1, padx=5, pady=5) self.frameKeySeqBasic = Frame(frameMain) self.frameKeySeqAdvanced = Frame(frameMain) self.frameControlsBasic = Frame(frameMain) self.frameHelpAdvanced = Frame(frameMain) self.frameKeySeqAdvanced.grid(row=0, column=0, sticky=NSEW, padx=5, pady=5) self.frameKeySeqBasic.grid(row=0, column=0, sticky=NSEW, padx=5, pady=5) self.frameKeySeqBasic.lift() self.frameHelpAdvanced.grid(row=1, column=0, sticky=NSEW, padx=5) self.frameControlsBasic.grid(row=1, column=0, sticky=NSEW, padx=5) self.frameControlsBasic.lift() self.buttonLevel = Button(frameMain, command=self.ToggleLevel, text='Advanced Key Binding Entry >>') self.buttonLevel.grid(row=2, column=0, stick=EW, padx=5, pady=5) labelTitleBasic = Label(self.frameKeySeqBasic, text="New keys for '" + self.action + "' :") labelTitleBasic.pack(anchor=W) labelKeysBasic = Label(self.frameKeySeqBasic, justify=LEFT, textvariable=self.keyString, relief=GROOVE, borderwidth=2) labelKeysBasic.pack(ipadx=5, ipady=5, fill=X) self.modifier_checkbuttons = {} column = 0 for modifier, variable in zip(self.modifiers, self.modifier_vars): label = self.modifier_label.get(modifier, modifier) check = Checkbutton(self.frameControlsBasic, command=self.BuildKeyString, text=label, variable=variable, onvalue=modifier, offvalue='') check.grid(row=0, column=column, padx=2, sticky=W) self.modifier_checkbuttons[modifier] = check column += 1 labelFnAdvice=Label(self.frameControlsBasic,justify=LEFT, text=\ "Select the desired modifier keys\n"+ "above, and the final key from the\n"+ "list on the right.\n\n" + "Use upper case Symbols when using\n" + "the Shift modifier. (Letters will be\n" + "converted automatically.)") labelFnAdvice.grid(row=1, column=0, columnspan=4, padx=2, sticky=W) self.listKeysFinal = Listbox(self.frameControlsBasic, width=15, height=10, selectmode=SINGLE) self.listKeysFinal.bind('<ButtonRelease-1>', self.FinalKeySelected) self.listKeysFinal.grid(row=0, column=4, rowspan=4, sticky=NS) scrollKeysFinal = Scrollbar(self.frameControlsBasic, orient=VERTICAL, command=self.listKeysFinal.yview) self.listKeysFinal.config(yscrollcommand=scrollKeysFinal.set) scrollKeysFinal.grid(row=0, column=5, rowspan=4, sticky=NS) self.buttonClear = Button(self.frameControlsBasic, text='Clear Keys', command=self.ClearKeySeq) self.buttonClear.grid(row=2, column=0, columnspan=4) labelTitleAdvanced = Label( self.frameKeySeqAdvanced, justify=LEFT, text="Enter new binding(s) for '" + self.action + "' :\n" + "(These bindings will not be checked for validity!)") labelTitleAdvanced.pack(anchor=W) self.entryKeysAdvanced = Entry(self.frameKeySeqAdvanced, textvariable=self.keyString) self.entryKeysAdvanced.pack(fill=X) labelHelpAdvanced = Label( self.frameHelpAdvanced, justify=LEFT, text="Key bindings are specified using Tkinter keysyms as\n" + "in these samples: <Control-f>, <Shift-F2>, <F12>,\n" "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n" "Upper case is used when the Shift modifier is present!\n\n" + "'Emacs style' multi-keystroke bindings are specified as\n" + "follows: <Control-x><Control-y>, where the first key\n" + "is the 'do-nothing' keybinding.\n\n" + "Multiple separate bindings for one action should be\n" + "separated by a space, eg., <Alt-v> <Meta-v>.") labelHelpAdvanced.grid(row=0, column=0, sticky=NSEW) def SetModifiersForPlatform(self): """Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn't matter if the keyboard has these keys, it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering. """ if sys.platform == "darwin": self.modifiers = ['Shift', 'Control', 'Option', 'Command'] else: self.modifiers = ['Control', 'Alt', 'Shift'] self.modifier_label = {'Control': 'Ctrl'} # short name def ToggleLevel(self): if self.buttonLevel.cget('text')[:8] == 'Advanced': self.ClearKeySeq() self.buttonLevel.config(text='<< Basic Key Binding Entry') self.frameKeySeqAdvanced.lift() self.frameHelpAdvanced.lift() self.entryKeysAdvanced.focus_set() self.advanced = True else: self.ClearKeySeq() self.buttonLevel.config(text='Advanced Key Binding Entry >>') self.frameKeySeqBasic.lift() self.frameControlsBasic.lift() self.advanced = False def FinalKeySelected(self, event): self.BuildKeyString() def BuildKeyString(self): keyList = modifiers = self.GetModifiers() finalKey = self.listKeysFinal.get(ANCHOR) if finalKey: finalKey = self.TranslateKey(finalKey, modifiers) keyList.append(finalKey) self.keyString.set('<' + string.join(keyList, '-') + '>') def GetModifiers(self): modList = [variable.get() for variable in self.modifier_vars] return [mod for mod in modList if mod] def ClearKeySeq(self): self.listKeysFinal.select_clear(0, END) self.listKeysFinal.yview(MOVETO, '0.0') for variable in self.modifier_vars: variable.set('') self.keyString.set('') def LoadFinalKeyList(self): #these tuples are also available for use in validity checks self.functionKeys = ('F1', 'F2', 'F2', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12') self.alphanumKeys = tuple(string.ascii_lowercase + string.digits) self.punctuationKeys = tuple('~!@#%^&*()_-+={}[]|;:,.<>/?') self.whitespaceKeys = ('Tab', 'Space', 'Return') self.editKeys = ('BackSpace', 'Delete', 'Insert') self.moveKeys = ('Home', 'End', 'Page Up', 'Page Down', 'Left Arrow', 'Right Arrow', 'Up Arrow', 'Down Arrow') #make a tuple of most of the useful common 'final' keys keys = (self.alphanumKeys + self.punctuationKeys + self.functionKeys + self.whitespaceKeys + self.editKeys + self.moveKeys) self.listKeysFinal.insert(END, *keys) def TranslateKey(self, key, modifiers): "Translate from keycap symbol to the Tkinter keysym" translateDict = { 'Space': 'space', '~': 'asciitilde', '!': 'exclam', '@': 'at', '#': 'numbersign', '%': 'percent', '^': 'asciicircum', '&': 'ampersand', '*': 'asterisk', '(': 'parenleft', ')': 'parenright', '_': 'underscore', '-': 'minus', '+': 'plus', '=': 'equal', '{': 'braceleft', '}': 'braceright', '[': 'bracketleft', ']': 'bracketright', '|': 'bar', ';': 'semicolon', ':': 'colon', ',': 'comma', '.': 'period', '<': 'less', '>': 'greater', '/': 'slash', '?': 'question', 'Page Up': 'Prior', 'Page Down': 'Next', 'Left Arrow': 'Left', 'Right Arrow': 'Right', 'Up Arrow': 'Up', 'Down Arrow': 'Down', 'Tab': 'Tab' } if key in translateDict.keys(): key = translateDict[key] if 'Shift' in modifiers and key in string.ascii_lowercase: key = key.upper() key = 'Key-' + key return key def OK(self, event=None): if self.advanced or self.KeysOK(): # doesn't check advanced string yet self.result = self.keyString.get() self.destroy() def Cancel(self, event=None): self.result = '' self.destroy() def KeysOK(self): '''Validity check on user's 'basic' keybinding selection. Doesn't check the string produced by the advanced dialog because 'modifiers' isn't set. ''' keys = self.keyString.get() keys.strip() finalKey = self.listKeysFinal.get(ANCHOR) modifiers = self.GetModifiers() # create a key sequence list for overlap check: keySequence = keys.split() keysOK = False title = 'Key Sequence Error' if not keys: tkMessageBox.showerror(title=title, parent=self, message='No keys specified.') elif not keys.endswith('>'): tkMessageBox.showerror(title=title, parent=self, message='Missing the final Key') elif (not modifiers and finalKey not in self.functionKeys + self.moveKeys): tkMessageBox.showerror(title=title, parent=self, message='No modifier key(s) specified.') elif (modifiers == ['Shift']) \ and (finalKey not in self.functionKeys + self.moveKeys + ('Tab', 'Space')): msg = 'The shift modifier by itself may not be used with'\ ' this key symbol.' tkMessageBox.showerror(title=title, parent=self, message=msg) elif keySequence in self.currentKeySequences: msg = 'This key combination is already in use.' tkMessageBox.showerror(title=title, parent=self, message=msg) else: keysOK = True return keysOK
try: f = open(fn, 'U') except IOError, e: from cStringIO import StringIO f = StringIO(DEMO) en.delete(0, 'end') if fn.lower() == 'demo': en.insert(0, fn) else: import os en.insert(0, r"DEMO (can't open %s: %s)" % (os.path.join(os.getcwd(), fn), str(e))) en.update_idletasks() txt2ppt(line.rstrip() for line in f) f.close() if __name__ == '__main__': tk = Tk() lb = Label(tk, text='Enter file [or "DEMO"]:') lb.pack() en = Entry(tk) en.bind('<Return>', _start) en.pack() en.focus_set() quit = Button(tk, text="QUIT", command=tk.quit, fg='white', bg='red') quit.pack(fill='x', expand=True) tk.mainloop()
class TreeNode: def __init__(self, canvas, parent, item, colortheme, vspace=20): self.canvas = canvas self.parent = parent self.item = item self.state = 'collapsed' self.selected = False self.edited = False self.children = [] self.colortheme =colortheme self.x = self.y = None self.vspace=vspace self.halfvspace=int(round(self.vspace/2)) self.evenodd=0 if not self.parent: self.canvas.bind('<Configure>',self.reconfig) def reconfig(self,*args): if len(self.canvas['scrollregion']) >0: w,n,e,s = self.canvas._getints(self.canvas['scrollregion']) if e < self.canvas.winfo_width(): e=self.canvas.winfo_width() for item in self.canvas.windows: win,x=item rightside=x+self.canvas._getints(self.canvas.itemcget(win,'width'))[0] if rightside<e: self.canvas.itemconfigure(win,width=e-x) def destroy(self): for c in self.children[:]: self.children.remove(c) c.destroy() self.parent = None def geticonimage(self, name): return name def select(self, event=None): if self.selected: return self.deselectall() self.selected = True # self.canvas.delete(self.image_id) self.drawicon() self.drawtext() self.item.OnClick() def deselect(self, event=None): if not self.selected: return self.selected = False # self.canvas.delete(self.image_id) self.drawicon() self.drawtext() def deselectall(self): if self.parent: self.parent.deselectall() else: self.deselecttree() def deselecttree(self): if self.selected: self.deselect() for child in self.children: child.deselecttree() def flip(self, event=None): if self.state == 'expanded': self.collapse() else: self.expand() self.item.OnDoubleClick() return "break" def expand(self, event=None): if not self.item._IsExpandable(): return if self.state != 'expanded': self.state = 'expanded' self.update() self.view() def collapse(self, event=None): self.deselecttree() if self.state != 'collapsed': self.state = 'collapsed' self.update() def view(self): top = self.y bottom = self.lastvisiblechild().y + self.vspace height = bottom - top visible_top = self.canvas.canvasy(0) visible_height = self.canvas.winfo_height() visible_bottom = self.canvas.canvasy(visible_height) if visible_top <= top and bottom <= visible_bottom: return x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion']) if top >= visible_top and height <= visible_height: fraction = top + height - visible_height else: fraction = top fraction = float(fraction) / y1 self.canvas.yview_moveto(fraction) def lastvisiblechild(self): if self.children and self.state == 'expanded': return self.children[-1].lastvisiblechild() else: return self def update(self): if self.parent: self.parent.update() else: self.canvas.evenodd=1 self.canvas.windows=[] oldcursor = self.canvas['cursor'] self.canvas['cursor'] = "watch" self.canvas.update() self.canvas.delete(ALL) self.draw(5, 3) x0, y0, x1, y1 = self.canvas.bbox(ALL) self.canvas.configure(scrollregion=(0, 0, x1, y1)) self.canvas['cursor'] = oldcursor self.reconfig() def draw(self, x, y): if self.canvas.evenodd: self.evenodd=0 self.canvas.evenodd=0 else: self.evenodd=1 self.canvas.evenodd=1 self.x, self.y = x, y self.drawicon() self.drawtext() if self.state != 'expanded': return y+self.vspace # draw children if not self.children: sublist = self.item._GetSubList() if not sublist: # _IsExpandable() was mistaken; that's allowed return y+self.vspace for item in sublist: child = self.__class__(self.canvas, self, item, self.colortheme, self.vspace) self.children.append(child) cx = x+self.vspace cy = y+self.vspace cylast = 0 for child in self.children: cylast = cy self.canvas.create_line(x+self.halfvspace, cy+self.halfvspace, cx, cy+self.halfvspace, fill=self.colortheme.treelinescolor, stipple="gray50") cy = child.draw(cx, cy) if child.item._IsExpandable(): if child.state == 'expanded': iconname = "tree_minus" callback = child.collapse else: iconname = "tree_plus" callback = child.expand image = self.geticonimage(iconname) id = self.canvas.create_image(x+self.halfvspace, cylast+self.halfvspace, image=image) self.canvas.tag_bind(id, "<1>", callback) self.canvas.tag_bind(id, "<Double-1>", lambda x: None) id = self.canvas.create_line(x+self.halfvspace, y+self.halfvspace, x+self.halfvspace, cylast+self.halfvspace, stipple="gray50", fill=self.colortheme.treelinescolor) self.canvas.tag_lower(id) return cy def drawicon(self): return def drawtext(self): textx = self.x texty = self.y labeltext = self.item.GetLabelText() if labeltext: id = self.canvas.create_text(textx, texty, anchor="nw", text=labeltext) self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) x0, y0, x1, y1 = self.canvas.bbox(id) textx = max(x1, 200) + self.halfvspace text = self.item.GetText() or "<no text>" if self.selected: imagename = (self.item.GetSelectedIconName() or self.item.GetIconName() or "tree_node") else: imagename = self.item.GetIconName() or "tree_node" image = self.geticonimage(imagename) try: self.entry except AttributeError: pass else: self.edit_finish() try: label = self.label except AttributeError: self.frame = Frame(self.canvas, border=1, relief='flat') self.iconlabel = Label(self.frame, image=image, bd=0, padx=1, pady=1, anchor=W) self.label = Label(self.frame, text=text, bd=0, padx=3, pady=1, anchor=W) self.iconlabel.pack(side='left') self.label.pack(side='left', fill='y') widgets=[self.label,self.iconlabel, self.frame] if self.evenodd: bgcolor=self.colortheme.evencolor else: bgcolor=self.colortheme.editfieldbackground for widget in widgets: if self.selected: widget['bg']=self.colortheme.selectbackground else: widget['bg']=bgcolor if self.selected: self.label['fg']=self.colortheme.selectforeground else: self.label['fg']=self.colortheme.foreground width=self.frame.winfo_reqwidth() if width < self.canvas.winfo_width()-textx: width = self.canvas.winfo_width()-textx id = self.canvas.create_window(textx, texty, anchor=NW, window=self.frame, width=width) self.canvas.windows.append((id,textx)) self.label.bind("<1>", self.select_or_edit) self.label.bind("<Double-1>", self.flip) self.iconlabel.bind("<1>", self.select_or_edit) self.iconlabel.bind("<Double-1>", self.flip) self.frame.bind("<1>", self.select_or_edit) self.frame.bind("<Double-1>", self.flip) self.label.bind("<Button-4>", self.unit_up) self.label.bind("<Button-5>", self.unit_down) self.iconlabel.bind("<Button-4>", self.unit_up) self.iconlabel.bind("<Button-5>", self.unit_down) self.frame.bind("<Button-4>", self.unit_up) self.frame.bind("<Button-5>", self.unit_down) self.text_id = id def unit_up(self, event): first,last=self.canvas.yview() if first <= 0 and last >= 1: return "break" self.canvas.yview_scroll(-1, "unit") return "break" def unit_down(self, event): first,last=self.canvas.yview() if first <= 0 and last >= 1: return "break" self.canvas.yview_scroll(1, "unit") return "break" def select_or_edit(self, event=None): if self.selected and self.item.IsEditable(): self.edit(event) else: self.select(event) def edit(self, event=None): if self.edited: return self.edited = True self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0) self.entry.insert(0, self.label['text']) self.entry.selection_range(0, END) self.entry.pack(ipadx=5) self.entry.focus_set() self.entry.bind("<Return>", self.edit_finish) self.entry.bind("<Escape>", self.edit_cancel) def edit_finish(self, event=None): try: entry = self.entry del self.entry self.edited = False except AttributeError: return text = entry.get() entry.destroy() if text and text != self.item.GetText(): self.item.SetText(text) text = self.item.GetText() self.label['text'] = text self.drawtext() self.canvas.focus_set() def edit_cancel(self, event=None): try: entry = self.entry del self.entry self.edited = False except AttributeError: return entry.destroy() self.drawtext() self.canvas.focus_set()
class TreeNode: def __init__(self, canvas, parent, item, colortheme, vspace=20): self.canvas = canvas self.parent = parent self.item = item self.state = 'collapsed' self.selected = False self.edited = False self.children = [] self.colortheme = colortheme self.x = self.y = None self.vspace = vspace self.halfvspace = int(round(self.vspace / 2)) self.evenodd = 0 if not self.parent: self.canvas.bind('<Configure>', self.reconfig) def reconfig(self, *args): if len(self.canvas['scrollregion']) > 0: w, n, e, s = self.canvas._getints(self.canvas['scrollregion']) if e < self.canvas.winfo_width(): e = self.canvas.winfo_width() for item in self.canvas.windows: win, x = item rightside = x + self.canvas._getints( self.canvas.itemcget(win, 'width'))[0] if rightside < e: self.canvas.itemconfigure(win, width=e - x) def destroy(self): for c in self.children[:]: self.children.remove(c) c.destroy() self.parent = None def geticonimage(self, name): return name def select(self, event=None): if self.selected: return self.deselectall() self.selected = True # self.canvas.delete(self.image_id) self.drawicon() self.drawtext() self.item.OnClick() def deselect(self, event=None): if not self.selected: return self.selected = False # self.canvas.delete(self.image_id) self.drawicon() self.drawtext() def deselectall(self): if self.parent: self.parent.deselectall() else: self.deselecttree() def deselecttree(self): if self.selected: self.deselect() for child in self.children: child.deselecttree() def flip(self, event=None): if self.state == 'expanded': self.collapse() else: self.expand() self.item.OnDoubleClick() return "break" def expand(self, event=None): if not self.item._IsExpandable(): return if self.state != 'expanded': self.state = 'expanded' self.update() self.view() def collapse(self, event=None): self.deselecttree() if self.state != 'collapsed': self.state = 'collapsed' self.update() def view(self): top = self.y bottom = self.lastvisiblechild().y + self.vspace height = bottom - top visible_top = self.canvas.canvasy(0) visible_height = self.canvas.winfo_height() visible_bottom = self.canvas.canvasy(visible_height) if visible_top <= top and bottom <= visible_bottom: return x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion']) if top >= visible_top and height <= visible_height: fraction = top + height - visible_height else: fraction = top fraction = float(fraction) / y1 self.canvas.yview_moveto(fraction) def lastvisiblechild(self): if self.children and self.state == 'expanded': return self.children[-1].lastvisiblechild() else: return self def update(self): if self.parent: self.parent.update() else: self.canvas.evenodd = 1 self.canvas.windows = [] oldcursor = self.canvas['cursor'] self.canvas['cursor'] = "watch" self.canvas.update() self.canvas.delete(ALL) self.draw(5, 3) x0, y0, x1, y1 = self.canvas.bbox(ALL) self.canvas.configure(scrollregion=(0, 0, x1, y1)) self.canvas['cursor'] = oldcursor self.reconfig() def draw(self, x, y): if self.canvas.evenodd: self.evenodd = 0 self.canvas.evenodd = 0 else: self.evenodd = 1 self.canvas.evenodd = 1 self.x, self.y = x, y self.drawicon() self.drawtext() if self.state != 'expanded': return y + self.vspace # draw children if not self.children: sublist = self.item._GetSubList() if not sublist: # _IsExpandable() was mistaken; that's allowed return y + self.vspace for item in sublist: child = self.__class__(self.canvas, self, item, self.colortheme, self.vspace) self.children.append(child) cx = x + self.vspace cy = y + self.vspace cylast = 0 for child in self.children: cylast = cy self.canvas.create_line(x + self.halfvspace, cy + self.halfvspace, cx, cy + self.halfvspace, fill=self.colortheme.treelinescolor, stipple="gray50") cy = child.draw(cx, cy) if child.item._IsExpandable(): if child.state == 'expanded': iconname = "tree_minus" callback = child.collapse else: iconname = "tree_plus" callback = child.expand image = self.geticonimage(iconname) id = self.canvas.create_image(x + self.halfvspace, cylast + self.halfvspace, image=image) self.canvas.tag_bind(id, "<1>", callback) self.canvas.tag_bind(id, "<Double-1>", lambda x: None) id = self.canvas.create_line(x + self.halfvspace, y + self.halfvspace, x + self.halfvspace, cylast + self.halfvspace, stipple="gray50", fill=self.colortheme.treelinescolor) self.canvas.tag_lower(id) return cy def drawicon(self): return def drawtext(self): textx = self.x texty = self.y labeltext = self.item.GetLabelText() if labeltext: id = self.canvas.create_text(textx, texty, anchor="nw", text=labeltext) self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) x0, y0, x1, y1 = self.canvas.bbox(id) textx = max(x1, 200) + self.halfvspace text = self.item.GetText() or "<no text>" if self.selected: imagename = (self.item.GetSelectedIconName() or self.item.GetIconName() or "tree_node") else: imagename = self.item.GetIconName() or "tree_node" image = self.geticonimage(imagename) try: self.entry except AttributeError: pass else: self.edit_finish() try: label = self.label except AttributeError: self.frame = Frame(self.canvas, border=1, relief='flat') self.iconlabel = Label(self.frame, image=image, bd=0, padx=1, pady=1, anchor=W) self.label = Label(self.frame, text=text, bd=0, padx=3, pady=1, anchor=W) self.iconlabel.pack(side='left') self.label.pack(side='left', fill='y') widgets = [self.label, self.iconlabel, self.frame] if self.evenodd: bgcolor = self.colortheme.evencolor else: bgcolor = self.colortheme.editfieldbackground for widget in widgets: if self.selected: widget['bg'] = self.colortheme.selectbackground else: widget['bg'] = bgcolor if self.selected: self.label['fg'] = self.colortheme.selectforeground else: self.label['fg'] = self.colortheme.foreground width = self.frame.winfo_reqwidth() if width < self.canvas.winfo_width() - textx: width = self.canvas.winfo_width() - textx id = self.canvas.create_window(textx, texty, anchor=NW, window=self.frame, width=width) self.canvas.windows.append((id, textx)) self.label.bind("<1>", self.select_or_edit) self.label.bind("<Double-1>", self.flip) self.iconlabel.bind("<1>", self.select_or_edit) self.iconlabel.bind("<Double-1>", self.flip) self.frame.bind("<1>", self.select_or_edit) self.frame.bind("<Double-1>", self.flip) self.label.bind("<Button-4>", self.unit_up) self.label.bind("<Button-5>", self.unit_down) self.iconlabel.bind("<Button-4>", self.unit_up) self.iconlabel.bind("<Button-5>", self.unit_down) self.frame.bind("<Button-4>", self.unit_up) self.frame.bind("<Button-5>", self.unit_down) self.text_id = id def unit_up(self, event): first, last = self.canvas.yview() if first <= 0 and last >= 1: return "break" self.canvas.yview_scroll(-1, "unit") return "break" def unit_down(self, event): first, last = self.canvas.yview() if first <= 0 and last >= 1: return "break" self.canvas.yview_scroll(1, "unit") return "break" def select_or_edit(self, event=None): if self.selected and self.item.IsEditable(): self.edit(event) else: self.select(event) def edit(self, event=None): if self.edited: return self.edited = True self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0) self.entry.insert(0, self.label['text']) self.entry.selection_range(0, END) self.entry.pack(ipadx=5) self.entry.focus_set() self.entry.bind("<Return>", self.edit_finish) self.entry.bind("<Escape>", self.edit_cancel) def edit_finish(self, event=None): try: entry = self.entry del self.entry self.edited = False except AttributeError: return text = entry.get() entry.destroy() if text and text != self.item.GetText(): self.item.SetText(text) text = self.item.GetText() self.label['text'] = text self.drawtext() self.canvas.focus_set() def edit_cancel(self, event=None): try: entry = self.entry del self.entry self.edited = False except AttributeError: return entry.destroy() self.drawtext() self.canvas.focus_set()
def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.worker = None self.elapsed = 0 self.settings = Settings(self) # self.initUI() follows self.parent.title("Scan Images") self.pack(fill=BOTH, expand=1) r = 0 # current grid row Label(self, text="Name prefix:").grid(row=r, column=0) Label(self, text="Number suffix:").grid(row=r, column=1) r += 1 self.newName = StringVar() self.newName.set('Scan_') newName = Entry(self, textvariable=self.newName, width=60) newName.grid(row=1, column=0) newName.bind("<Return>", lambda event: self.scan()) newName.bind("<KP_Enter>", lambda event: self.scan()) newName.bind("<Escape>", lambda event: self.parent.destroy()) newName.focus_set() self.newNameEntry = newName self.numberSuffix = Spinbox(self, from_=1, to=999) self.numberSuffix.bind("<Return>", lambda event: self.scan()) self.numberSuffix.bind("<KP_Enter>", lambda event: self.scan()) self.numberSuffix.grid(row=r, column=1) r += 1 self.okButton = Button(self, text="Scan", command=self.scan, width=60, height=5) self.okButton.grid(row=r, column=0) cancelButton = Button(self, text="Cancel", command=self.parent.destroy) cancelButton.grid(row=r, column=1) r += 1 settings_panel = tk.Frame(self) panel = tk.Frame(settings_panel) tk.Label(panel, text="Paper Format").pack() tk.Radiobutton(panel, text="A4", value=1.0, variable=self.settings.scale).pack(anchor=tk.W) tk.Radiobutton(panel, text="A5", value=2 ** (-0.5), variable=self.settings.scale).pack(anchor=tk.W) tk.Radiobutton(panel, text="A6", value=0.5, variable=self.settings.scale).pack(anchor=tk.W) panel.pack(side=tk.LEFT, anchor=tk.N) panel = tk.Frame(settings_panel) tk.Label(panel, text="File Format").pack() tk.Radiobutton(panel, text="PNG", value='.png', variable=self.settings.extension).pack(anchor=tk.W) tk.Radiobutton(panel, text="JPG", value='.jpg', variable=self.settings.extension).pack(anchor=tk.W) panel.pack(side=tk.LEFT, anchor=tk.N) panel = tk.Frame(settings_panel) tk.Label(panel, text="Scan Mode").pack() tk.Radiobutton(panel, text="Color", value='color', variable=self.settings.scan_mode).pack(anchor=tk.W) tk.Radiobutton(panel, text="Gray", value='gray', variable=self.settings.scan_mode).pack(anchor=tk.W) tk.Radiobutton(panel, text="Lineart", value='lineart', variable=self.settings.scan_mode).pack(anchor=tk.W) panel.pack(side=tk.LEFT, anchor=tk.N) settings_panel.grid(row=r, column=0, columnspan=2) r += 1 self.statusLabel = Label(self, text="Idle") self.statusLabel.grid(row=r, column=0, columnspan=2)
class GetHelpSourceDialog(Toplevel): def __init__(self, parent, title, menuItem='', filePath=''): """Get menu entry and url/ local file location for Additional Help User selects a name for the Help resource and provides a web url or a local file as its source. The user can enter a url or browse for the file. """ Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.resizable(height=False, width=False) self.title(title) self.transient(parent) self.grab_set() self.protocol("WM_DELETE_WINDOW", self.Cancel) self.parent = parent self.result = None self.CreateWidgets() self.menu.set(menuItem) self.path.set(filePath) self.withdraw() #hide while setting geometry #needs to be done here so that the winfo_reqwidth is valid self.update_idletasks() #centre dialog over parent: self.geometry("+%d+%d" % ((parent.winfo_rootx() + ((parent.winfo_width()/2) -(self.winfo_reqwidth()/2)), parent.winfo_rooty() + ((parent.winfo_height()/2) -(self.winfo_reqheight()/2))))) self.deiconify() #geometry set, unhide self.bind('<Return>', self.Ok) self.wait_window() def CreateWidgets(self): self.menu = StringVar(self) self.path = StringVar(self) self.fontSize = StringVar(self) self.frameMain = Frame(self, borderwidth=2, relief=GROOVE) labelMenu = Label(self.frameMain, anchor=W, justify=LEFT, text='Menu Item:') self.entryMenu = Entry(self.frameMain, textvariable=self.menu) labelPath = Label(self.frameMain, anchor=W, justify=LEFT, text='Help File Path: Enter URL or browse for file') self.entryPath = Entry(self.frameMain, textvariable=self.path, width=30) browseButton = Button(self.frameMain, text='Browse', width=8, command=self.browseFile) frameButtons = Frame(self) self.buttonOk = Button(frameButtons, text='OK', width=8, default=ACTIVE, command=self.Ok) self.buttonCancel = Button(frameButtons, text='Cancel', width=8, command=self.Cancel) self.entryMenu.focus_set() self.frameMain.pack(side=TOP, expand=True, fill=BOTH) labelMenu.pack(anchor=W, padx=5, pady=3) self.entryMenu.pack(anchor=W, padx=5, pady=3, fill=X) labelPath.pack(anchor=W, padx=5, pady=3) self.entryPath.pack(anchor=W, padx=5, pady=3, side=LEFT, fill=X) browseButton.pack(pady=3, padx=5, side=RIGHT) frameButtons.pack(side=BOTTOM, fill=X) self.buttonOk.pack(pady=5, side=RIGHT) self.buttonCancel.pack(padx=5, pady=5, side=RIGHT) if TTK: frameButtons['style'] = 'RootColor.TFrame' def browseFile(self): filetypes = [ ("HTML Files", "*.htm *.html", "TEXT"), ("PDF Files", "*.pdf", "TEXT"), ("Windows Help Files", "*.chm"), ("Text Files", "*.txt", "TEXT"), ("All Files", "*")] path = self.path.get() if path: dir, base = os.path.split(path) else: base = None if sys.platform[:3] == 'win': dir = os.path.join(os.path.dirname(sys.executable), 'Doc') if not os.path.isdir(dir): dir = os.getcwd() else: dir = os.getcwd() opendialog = tkFileDialog.Open(parent=self, filetypes=filetypes) file = opendialog.show(initialdir=dir, initialfile=base) if file: self.path.set(file) def MenuOk(self): "Simple validity check for a sensible menu item name" menuOk = True menu = self.menu.get() menu.strip() if not menu: tkMessageBox.showerror(title='Menu Item Error', message='No menu item specified', parent=self) self.entryMenu.focus_set() menuOk = False elif len(menu) > 30: tkMessageBox.showerror(title='Menu Item Error', message='Menu item too long:' '\nLimit 30 characters.', parent=self) self.entryMenu.focus_set() menuOk = False return menuOk def PathOk(self): "Simple validity check for menu file path" pathOk = True path = self.path.get() path.strip() if not path: #no path specified tkMessageBox.showerror(title='File Path Error', message='No help file path specified.', parent=self) self.entryPath.focus_set() pathOk = False elif path.startswith(('www.', 'http')): pass else: if path[:5] == 'file:': path = path[5:] if not os.path.exists(path): tkMessageBox.showerror(title='File Path Error', message='Help file path does not exist.', parent=self) self.entryPath.focus_set() pathOk = False return pathOk def Ok(self, event=None): if self.MenuOk() and self.PathOk(): self.result = (self.menu.get().strip(), self.path.get().strip()) if sys.platform == 'darwin': path = self.result[1] if path.startswith(('www', 'file:', 'http:')): pass else: # Mac Safari insists on using the URI form for local files self.result = list(self.result) self.result[1] = "file://" + path self.destroy() def Cancel(self, event=None): self.result = None self.destroy()
class PIDTune(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initialize() def initialize(self): self.grid() ##PID TUNING self.KpVar = StringVar() self.KiVar = StringVar() self.KdVar = StringVar() self.KscaleVar = StringVar() self.Kp = Entry(self, textvariable=self.KpVar) self.Ki = Entry(self, textvariable=self.KiVar) self.Kd = Entry(self, textvariable=self.KdVar) self.Kscale = Entry(self, textvariable=self.KscaleVar) self.Kp.grid(column=0,row=2,sticky='EW') self.Ki.grid(column=0,row=3,sticky='EW') self.Kd.grid(column=0,row=4,sticky='EW') self.Kscale.grid(column=0,row=5,sticky='EW') self.Kp.bind("<Return>", self.OnKp) self.Ki.bind("<Return>", self.OnKi) self.Kd.bind("<Return>", self.OnKd) self.Kscale.bind("<Return>", self.OnKscale) self.KpLabVar = StringVar() self.KiLabVar = StringVar() self.KdLabVar = StringVar() self.KscaleLabVar = StringVar() kpLabel = Label(self,textvariable=self.KpLabVar, anchor="w",fg="white",bg="blue") kpLabel.grid(column=1, row=2,columnspan=1,sticky='EW') self.KpLabVar.set("Kp") kiLabel = Label(self,textvariable=self.KiLabVar, anchor="w",fg="white",bg="blue") kiLabel.grid(column=1, row=3,columnspan=1,sticky='EW') self.KiLabVar.set("Ki") kdLabel = Label(self,textvariable=self.KdLabVar, anchor="w",fg="white",bg="blue") kdLabel.grid(column=1, row=4,columnspan=1,sticky='EW') self.KdLabVar.set("Kd") kscaleLabel= Label(self,textvariable=self.KscaleLabVar, anchor="w",fg="white",bg="blue") kscaleLabel.grid(column=1, row=5,columnspan=1,sticky='EW') self.KscaleLabVar.set("Kscale") def OnKp(self, event): kp = int(self.KpVar.get()) if (speed.SetKp(kp)): self.KpLabVar.set("Kp: " + str(kp)) self.Kp.focus_set() self.Kp.selection_range(0, END) def OnKi(self, event): ki = int(self.KiVar.get()) if (speed.SetKi(ki)): self.KiLabVar.set("Ki: " + str(ki)) self.Ki.focus_set() self.Ki.selection_range(0, END) def OnKd(self, event): kd = int(self.KdVar.get()) if (speed.SetKd(kd)): self.KdLabVar.set("Kd: " + str(kd)) self.Kd.focus_set() self.Kd.selection_range(0, END) def OnKscale(self, event): ks = int(self.KscaleVar.get()) if (speed.SetKscale(ks)): self.KscaleLabVar.set("Ks: " + str(ks)) self.Kscale.focus_set() self.Kscale.selection_range(0, END)
class SteeringFrame(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initialize() def initialize(self): self.grid() self.entryVariable = StringVar() self.entry = Entry(self, textvariable=self.entryVariable) self.entry.grid(column=0,row=0,sticky='EW') self.entry.bind("<Return>", self.OnPressEnter) button = Button(self,text="Set Steering", command=self.OnButtonClick) button.grid(column=1,row=0) self.labelVariable = StringVar() label = Label(self,textvariable=self.labelVariable, anchor="w",fg="white",bg="green") label.grid(column=0,row=1,columnspan=1,sticky='EW') self.labelVariable.set("Start..") left = Button(self,text="Left", command=self.Left) left.grid(column=0,row=2) right = Button(self,text="Right", command=self.Right) right.grid(column=1,row=2) centre = Button(self,text="Centre", command=self.Centre) centre.grid(column=3,row=2) self.steerVariable = StringVar() steerState = Label(self,textvariable=self.steerVariable, anchor="w",fg="white",bg="green") steerState.grid(column=0,row=3,columnspan=1,sticky='EW') self.steerVariable.set("Start..") self.turn_angle = steering.GetTurnAngle(); self.slider = Scale(self, from_=-self.turn_angle, to=self.turn_angle, orient=HORIZONTAL, command=self.setSteerState) self.slider.grid(column=0, row=4, columnspan=3, sticky='EW') self.grid_columnconfigure(0,weight=1) self.update() #self.geometry(self.geometry()) # caused busy wait? self.entry.focus_set() #self.entry.selection_range(0, Tkinter.END) # caused busy wait? def OnButtonClick(self): steerAngle = int(self.entryVariable.get()) steering.SetAngle(steerAngle) self.slider.set(steerAngle) self.labelVariable.set("Steering set: " + str(steerAngle) ) self.entry.focus_set() self.entry.selection_range(0, END) def OnPressEnter(self,event): steerAngle = int(self.entryVariable.get()) steering.SetAngle(steerAngle) self.slider.set(steerAngle) self.labelVariable.set("Steering set: " + str(steerAngle) ) self.entry.focus_set() self.entry.selection_range(0, END) def Left(self): self.steerVariable.set("LEFT") steering.TurnLeft() self.slider.set(-self.turn_angle) def Right(self): self.steerVariable.set("RIGHT") steering.TurnRight() self.slider.set(self.turn_angle) def Centre(self): self.steerVariable.set("CENTRE") steering.TurnStraight() self.slider.set(0) def setSteerState(self, val): val = self.slider.get() steering.SetAngle(val) steerAngle = val; self.steerVariable.set("Steering: " + str(val) )
class TreeNode: def __init__(self, canvas, parent, item, menuList=[]): self.canvas = canvas self.parent = parent self.item = item self.state = 'collapsed' self.selected = 0 self.children = {} self.kidKeys = [] self.x = self.y = None self.iconimages = {} # cache of PhotoImage instances for icons self.menuList = menuList self.menuVar = IntVar() self.menuVar.set(0) self._popupMenu = None self.image_id = None if self.menuList: if self.menuList[-1] == 'Separator': self.menuList = self.menuList[:-1] self._popupMenu = Menu(self.canvas, tearoff=0) for i in range(len(self.menuList)): item = self.menuList[i] if item == 'Separator': self._popupMenu.add_separator() else: self._popupMenu.add_radiobutton( label=item, variable=self.menuVar, value=i, indicatoron=0, command=self.popupMenuCommand) def destroy(self): for key in self.kidKeys: c = self.children[key] del self.children[key] c.destroy() self.parent = None def geticonimage(self, name): try: return self.iconimages[name] except KeyError: pass file, ext = os.path.splitext(name) ext = ext or ".gif" fullname = os.path.join(ICONDIR, file + ext) image = PhotoImage(master=self.canvas, file=fullname) self.iconimages[name] = image return image def select(self, event=None): if self.selected: return self.deselectall() self.selected = 1 if self.parent != None: if self.parent.state == 'expanded': self.canvas.delete(self.image_id) self.drawicon() self.drawtext() self.item.OnSelect(event) def deselect(self, event=None): if not self.selected: return self.selected = 0 if self.parent != None: if self.parent.state == 'expanded': self.canvas.delete(self.image_id) self.drawicon() self.drawtext() def deselectall(self): if self.parent: self.parent.deselectall() else: self.deselecttree() def deselecttree(self): if self.selected: self.deselect() for key in self.kidKeys: child = self.children[key] child.deselecttree() def flip(self, event=None): if self.state == 'expanded': self.collapse() else: self.expand() self.item.OnDoubleClick() return "break" def popupMenu(self, event=None): if self._popupMenu: self._popupMenu.post(event.widget.winfo_pointerx(), event.widget.winfo_pointery()) return "break" def popupMenuCommand(self): command = self.menuList[self.menuVar.get()] self.item.MenuCommand(command) if self.parent and (command != 'Update Explorer'): # Update parent to try to keep explorer up to date self.parent.update() def expand(self, event=None): if not self.item.IsExpandable(): return if self.state != 'expanded': self.state = 'expanded' self.update() self.view() def collapse(self, event=None): if self.state != 'collapsed': self.state = 'collapsed' self.update() def view(self): top = self.y - 2 bottom = self.lastvisiblechild().y + 17 height = bottom - top visible_top = self.canvas.canvasy(0) visible_height = self.canvas.winfo_height() visible_bottom = self.canvas.canvasy(visible_height) if visible_top <= top and bottom <= visible_bottom: return x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion']) if top >= visible_top and height <= visible_height: fraction = top + height - visible_height else: fraction = top fraction = float(fraction) / y1 self.canvas.yview_moveto(fraction) def reveal(self): # Make sure all parent nodes are marked as expanded parent = self.parent while parent: if parent.state == 'collapsed': parent.state = 'expanded' parent = parent.parent else: break # Redraw tree accordingly self.update() # Bring this item into view self.view() def lastvisiblechild(self): if self.kidKeys and self.state == 'expanded': return self.children[self.kidKeys[-1]].lastvisiblechild() else: return self def update(self): if self.parent: self.parent.update() else: oldcursor = self.canvas['cursor'] self.canvas['cursor'] = "watch" self.canvas.update() self.canvas.delete(Tkinter.ALL) # XXX could be more subtle self.draw(7, 2) x0, y0, x1, y1 = self.canvas.bbox(Tkinter.ALL) self.canvas.configure(scrollregion=(0, 0, x1, y1)) self.canvas['cursor'] = oldcursor def draw(self, x, y): # XXX This hard-codes too many geometry constants! self.x, self.y = x, y self.drawicon() self.drawtext() if self.state != 'expanded': return y + 17 # draw children sublist = self.item._GetSubList() if not sublist: # IsExpandable() was mistaken; that's allowed return y + 17 self.kidKeys = [] for item in sublist: key = item.GetKey() if self.children.has_key(key): child = self.children[key] else: child = TreeNode(self.canvas, self, item, self.menuList) self.children[key] = child self.kidKeys.append(key) # Remove unused children for key in self.children.keys(): if key not in self.kidKeys: del (self.children[key]) cx = x + 20 cy = y + 17 cylast = 0 for key in self.kidKeys: child = self.children[key] cylast = cy self.canvas.create_line(x + 9, cy + 7, cx, cy + 7, fill="gray50") cy = child.draw(cx, cy) if child.item.IsExpandable(): if child.state == 'expanded': iconname = "minusnode" callback = child.collapse else: iconname = "plusnode" callback = child.expand image = self.geticonimage(iconname) id = self.canvas.create_image(x + 9, cylast + 7, image=image) # XXX This leaks bindings until canvas is deleted: self.canvas.tag_bind(id, "<1>", callback) self.canvas.tag_bind(id, "<Double-1>", lambda x: None) id = self.canvas.create_line( x + 9, y + 10, x + 9, cylast + 7, ##stipple="gray50", # XXX Seems broken in Tk 8.0.x fill="gray50") self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2 return cy def drawicon(self): if self.selected: imagename = (self.item.GetSelectedIconName() or self.item.GetIconName() or "openfolder") else: imagename = self.item.GetIconName() or "folder" image = self.geticonimage(imagename) id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image) self.image_id = id self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) self.canvas.tag_bind(id, "<3>", self.popupMenu) def drawtext(self, text=None): textx = self.x + 20 - 1 texty = self.y - 1 labeltext = self.item.GetLabelText() if labeltext: id = self.canvas.create_text(textx, texty, anchor="nw", text=labeltext) self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) x0, y0, x1, y1 = self.canvas.bbox(id) textx = max(x1, 200) + 10 if text == None: text = self.item.GetText() or "<no text>" try: self.entry except AttributeError: pass else: self.edit_finish() try: label = self.label except AttributeError: # padding carefully selected (on Windows) to match Entry widget: self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2) if self.selected: self.label.configure(fg="white", bg="darkblue") else: fg = self.item.GetTextFg() self.label.configure(fg=fg, bg="white") id = self.canvas.create_window(textx, texty, anchor="nw", window=self.label) self.label.bind("<1>", self.select_or_edit) self.label.bind("<Double-1>", self.flip) self.label.bind("<3>", self.popupMenu) # Update text if necessary if text != self.label['text']: self.label['text'] = text self.text_id = id def select_or_edit(self, event=None): if self.selected and self.item.IsEditable(): text = self.item.GetTextForEdit() self.label['text'] = text self.drawtext(text) self.edit(event) else: self.select(event) def edit(self, event=None): self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0) self.entry.insert(0, self.label['text']) self.entry.selection_range(0, Tkinter.END) self.entry.pack(ipadx=5) self.entry.focus_set() self.entry.bind("<Return>", self.edit_finish) self.entry.bind("<Escape>", self.edit_cancel) def edit_finish(self, event=None): try: entry = self.entry del self.entry except AttributeError: return text = entry.get() entry.destroy() if text and text != self.item.GetText(): self.item.SetText(text) text = self.item.GetText() self.label['text'] = text self.drawtext() self.canvas.focus_set() def edit_cancel(self, event=None): self.drawtext() self.canvas.focus_set() def find(self, searchKey): # Search for a node who's key matches the given key # Is it this node if searchKey == self.item.GetKey(): return self # Nope, check the children sublist = self.item._GetSubList() for item in sublist: key = item.GetKey() # Use existing child or create new TreeNode if none exists if self.children.has_key(key): child = self.children[key] else: child = TreeNode(self.canvas, self, item, self.menuList) # Update local list of children and keys self.children[key] = child self.kidKeys.append(key) # See if node is child (or one of child's descendants) retVal = child.find(searchKey) if retVal: return retVal # Not here return None
class HomunculusRecording(Homunculus): def get_row(self, cut_off=0): result = self.grid_row - cut_off self.grid_row += 1 return result def __init__(self, params): self.grid_row = 0 Homunculus.__init__(self, params[0]) self.title(settings.HOMUNCULUS_VERSION + settings.HMC_TITLE_RECORDING) self.geometry("640x480+" + str(int(self.winfo_screenwidth() / 2 - 320)) + "+" + str(int(self.winfo_screenheight() / 2 - 240))) self.instructions = "Macro Recording Options" Label(self, text=self.instructions, name="pathlabel").grid(row=self.get_row(), column=1, sticky=tk.E) wf_row = self.get_row() Label(self, text="Command Words:", name="wordlabel").grid(row=wf_row, column=0, sticky=tk.W) self.word_box = Entry(self, name="word_box") self.word_box.grid(row=wf_row, column=1, sticky=tk.W) self.repeatable = tk.IntVar() Checkbutton(self, text="Make Repeatable", variable=self.repeatable).grid(row=self.get_row(), column=0, sticky=tk.W) Label(self, text="Dictation History", name="optionslabel").grid(row=self.get_row(), column=1, sticky=tk.E) self.word_state = [] cb_number = 1 sentences = params[1].split("[s]") sentences.pop() for sentence in sentences: sentence_words = sentence.split("[w]") sentence_words.pop() display_sentence = " ".join(sentence_words) cb_row = 0 # self.get_row() cb_col = 0 row_cut_off = 14 col2_inc = -1 word_state_var = tk.IntVar() if cb_number == 1: word_state_var.set(True) if cb_number < row_cut_off: cb_row = cb_row = self.get_row() else : cb_row = cb_row = self.get_row(row_cut_off + col2_inc) cb_col = 2 col2_inc += 1 Checkbutton(self, text="(" + str(cb_number) + ")", variable=word_state_var).grid(row=cb_row, column=cb_col + 1, sticky=tk.W) self.word_state.append((word_state_var, cb_number)) cb_number += 1 Label(self, text=display_sentence, name="cb_label" + str(cb_number)).grid(row=cb_row, column=cb_col, sticky=tk.W) self.cb_max = cb_number def xmlrpc_get_message(self): if self.completed: response = {"mode": "recording"} word = self.word_box.get() if len(word) == 0: self.xmlrpc_kill() response["word"] = word response["repeatable"] = self.repeatable.get() selected_indices = [] for ws in self.word_state: if ws[0].get() == 1: selected_indices.append(ws[1] - 1) response["selected_indices"] = selected_indices Timer(1, self.xmlrpc_kill).start() self.after(10, self.withdraw) return response else: return None def check_boxes(self, details): for box_index in details: if box_index >= 1 and box_index <= self.cb_max: self.word_state[box_index - 1][0].set(self.word_state[box_index - 1][0].get() == 0) def check_range_of_boxes(self, details): box_index_from = details[0] - 1 box_index_to = details[1] - 1 for i in range(0, self.cb_max): if i <= self.cb_max: self.word_state[i][0].set(i >= box_index_from and i <= box_index_to) def xmlrpc_do_action(self, action, details=None): '''acceptable keys are numbers and w and p''' if action == "check": self.check_boxes(details) elif action == "focus": if details == "word": self.word_box.focus_set() elif action == "check_range": self.check_range_of_boxes(details) elif action == "exclude": box_index = details if box_index >= 1 and box_index <= self.cb_max: self.word_state[box_index - 1][0].set(False) elif action == "repeatable": self.repeatable.set(not self.repeatable.get())
# if time string has changed, update it if vTime2 != vTime1: vTime1 = vTime2 lblClock.config(text=vTime2) # calls itself every 200 milliseconds # to update the time display as needed # could use >200 ms, but display gets jerky lblClock.after(200, fn_tick) #END OF CLOCK TICKER #FUNCTION END #START To find stockitemname #END - StockITemName selection #Call the clock ticker on initialization fn_tick() #Set focus to the first serial number txtBillRow1_1.focus_set() #Kickoff the StockItemList selection popup txtBillRow1_2.bind('<KeyRelease>', fn_selectStockItemList) txtBillRow2_2.bind('<KeyRelease>', fn_selectStockItemList) txtBillRow3_2.bind('<KeyRelease>', fn_selectStockItemList) txtBillRow10_2.bind('<KeyRelease>', fn_selectStockItemList) root.mainloop()
class LintGui(object): """Build and control a window to interact with pylint""" def __init__(self, root=None): """init""" self.root = root or Tk() self.root.title('Pylint') #reporter self.reporter = None #message queue for output from reporter self.msg_queue = Queue.Queue() self.msgs = [] self.visible_msgs = [] self.filenames = [] self.rating = StringVar() self.tabs = {} self.report_stream = BasicStream(self) self.differ = differ.Differ() #gui objects self.lbMessages = None self.showhistory = None self.results = None self.btnRun = None self.information_box = None self.convention_box = None self.refactor_box = None self.warning_box = None self.error_box = None self.fatal_box = None self.txtModule = None self.status = None self.msg_type_dict = None self.init_gui() def init_gui(self): """init helper""" #setting up frames top_frame = Frame(self.root) mid_frame = Frame(self.root) radio_frame = Frame(self.root) res_frame = Frame(self.root) msg_frame = Frame(self.root) check_frame = Frame(self.root) history_frame = Frame(self.root) btn_frame = Frame(self.root) rating_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) mid_frame.pack(side=TOP, fill=X) history_frame.pack(side=TOP, fill=BOTH, expand=True) radio_frame.pack(side=TOP, fill=BOTH, expand=True) rating_frame.pack(side=TOP, fill=BOTH, expand=True) res_frame.pack(side=TOP, fill=BOTH, expand=True) check_frame.pack(side=TOP, fill=BOTH, expand=True) msg_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) # Binding F5 application-wide to run lint self.root.bind('<F5>', self.run_lint) #Message ListBox rightscrollbar = Scrollbar(msg_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.lbMessages = Listbox(msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white") self.lbMessages.bind("<Double-Button-1>", self.show_sourcefile) self.lbMessages.pack(expand=True, fill=BOTH) rightscrollbar.config(command=self.lbMessages.yview) bottomscrollbar.config(command=self.lbMessages.xview) #Message context menu self.mnMessages = Menu(self.lbMessages, tearoff=0) self.mnMessages.add_command(label="View in sourcefile", command=self.show_sourcefile) self.mnMessages.add_command(label="Add to ignore patchfile", command=self.add_to_ignore_patchfile) self.lbMessages.bind("<Button-3>", self.show_messages_context) #History ListBoxes rightscrollbar2 = Scrollbar(history_frame) rightscrollbar2.pack(side=RIGHT, fill=Y) bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL) bottomscrollbar2.pack(side=BOTTOM, fill=X) self.showhistory = Listbox(history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white") self.showhistory.pack(expand=True, fill=BOTH) rightscrollbar2.config(command=self.showhistory.yview) bottomscrollbar2.config(command=self.showhistory.xview) self.showhistory.bind('<Double-Button-1>', self.select_recent_file) self.set_history_window() #status bar self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) #labels self.lblRatingLabel = Label(rating_frame, text='Rating:') self.lblRatingLabel.pack(side=LEFT) self.lblRating = Label(rating_frame, textvariable=self.rating) self.lblRating.pack(side=LEFT) Label(mid_frame, text='Recently Used:').pack(side=LEFT) Label(top_frame, text='Module or package').pack(side=LEFT) #file textbox self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) #results box rightscrollbar = Scrollbar(res_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.results = Listbox(res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier") self.results.pack(expand=True, fill=BOTH, side=BOTTOM) rightscrollbar.config(command=self.results.yview) bottomscrollbar.config(command=self.results.xview) #buttons Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT) Button(top_frame, text='Open Package', command=(lambda: self.file_open(package=True))).pack(side=LEFT) self.btnRun = Button(top_frame, text='Run', command=self.run_lint) self.btnRun.pack(side=LEFT) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #radio buttons self.information_box = IntVar() self.convention_box = IntVar() self.refactor_box = IntVar() self.warning_box = IntVar() self.error_box = IntVar() self.fatal_box = IntVar() i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window) c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window) r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window) w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window) e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window) f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window) i.select() c.select() r.select() w.select() e.select() f.select() i.pack(side=LEFT) c.pack(side=LEFT) r.pack(side=LEFT) w.pack(side=LEFT) e.pack(side=LEFT) f.pack(side=LEFT) #check boxes self.box = StringVar() # XXX should be generated report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window) rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window) dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window) ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window) stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window) msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window) msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window) sourceFile = Radiobutton(radio_frame, text="Source File", variable=self.box, value="Source File", command=self.refresh_results_window) report.select() report.grid(column=0, row=0, sticky=W) rawMet.grid(column=1, row=0, sticky=W) dup.grid(column=2, row=0, sticky=W) msg.grid(column=3, row=0, sticky=W) stat.grid(column=0, row=1, sticky=W) msgCat.grid(column=1, row=1, sticky=W) ext.grid(column=2, row=1, sticky=W) sourceFile.grid(column=3, row=1, sticky=W) #dictionary for check boxes and associated error term self.msg_type_dict = { 'I': lambda: self.information_box.get() == 1, 'C': lambda: self.convention_box.get() == 1, 'R': lambda: self.refactor_box.get() == 1, 'E': lambda: self.error_box.get() == 1, 'W': lambda: self.warning_box.get() == 1, 'F': lambda: self.fatal_box.get() == 1 } self.txtModule.focus_set() def select_recent_file(self, event): """adds the selected file in the history listbox to the Module box""" if not self.showhistory.size(): return selected = self.showhistory.curselection() item = self.showhistory.get(selected) #update module self.txtModule.delete(0, END) self.txtModule.insert(0, item) def refresh_msg_window(self): """refresh the message window with current output""" #clear the window self.lbMessages.delete(0, END) self.visible_msgs = [] for msg in self.msgs: if (self.msg_type_dict.get(msg.C)()): self.visible_msgs.append(msg) msg_str = convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) def refresh_results_window(self): """refresh the results window with current output""" #clear the window self.results.delete(0, END) try: for res in self.tabs[self.box.get()]: self.results.insert(END, res) except: pass def process_incoming(self): """process the incoming messages from running pylint""" while self.msg_queue.qsize(): try: msg = self.msg_queue.get(0) if msg == "DONE": self.report_stream.output_contents() return False #adding message to list of msgs self.msgs.append(msg) #displaying msg if message type is selected in check box if (self.msg_type_dict.get(msg.C)()): self.visible_msgs.append(msg) msg_str = convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) except Queue.Empty: pass return True def periodic_call(self): """determine when to unlock the run button""" if self.process_incoming(): self.root.after(100, self.periodic_call) else: #enabling button so it can be run again self.btnRun.config(state=NORMAL) def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def halt(self): """program halt placeholder""" return def file_open(self, package=False, _=None): """launch a file browser""" if not package: filename = askopenfilename(parent=self.root, filetypes=[('pythonfiles', '*.py'), ('allfiles', '*')], title='Select Module') else: filename = askdirectory(title="Select A Folder", mustexist=1) if filename == (): return self.txtModule.delete(0, END) self.txtModule.insert(0, filename) def update_filenames(self): """update the list of recent filenames""" filename = self.txtModule.get() if not filename: filename = os.getcwd() if filename + '\n' in self.filenames: index = self.filenames.index(filename + '\n') self.filenames.pop(index) #ensure only 10 most recent are stored if len(self.filenames) == 10: self.filenames.pop() self.filenames.insert(0, filename + '\n') def set_history_window(self): """update the history window with info from the history file""" #clear the window self.showhistory.delete(0, END) # keep the last 10 most recent files try: view_history = open(HOME + HISTORY, 'r') for hist in view_history.readlines(): if not hist in self.filenames: self.filenames.append(hist) self.showhistory.insert(END, hist.split('\n')[0]) view_history.close() except IOError: # do nothing since history file will be created later return def run_lint(self, _=None): """launches pylint""" self.update_filenames() self.root.configure(cursor='watch') self.reporter = GUIReporter(self, output=self.report_stream) module = self.txtModule.get() if not module: module = os.getcwd() #cleaning up msgs and windows self.msgs = [] self.visible_msgs = [] self.lbMessages.delete(0, END) self.tabs = {} self.results.delete(0, END) self.btnRun.config(state=DISABLED) #setting up a worker thread to run pylint worker = Thread(target=lint_thread, args=( module, self.reporter, self, )) self.periodic_call() worker.start() # Overwrite the .pylint-gui-history file with all the new recently added files # in order from filenames but only save last 10 files write_history = open(HOME + HISTORY, 'w') write_history.writelines(self.filenames) write_history.close() self.set_history_window() self.root.configure(cursor='') def show_sourcefile(self, event=None): selected = self.lbMessages.curselection() if not selected: return msg = self.visible_msgs[int(selected[0])] scroll = msg.line - 3 if scroll < 0: scroll = 0 self.tabs["Source File"] = open(msg.abspath, "r").readlines() self.box.set("Source File") self.refresh_results_window() self.results.yview(scroll) self.results.select_set(msg.line - 1) def show_messages_context(self, event): """Show the message listbox's context menu""" # Select the item that was clicked index = self.lbMessages.nearest(event.y) self.lbMessages.selection_clear(0, END) self.lbMessages.selection_set(index) self.lbMessages.activate(index) self.mnMessages.tk_popup(event.x_root, event.y_root) def add_to_ignore_patchfile(self, event=None): """ Add the selected message to the ignore patchfile. This means that this message will now be ignored by pylint-patcher. """ selected = self.lbMessages.curselection() if not selected: return selected_index = int(selected[0]) msg = self.visible_msgs[selected_index] self.differ.add_disable_pragma(msg.abspath, msg.line, msg.symbol) self.differ.diff() del self.msgs[self.msgs.index(msg)] del self.visible_msgs[selected_index] self.lbMessages.delete(selected_index)
class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): """init""" self.root = root or Tk() self.root.title('Pylint') #reporter self.reporter = None #message queue for output from reporter self.msg_queue = Queue.Queue() self.msgs = [] self.filenames = [] self.rating = StringVar() self.tabs = {} self.report_stream = BasicStream(self) #gui objects self.lbMessages = None self.showhistory = None self.results = None self.btnRun = None self.information_box = None self.convention_box = None self.refactor_box = None self.warning_box = None self.error_box = None self.fatal_box = None self.txtModule = None self.status = None self.msg_type_dict = None self.init_gui() def init_gui(self): """init helper""" #setting up frames top_frame = Frame(self.root) mid_frame = Frame(self.root) radio_frame = Frame(self.root) res_frame = Frame(self.root) msg_frame = Frame(self.root) check_frame = Frame(self.root) history_frame = Frame(self.root) btn_frame = Frame(self.root) rating_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) mid_frame.pack(side=TOP, fill=X) history_frame.pack(side=TOP, fill=BOTH, expand=True) radio_frame.pack(side=TOP, fill=BOTH, expand=True) rating_frame.pack(side=TOP, fill=BOTH, expand=True) res_frame.pack(side=TOP, fill=BOTH, expand=True) check_frame.pack(side=TOP, fill=BOTH, expand=True) msg_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) #Message ListBox rightscrollbar = Scrollbar(msg_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.lbMessages = Listbox(msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white") self.lbMessages.pack(expand=True, fill=BOTH) rightscrollbar.config(command=self.lbMessages.yview) bottomscrollbar.config(command=self.lbMessages.xview) #History ListBoxes rightscrollbar2 = Scrollbar(history_frame) rightscrollbar2.pack(side=RIGHT, fill=Y) bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL) bottomscrollbar2.pack(side=BOTTOM, fill=X) self.showhistory = Listbox(history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white") self.showhistory.pack(expand=True, fill=BOTH) rightscrollbar2.config(command=self.showhistory.yview) bottomscrollbar2.config(command=self.showhistory.xview) self.showhistory.bind('<Double-Button-1>', self.select_recent_file) self.set_history_window() #status bar self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) #labels self.lblRatingLabel = Label(rating_frame, text='Rating:') self.lblRatingLabel.pack(side=LEFT) self.lblRating = Label(rating_frame, textvariable=self.rating) self.lblRating.pack(side=LEFT) Label(mid_frame, text='Recently Used:').pack(side=LEFT) Label(top_frame, text='Module or package').pack(side=LEFT) #file textbox self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) #results box rightscrollbar = Scrollbar(res_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.results = Listbox(res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier") self.results.pack(expand=True, fill=BOTH, side=BOTTOM) rightscrollbar.config(command=self.results.yview) bottomscrollbar.config(command=self.results.xview) #buttons Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT) Button(top_frame, text='Open Package', command=(lambda : self.file_open(package=True))).pack(side=LEFT) self.btnRun = Button(top_frame, text='Run', command=self.run_lint) self.btnRun.pack(side=LEFT) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #radio buttons self.information_box = IntVar() self.convention_box = IntVar() self.refactor_box = IntVar() self.warning_box = IntVar() self.error_box = IntVar() self.fatal_box = IntVar() i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window) c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window) r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window) w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window) e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window) f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window) i.select() c.select() r.select() w.select() e.select() f.select() i.pack(side=LEFT) c.pack(side=LEFT) r.pack(side=LEFT) w.pack(side=LEFT) e.pack(side=LEFT) f.pack(side=LEFT) #check boxes self.box = StringVar() # XXX should be generated report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window) rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window) dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window) ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window) stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window) msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window) msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window) report.select() report.grid(column=0, row=0, sticky=W) rawMet.grid(column=1, row=0, sticky=W) dup.grid(column=2, row=0, sticky=W) msg.grid(column=3, row=0, sticky=E) stat.grid(column=0, row=1, sticky=W) msgCat.grid(column=1, row=1, sticky=W) ext.grid(column=2, row=1, columnspan=2, sticky=W) #dictionary for check boxes and associated error term self.msg_type_dict = { 'I' : lambda : self.information_box.get() == 1, 'C' : lambda : self.convention_box.get() == 1, 'R' : lambda : self.refactor_box.get() == 1, 'E' : lambda : self.error_box.get() == 1, 'W' : lambda : self.warning_box.get() == 1, 'F' : lambda : self.fatal_box.get() == 1 } self.txtModule.focus_set() def select_recent_file(self, event): """adds the selected file in the history listbox to the Module box""" if not self.showhistory.size(): return selected = self.showhistory.curselection() item = self.showhistory.get(selected) #update module self.txtModule.delete(0, END) self.txtModule.insert(0, item) def refresh_msg_window(self): """refresh the message window with current output""" #clear the window self.lbMessages.delete(0, END) for msg in self.msgs: if (self.msg_type_dict.get(msg[0])()): msg_str = self.convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) def refresh_results_window(self): """refresh the results window with current output""" #clear the window self.results.delete(0, END) try: for res in self.tabs[self.box.get()]: self.results.insert(END, res) except: pass def convert_to_string(self, msg): """make a string representation of a message""" if (msg[2] != ""): return "(" + msg[0] + ") " + msg[1] + "." + msg[2] + " [" + msg[3] + "]: " + msg[4] else: return "(" + msg[0] + ") " + msg[1] + " [" + msg[3] + "]: " + msg[4] def process_incoming(self): """process the incoming messages from running pylint""" while self.msg_queue.qsize(): try: msg = self.msg_queue.get(0) if msg == "DONE": self.report_stream.output_contents() return False #adding message to list of msgs self.msgs.append(msg) #displaying msg if message type is selected in check box if (self.msg_type_dict.get(msg[0])()): msg_str = self.convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) except Queue.Empty: pass return True def periodic_call(self): """determine when to unlock the run button""" if self.process_incoming(): self.root.after(100, self.periodic_call) else: #enabling button so it can be run again self.btnRun.config(state=NORMAL) def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def halt(self): """program halt placeholder""" return def file_open(self, package=False, _=None): """launch a file browser""" if not package: filename = askopenfilename(parent=self.root, filetypes=[('pythonfiles', '*.py'), ('allfiles', '*')], title='Select Module') else: filename = askdirectory(title="Select A Folder", mustexist=1) if filename == (): return self.txtModule.delete(0, END) self.txtModule.insert(0, filename) def update_filenames(self): """update the list of recent filenames""" filename = self.txtModule.get() if not filename: filename = os.getcwd() if filename+'\n' in self.filenames: index = self.filenames.index(filename+'\n') self.filenames.pop(index) #ensure only 10 most recent are stored if len(self.filenames) == 10: self.filenames.pop() self.filenames.insert(0, filename+'\n') def set_history_window(self): """update the history window with info from the history file""" #clear the window self.showhistory.delete(0, END) # keep the last 10 most recent files try: view_history = open(HOME+HISTORY, 'r') for hist in view_history.readlines(): if not hist in self.filenames: self.filenames.append(hist) self.showhistory.insert(END, hist.split('\n')[0]) view_history.close() except IOError: # do nothing since history file will be created later return def run_lint(self, _=None): """launches pylint""" self.update_filenames() self.root.configure(cursor='watch') self.reporter = GUIReporter(self, output=self.report_stream) module = self.txtModule.get() if not module: module = os.getcwd() #cleaning up msgs and windows self.msgs = [] self.lbMessages.delete(0, END) self.tabs = {} self.results.delete(0, END) self.btnRun.config(state=DISABLED) #setting up a worker thread to run pylint worker = Thread(target=lint_thread, args=(module, self.reporter, self,)) self.periodic_call() worker.start() # Overwrite the .pylint-gui-history file with all the new recently added files # in order from filenames but only save last 10 files write_history = open(HOME+HISTORY, 'w') write_history.writelines(self.filenames) write_history.close() self.set_history_window() self.root.configure(cursor='')
class IdwApp(Frame): """ Main app object for creating a Python GUI to calculate and display Inverse Distance Weighted spatial analysis for cancer occurrences. :param tkinter.ttk.Frame Frame: Parent Frame widget """ def __init__(self, root_window): """ Constructor method for setting up the window and user interface :param Tkinter.Tk root_window: Main window object """ Frame.__init__(self) self.root = root_window self.master.state('zoomed') # set font font_type = "Helvetica" self.main_font = tkFont.Font(family=font_type, size=16) self.sub_font = tkFont.Font(family=font_type, size=13) self.small_font = tkFont.Font(family=font_type, size=8) # placeholder for Entry box self.k_input = None # placeholder for image self.idw_image_jov = None # placeholder for message self.info_message = None self.initGIS() self.initUI() def initGIS(self): """ Factory method for setting up required ArcPy processing """ # GIS globals env.overwriteOutput = True env.extent = "MINOF" CheckOutExtension("Spatial") self.output_location = os.path.join(os.getcwd(), 'tkinter_output') print self.output_location if not os.path.isdir(self.output_location): os.mkdir(self.output_location) env.workspace = self.output_location self.tracts_file = os.path.join(self.output_location, "cancer_tracts.shp") self.mxd = mapping.MapDocument( os.path.join(self.output_location, "cancer_data.mxd")) def initUI(self): """ Method for creating the user interface and calling all required widget creation methods """ self.columnconfigure(0, minsize=30, weight=2) self.style = Style() Style().configure("TFrame", background="#333") self.master.title("Cancer Research") self.pack(fill=BOTH, expand=True) # Put text and image on same row frame1 = self.create_frame() self.frame = frame1 self.create_description_text(frame1) self.info_message = self.set_status_message() self.create_image(frame1) # Add any buttons self.create_buttons() def get_screen_h(self): """ Method for obtaining the user's screen height value :return int: Screen height in pixels """ return self.master.winfo_screenheight() def get_screen_w(self): """ Method for obtaining the user's screen height value :return int: Screen width in pixels """ return self.master.winfo_screenwidth() def create_frame(self): """ Factory method for creating a new frame when needed :return tkinter.ttk.Frame: Frame object """ new_frame = Frame(self) new_frame.pack(fill=X) new_frame.config() return new_frame def create_description_text(self, frame): """ Method for implementing the text boxes that describe the application """ one = "High concentrations of nitrate have\n" two = "been found during routine sampling\n" three = "of water wells throughout Wisconsin.\n\n" four = "This tool will generate a map\n" five = "based on an inverted-distance\n" six = "weighted analysis that approximates\n" seven = "the geographic extent of nitrate\nbased on sample locations." main_text = "{}{}{}{}{}{}{}".format(one, two, three, four, five, six, seven) """1st section""" style = Style() style.configure("grey.TLabel", foreground="white", background="#333") text_label = Label(frame, text=main_text, width=30, font=self.main_font, style="grey.TLabel") # text_label.pack(side=LEFT, padx=5, pady=5) text_label.grid(row=0, column=0, columnspan=2, rowspan=6, padx=30, pady=70, sticky=W + N + E) """2nd section""" k_label = Label(frame, text="Enter a value for k: (ex: 2-30)", font=self.sub_font, style="grey.TLabel") k_label.grid(row=4, column=0, columnspan=1, rowspan=1, padx=30, pady=40, sticky=W) self.k_input = Entry(frame, width=7) self.k_input.focus_set() self.k_input.grid(row=4, column=1, columnspan=1, rowspan=1, padx=1, pady=50, sticky=W) """3rd section""" small_text = "where k = power exponent of distance\nfor consideration of surrounding points" small_label = Label(frame, text=small_text, font=self.small_font, style="grey.TLabel") small_label.grid(row=4, column=0, columnspan=1, rowspan=2, padx=55, pady=50, sticky=W + E) def create_image(self, frame, new=False): """ Method for initializing the main image and resizing it to fit the required size :param tkinter.ttk.Frame frame: Frame object used for current image :param bool new: Placeholder variable for swapping default image """ if new is False: orig_image = Image.open( os.path.join(os.getcwd(), "sample_output.jpg")) else: orig_image = Image.open(os.path.join(os.getcwd(), "idwout.jpg")) resize_image = orig_image.resize((1000, 600), Image.ANTIALIAS) idw_image_jov = ImageTk.PhotoImage(resize_image) idw_label = Label(frame, image=idw_image_jov) idw_label.image = idw_image_jov idw_label.grid(row=0, column=2, rowspan=8, padx=1, pady=30, sticky=W + S + N) def set_status_message(self): """ Method to set a status message Label for later manipulation :return tkinter.ttk.Label: Label object for holding text """ """4th section""" processing = "Running IDW and creating output image...." info_message = Label(self.frame, text=processing, font=self.main_font, foreground="#333", background="#333") #style="grey.TLabel") info_message.grid(row=8, column=2, columnspan=1, rowspan=1, padx=80, pady=50, sticky=W) return info_message def update_status_message(self, color=False): """ Method for changing the color of the status Label object :param bool color: Check for adding or removing color """ if color: self.info_message.configure(foreground="white") else: self.info_message.configure(foreground="#333") self.root.update() def process_k_value(self): """ Method for verifying the K value and passing it to the back-end processing Also enforces a range of values """ k = self.k_input.get() if k == "" or not k.isdigit(): tkMessageBox.showinfo( "Warning", "Integer K value between 2 - 30 is required!") elif k and not 2 <= int(k) <= 30: tkMessageBox.showinfo( "Warning", "Your Value: {}\nChoose value between 2 - 30".format(k)) else: self.update_status_message(True) k_val = int(k) if k_val: try: self.run_idw_process(k_val) self.create_image(self.frame, new=True) except: raise ValueError( "Unable to process IDW function! \n{}".format( GetMessages())) def output_message(self, message): """ Simple method for custom error messaging :param str message: Custom error message """ tkMessageBox.showinfo("Success", message) def run_idw_process(self, k_val): """ Method for calculating the Inverse-Distance Weighted :param int k_val: User supplied k value """ filename = "idwout" full_filename = filename + ".tif" point_file = os.path.join(self.output_location, "well_nitrate.shp") # Run IDW process output_raster = idw(point_file, "nitr_ran", power=k_val) output_raster.save(full_filename) self.run_zonal_statistics( os.path.join(self.output_location, full_filename)) def run_zonal_statistics(self, output_raster): """ Method for calculating the Zonal Statistics :param str output_raster: Path to raster file """ output_table = os.path.join(self.output_location, "zonal_table.dbf") Z_Stats(self.tracts_file, "GEOID10", output_raster, output_table) self.join_table_to_tracts(output_table) def join_table_to_tracts(self, output_table): """ Method for creating an editable layer and joining the Zonal Statistics table to the census tracts shapefile :param str output_table: Path for the zonal statistics table that was created """ tracts_layer = "tracts_layer" MakeFeatureLayer_management(self.tracts_file, tracts_layer) attribute = "GEOID10" AddJoin_management(tracts_layer, attribute, output_table, attribute) self.run_ordinary_least_squres(tracts_layer) def run_ordinary_least_squres(self, tracts_layer): """ Method for calculating Ordinary Least Squares Statistics :param str tracts_layer: Name of the in-memory feature layer """ output_file = os.path.join(self.output_location, "Least Squares.shp") OrdinaryLeastSquares_stats(tracts_layer, "zonal_table.OID", output_file, "zonal_table.MEAN", ["cancer_tracts.canrate"]) self.add_layer_to_mxd(output_file) def add_layer_to_mxd(self, filename): """ Method for applying symbology to the in-memory layer and adding it to a template MXD file for output :param str filename: Name of the final output file for adding to the application """ df = mapping.ListDataFrames(self.mxd, "") create_layer = mapping.Layer(filename) ApplySymbologyFromLayer_management( create_layer, os.path.join(self.output_location, "least_squares.lyr")) mapping.AddLayer(df[0], create_layer, "BOTTOM") self.output_image("idwout.jpg") def output_image(self, image_name): """ Factory method for exporting different image types in ArcMap :param str image_name: Name of output image with file extension :return: """ if image_name.endswith("jpg"): mapping.ExportToJPEG( self.mxd, os.path.join(self.output_location, image_name)) # Add other image outputs if needed self.update_status_message() self.output_message("Process Completed") def create_buttons(self, button_text=None): """ Method to create and place all buttons for the application """ if button_text is None: button_text = "Run" button = Button(self, text=button_text, command=self.process_k_value) button.place(x=self.get_screen_w() * .75, y=self.get_screen_h() * .80) quit_button = Button(self, text="Quit", command=self.quit) quit_button.place(x=self.get_screen_w() * .80, y=self.get_screen_h() * .80)
class Words: def __init__(self, master): self.master = master master.title("Word Finder") letterCheck = master.register(self.CheckLetterEntry) wordLenCheck = master.register(self.CheckWordLenEntry) self.entryVariable = StringVar() self.entry = Entry(master, textvariable=self.entryVariable, validate='focusout', validatecommand=(letterCheck, '%P')) self.entry.grid(column=0, row=0, columnspan=2, sticky='EW', padx=10, pady=20, ipadx=10, ipady=10) #self.entry.bind("<Return>", self.OnButtonClick) self.entryVariable.set(u"Letters") wordLenLabel = Label(master, text="Word Length", anchor="e", justify="right", padx=10, pady=20) wordLenLabel.grid(column=0, row=1, sticky='E') self.wordLenVariable = StringVar() self.wordLenEntry = Entry(master, textvariable=self.wordLenVariable, validate='focusout', validatecommand=(wordLenCheck, '%P')) self.wordLenEntry.grid(column=1, row=1, padx=10, pady=10, ipadx=10, ipady=10) self.wordLenVariable.set("0") button = Button(master, text=u"Find Words!", command=self.OnButtonClick, pady=10, fg="#383a39", bg="#a1dbcd") button.grid(column=0, row=2, columnspan=2, pady=10) #button['state'] = "disabled" self.canvas = Canvas(master, width=300, height=50) self.canvas.grid(column=0, row=4, columnspan=2) self.resultsText = Text(master, state="disabled") self.resultsText.grid(column=0, row=3, columnspan=2) master.grid_columnconfigure(0, weight=1) # master.resizable(False,True) master.update() #master.geometry(self.geometry()) #self.entry.focus_set() self.entry.focus() #self.entry.selection_range(0, Tkinter.END) #self.entryVariable.trace("w", validateFields) #self.giflist = [] #self.giflist.append(PhotoImage('loadingdot1.gif')) #self.giflist.append(PhotoImage('loadingdot2.gif')) #self.giflist.append(PhotoImage('loadingdot3.gif')) self.timer_id = None def draw_one_frame(self, picNbr=0): giflist = [] giflist.append(PhotoImage(file='loadingdot1.gif')) giflist.append(PhotoImage(file='loadingdot2.gif')) giflist.append(PhotoImage(file='loadingdot3.gif')) #picNum = picNbr % (len(giflist)) gif = giflist[picNbr] self.canvas.create_image(gif.width() // 2, gif.height() // 2, image=gif) def start_loading(self, currFrame): if currFrame > 2: currFrame = 0 self.draw_one_frame(currFrame) currFrame = currFrame + 1 root.update_idletasks() self.stop_id = root.after(100, self.start_loading(currFrame)) def stop_loading(self): root.after_cancel(self.stop_id) self.canvas.delete(ALL) #def CheckLetterEntry(self, d, i, P, s, S, v, V, W): def CheckLetterEntry(self, new_text): if not new_text: self.entryVariable.set("Enter Letters Here.") return True if not (new_text.isalpha()): #print "Invalid Input Detected" self.entry.config(bg='red', fg='white') self.entry.focus_set() return False else: #print "Valid Input Detected" self.entry.config(bg='white', fg='black') return True def CheckWordLenEntry(self, new_text): if not new_text: self.wordLenVariable.set("0") return True if not (new_text.isdigit()): #print "WL Invalid Input Detected" self.wordLenEntry.config(bg='red', fg='white') self.wordLenEntry.focus_set() return False else: #print "WL Valid Input Detected" self.wordLenEntry.config(bg='white', fg='black') return True def OnButtonClick(self): self.resultsText['state'] = "normal" self.resultsText.delete(1.0, END) self.resultsText.insert(1.0, "Finding Words. Please Wait. . .") #self.resultsText['state'] = "disabled" self.master.update() # Check the Letters Entry and Word Len Entry if (self.entryVariable.get().isalpha()) and ( self.wordLenEntry.get().isdigit()): self.entry.config(bg='white', fg='black') self.wordLenEntry.config(bg='white', fg='black') #self.resultsText['state'] = "normal" #self.resultsText.delete(1.0, END) #self.resultsText['state'] = "disabled" #Get the letters to use letterArr = str(self.entry.get()) #Get the word length if self.wordLenEntry.get() == "": wordLen = 0 else: wordLen = int(self.wordLenEntry.get()) #### Build a list of possible words by running Permute on String[0-1] to String[0-length] #### read in the american-english list into an array. #### for each possible word, check it against american-english array if it exists add it to answer array if not already an answer #### only display answers that match the given wordLen # # compare fullWordList against dict and return matches # if wordLen given is 0 or blank, return ALL matching english words # if wordLen is not blank or 0, return only matches whose length = wordLen #convert all letters to lowercase letterArr = letterArr.lower() fullWordList = [] a = time.clock() if wordLen == 0: #PermWordList = itertools.permutations(letterArr,len(letterArr)) #for l in range(3,len(letterArr)+1): for l in range(2, len(letterArr) + 1): PermWordList = list(itertools.permutations(letterArr, l)) for permWord in PermWordList: combinedWord = "" for w in range(0, len(permWord)): combinedWord += permWord[w] fullWordList.append(combinedWord) # PermWordList = PermWordList + TempList else: PermWordList = itertools.permutations(letterArr, wordLen) PermWordList = list(PermWordList) for permWord in PermWordList: combinedWord = "" for w in range(0, len(permWord)): combinedWord += permWord[w] fullWordList.append(combinedWord) b = time.clock() exec_time_perm = (b - a) #fullWordList = sorted(set(fullWordList),key=len) fullWordList = sorted(set(fullWordList), key=lambda item: (-len(item), item), reverse=True) #fullWordList = fullWordList.sort(key=lambda item:(-len(item),item)) #print "Full Word List: ", fullWordList numWordsFound = 0 a = time.clock() # Enable the Results field and clear it self.resultsText['state'] = "normal" self.resultsText.delete(1.0, END) #self.start_loading(0) for checkWord in fullWordList: if (len(checkWord) > 1): #if checkWord in dictList and (wordLen == 0 or wordLen == ""): # self.resultsText.insert(Tkinter.INSERT,checkWord) # self.resultsText.insert(Tkinter.INSERT,'\n') # elif checkWord in dictList and wordLen == len(checkWord): if checkWord in dictList: self.resultsText.insert(INSERT, checkWord) self.resultsText.insert(INSERT, '\n') numWordsFound += 1 #self.stop_loading() b = time.clock() exec_time_search = (b - a) total_time = exec_time_perm + exec_time_search if numWordsFound == 0: self.resultsText.insert(1.0, "No Words Found.") else: headerStr = " %d Words Found in %.2f seconds\n----------------------------------------\n\n" % ( numWordsFound, total_time) self.resultsText.insert(1.0, headerStr) #self.resultsText['state'] = "disabled" else: self.resultsText['state'] = "normal" self.resultsText.delete(1.0, END) if not (self.entryVariable.get().isalpha()): self.resultsText.insert( 1.0, "Letters field can only contain letters.") self.entry.config(bg='red', fg='white') self.entry.focus_set() elif not (self.wordLenEntry.get().isdigit()): self.resultsText.insert( 1.0, "Word length field can only contain digits.") self.wordLenEntry.config(bg='red', fg='white') self.wordLenEntry.focus_set() self.resultsText['state'] = "disabled"
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)