class IndexWidget: def __init__(self, parser, prompt, url): self.query_url = string.joinfields(string.split(url), '') formatter = parser.formatter viewer = parser.viewer self.context = viewer.context self.w = Entry(viewer.text, highlightbackground=viewer.text["background"]) self.w.bind('<Return>', self.submit) formatter.add_hor_rule() formatter.add_flowing_data(prompt) formatter.add_literal_data(' ') parser.add_subwindow(self.w) formatter.add_line_break() formatter.add_hor_rule() def submit(self, event): data = self.w.get() url = self.query_url or self.context.get_baseurl() i = string.find(url, '?') if i >= 0: url = url[:i] url = url + '?' + quote(data) self.context.load(url)
def buscar(pattern, index): def listar(event): lista.delete(0, END) ix = open_dir(index) with ix.searcher() as searcher: query = QueryParser(pattern, ix.schema).parse(unicode(entrada.get())) results = searcher.search(query) for r in results: lista.insert(END, r['titulo']) lista.insert(END, r['fecha']) lista.insert(END, r['username']) lista.insert(END, '') root = Tkinter.Toplevel() frame1 = Frame(root) entrada = Entry(frame1, bd=2, width=60) lab = Label(frame1, text="Buscar: ") entrada.bind("<Return>", listar) sc = Scrollbar(root) sc.pack(side=RIGHT, fill=Y) lista = Listbox(root, yscrollcommand=sc.set) frame1.pack(side=TOP) lista.pack(side=TOP, fill=BOTH) lab.pack(side=LEFT) entrada.pack(side=LEFT) sc.config(command=lista.yview) root.mainloop()
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)
class EntryWithLabel(Frame, Observable): def __init__(self, master, text, default=None, minimum=-9999999, maximum=-9999999, var=DoubleVar): Frame.__init__(self, master) Observable.__init__(self) self.minimum = minimum self.maximum = maximum self.label = Label(self, text=text) self.label.grid(column=0, row=0) self.value = var() self.value.set(default if default != None else self.minimum) self.entry = Entry(self, textvariable=self.value) self.entry.bind("<FocusOut>", self.check_range) self.entry.grid(column=1, row=0) def set(self, value): return self.value.set(value) def get(self): return self.value.get() def check_range(self, event): v = self.get() v = max(v, self.minimum) v = min(v, self.maximum) self.value.set(v)
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...')
class LabelEntry(LabelBase): def __init__(self, parent_frame, label_text, entry_text='', on_input_callable=None): super(LabelEntry, self).__init__(parent_frame, label_text) self._on_input_callback = on_input_callable self._entry_var = StringVar(value=entry_text) self._entry = Entry(self._label_frame, bd=3, textvariable=self._entry_var) self._entry.bind('<Return>', self._entry_input) self._entry.pack(side=RIGHT) def _entry_input(self, event): #print 'Label [%s] text entered: %s' % (self.label_text, self.entry_text) #self.clear_entry() #self.label_text = self.entry_text if self._on_input_callback: self._on_input_callback() def clear_entry(self): self.entry_text = '' def set_entry_text(self, text): self._entry_var.set(text) def get_entry_text(self): return self._entry_var.get() entry_text = property(fget=get_entry_text, fset=set_entry_text)
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 createfileentry(self, parent_frame, fi_text, _def_fi_, f_ex=None): ''' Quite self explanatoy... creates a row in which is possible to search for a file''' file_row = Frame(parent_frame) if f_ex == None: f_ex = ((fi_text, '.' + _def_fi_.split('.')[-1]), ) _f_labels = format_dec([file_row, fi_text], _pack_=False) Efile = Entry(file_row, width=13) Efile.insert('end', _def_fi_) Efile.bind("<Key>", lambda e: "break") # Magic Efile.xview_moveto(1) Bsearch = Button(file_row, image=self.im_file, command=(lambda El=Efile: self.browsefile(El, f_ex))) # Just packing format_dec(_f_labels, _create_=False) Efile.pack(side='left', expand='yes', fill='x') Bsearch.pack(side='right', padx=0, pady=0) file_row.pack(side='top', fill='x', pady=3) # For tracing purposes list appending return Efile
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='')
class SendGCode(LabelFrame): def __init__(self, root, prtr, settings, log, *arg): LabelFrame.__init__(self, root, *arg, text="Send gcode") self.app = root self.printer = prtr self.settings = settings self.log = log self.entry = Entry(self, width=50) self.entry.grid(row=1, column=1, columnspan=3, sticky=N+E+W) self.bSend = Button(self, text="Send", width=4, command=self.doSend, state=DISABLED) self.bSend.grid(row=1, column=4, padx=2) self.entry.delete(0, END) self.entry.bind('<Return>', self.hitEnter) self.gcv = StringVar(self) gclist = gcoderef.gcKeys() self.gcv.set(gclist[0]) l = Label(self, text="G Code Reference:", justify=LEFT) l.grid(row=2, column=1, columnspan=2, sticky=W) self.gcm = Combobox(self, textvariable=self.gcv) self.gcm['values'] = gclist self.gcm.grid(row=2, column=3, padx=2) self.gcm.bind('<<ComboboxSelected>>', self.gcodeSel) #self.bInfo = Button(self, text="Info", width=9, command=self.doInfo) #self.bInfo.grid(row=2, column=4, padx=2) #def doInfo(self): def gcodeSel(self, *arg): verb = self.gcv.get() self.log.logMsg("%s: %s" % (verb, gcoderef.gcText(verb))) def activate(self, flag): if flag: self.bSend.config(state=NORMAL) else: self.bSend.config(state=DISABLED) def hitEnter(self, e): self.doSend() def doSend(self): cmd = self.entry.get() verb = cmd.split()[0] if self.app.printerAvailable(cmd=verb): self.log.logMsg("Sending: %s" % cmd) self.printer.send_now(cmd)
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 Login(Frame): def __init__(self, parent): Frame.__init__(self, parent, background="white") self.name = "None" self.proc = Popen(["python", os.path.dirname(os.path.abspath(sys.argv[0]))+ "/" + "discovery.py", self.name], stdout=PIPE, stderr=STDOUT) self.parent = parent self.parent.title("Centered window") self.entrythingy = Entry() self.entrythingy.pack() self.contents = StringVar() self.entrythingy["textvariable"] = self.contents self.entrythingy.bind('<Key-Return>', self.print_contents) self.pack(fill=BOTH, expand=1) self.centerWindow() def print_contents(self, event): name = self.contents.get() if(name): self.name = name q = Queue() t = Thread(target=self.reader_thread, args=[q]).start() # Start network discovery # subprocess.call([os.path.dirname(os.path.abspath(sys.argv[0]))+ "/" + "discovery.sh", name]) # process = Popen("python discovery.py", stdout=PIPE) # stdout, stderr = process.communicate() # # Starts network broadcast # process1 = Popen("python server.py " + name, stdout=PIPE) # stdout, stderr = process1.communicate() self.parent.destroy() def reader_thread(self, q): """Read subprocess output and put it into the queue.""" for line in iter(self.proc.stdout.readline, b''): print(line) print('done reading') def centerWindow(self): w = 290 h = 150 sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - w)/2 y = (sh - h)/2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
def login_gui(username, password): def get_login(evt=None): temp_username = username_holder.get() temp_password = password_holder.get() if remember_login_holder.get(): logon_file = open("dep.dat", "w") logon_file.write(encodestring(temp_username+" "+temp_password)) logon_file.close() elif os.path.isfile("dep.dat"): os.remove("dep.dat") login_tk.destroy() wrap.login(temp_username, temp_password) overview_gui() return def on_checkbox_flip(): if remember_login_holder.get(): logon_file = open("dep.dat", "w") logon_file.write(encodestring(username_holder.get()+" "+password_holder.get())) logon_file.close() else: if os.path.isfile("dep.dat"): os.remove("dep.dat") return login_tk = Tk() login_tk.title("Login Window") Label(login_tk, text="Login to GradeSpeed").pack(padx=50, pady=(10, 5)) Label(login_tk, text="Username:"******"<Key-Return>", get_login) Label(login_tk, text="Password:"******"*") password_field.pack(padx=50, pady=(0, 5)) password_field.bind("<Key-Return>", get_login) remember_login_holder = BooleanVar() remember_login_holder.set(len(username) > 0) login_frame = Frame(login_tk) Checkbutton(login_frame, text="Remember Logon", var=remember_login_holder, command=on_checkbox_flip).pack() login_frame.pack(pady=5) Button(text="Login", command=get_login).pack(padx=50, pady=(5, 10)) center_gui(login_tk) login_tk.mainloop()
def ask_title_and_create_window(self): toplevel = Toplevel() label = Label(toplevel, text="Title:") label.pack(anchor=W) entry = Entry(toplevel, width=15) entry.pack(anchor=W, fill=X) entry.bind("<Return>", lambda event: (self.new_window(entry.get()), toplevel.destroy())) entry.focus() return "break"
def ask_title_and_create_window(self): toplevel = Toplevel() label = Label(toplevel, text="Title:") label.pack(anchor=W) entry = Entry(toplevel, width=15) entry.pack(anchor=W, fill=X) entry.bind( "<Return>", lambda event: (self.new_window(entry.get()), toplevel.destroy())) entry.focus() return "break"
def addStudentOptions(self): identity = ["Student"] studentID = IntVar() label = Label(self, text="Student ID: ") label.grid(row=1, column=0, columnspan=2, padx=1, pady=1, sticky="nsew") entry = Entry(self, textvariable=studentID, width=3) entry.grid(row=1, column=2, padx=1, pady=1, sticky="nsew") def callback(event): try: i = studentID.get() assert i > 0 and i <= 80 except (ValueError, AssertionError): invalidID = Label(self, text="Invalid ID.") invalidID.grid(row=2, column=0, columnspan=3, padx=1, pady=1) else: identity.append(i) self.display(*identity) entry.bind("<Return>", callback)
def ask_captcha_old(fname='./tmp.jpg'): root = Tk() top = Frame(root) top.pack() image=PhotoImage(file=fname) Label(top, image=image).pack(side=TOP) var = StringVar() widget = Entry(top, textvariable=var) widget.focus_force() # Put keyboard focus on Entry def set_code(event=None): captcha = var.get() if len(captcha)>= 2: var.set("") else: root.destroy() widget.bind("<Key-Return>", set_code) widget.pack(side=BOTTOM) root.title(u"验证码:") root.mainloop() return var.get()
def addTeacherOptions(self): identity = ["Teacher"] subject = StringVar() label = Label(self, text="Course: ") label.grid(row=1, column=0, padx=1, pady=1, sticky="nsew") entry = Entry(self, textvariable = subject, width=20) entry.grid(row=1, column=1, columnspan=2, padx=1, pady=1, sticky="nsew") def callback(event): try: course = subject.get() courses = ["Mathematics", "French", "Physics", "Biology", "Sociology", "Programming", "Chemistry", "Music", "English", "History"] assert course in courses except AssertionError: invalidCourse = Label(self, text="Invalid course.") invalidCourse.grid(row=2, column=0, columnspan=2, padx=1, pady=1) else: identity.append(course) self.display(*identity) entry.bind("<Return>", callback)
class Login(Frame): def __init__(self, parent): Frame.__init__(self, parent, background="white") self.parent = parent self.parent.title("Centered window") self.entrythingy = Entry() self.entrythingy.pack() self.contents = StringVar() self.entrythingy["textvariable"] = self.contents self.entrythingy.bind('<Key-Return>', self.print_contents) self.pack(fill=BOTH, expand=1) self.centerWindow() def print_contents(self, event): name = self.contents.get() if(name): # Start network discovery subprocess.call([os.path.dirname(os.path.abspath(sys.argv[0]))+ "/" + "discovery.sh", name]) # process = Popen("python discovery.py", stdout=PIPE) # stdout, stderr = process.communicate() # # Starts network broadcast # process1 = Popen("python server.py " + name, stdout=PIPE) # stdout, stderr = process1.communicate() root.destroy() def centerWindow(self): w = 290 h = 150 sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - w)/2 y = (sh - h)/2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.data = '' self.grid() self.label = Label(self, text='not ready', fg='red') self.label.grid() self.img = ImageTk.PhotoImage(file='a.bmp') #Label(self, image=self.img).grid(side='top') Label(self, image=self.img).grid() self.content = StringVar() self.entry = Entry(self) self.entry.grid() self.entry.config(textvariable=self.content) self.entry.bind('<Key-Return>', self.post) def post(self, event): self.data = self.content.get() self.label['text']='ready' self.label['fg'] = 'green' self.quit() def getdata(self): return self.data
def entry(f, s, width, file=False, fileCheck=False,dir=False, button=None): defaulttext = s.get() def openFileDialog(event): if fileCheck: s.set(tkFileDialog.askopenfilename(parent=f, title='Choose a file')) checkFile() else: s.set(tkFileDialog.asksaveasfilename(parent=f, title='Create file to save data to')) button.bind("<Enter>", lambda event: "break") button.bind("<FocusIn>", lambda event: "break") button.bind("<Leave>", lambda event: "break") button.bind("<FocusOut>", lambda event: "break") button.flash() def openDirDialog(event): s.set(tkFileDialog.askdirectory(title='Choose the output directory', mustexist=True)) if len(s.get()) > 0: e.config(font=Styles.fonts["entryFilled"], bg=Styles.colours["lightGreen"]) else: s.set(defaulttext) button.bind("<Enter>", lambda event: "break") button.bind("<FocusIn>", lambda event: "break") button.bind("<Leave>", lambda event: "break") button.bind("<FocusOut>", lambda event: "break") button.flash() def clearEntry(event): if s.get() == defaulttext: s.set("") event.widget.config(font=Styles.fonts["entryFilled"], foreground=Styles.colours["black"]) def checkFile(): if os.path.isfile(s.get()): e.config(font=Styles.fonts["entryFilled"], bg=Styles.colours["lightGreen"]) else: e.config(font=Styles.fonts["entryFilled"], bg=Styles.colours["lightRed"]) def restoreEntry(event): if s.get() == "": s.set(defaulttext) event.widget.config(font=Styles.fonts["entry"], foreground=Styles.colours["darkGrey"]) elif file: checkFile() e = Entry(f, textvariable=s, font=Styles.fonts["entry"], foreground=Styles.colours["darkGrey"], width=width, relief=FLAT) e.bind("<FocusIn>", clearEntry) e.bind("<FocusOut>", restoreEntry) e.bind("<Button-1>", clearEntry) if button is not None: if file: button.bind("<Button-1>", openFileDialog) if dir: button.bind("<Button-1>", openDirDialog) return e
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()
def start(): #CREATE THE WINDOW global prefstr window = Tkinter.Tk() screen_width = window.winfo_screenwidth() # width of the screen screen_height = window.winfo_screenheight() # height of the screen window.title("EvE Route Optimizer") window.geometry('%dx%d+%d+%d' % (680, 640, (screen_width / 2) - 340, (screen_height / 2) - 320)) window.configure(background='gray') result = ScrolledText.ScrolledText(window, width=60, height=20) result.configure(font=("Arial Bold", 12), fg="white") result.configure(background='black') start_field = Entry(window, width=37, font=("Arial Bold", 12)) end_field = Entry(window, width=37, font=("Arial Bold", 12)) fixed_end_field = Entry(window, width=37, font=("Arial Bold", 12)) iteration_field = Entry(window, width=6, font=("Arial Bold", 12)) start_field.insert(0, "Origin") end_field.insert(0, "Destination") fixed_end_field.insert(0, "Fixed End Point") iteration_field.insert(0, "Cycles") result.pack() start_field.pack() end_field.pack() fixed_end_field.pack() iteration_field.pack() fixed_end_field.configure(state=DISABLED) try: version_url = "https://sites.google.com/site/ustleveonline/route_optimizer_version" version_response = urllib.urlopen(version_url).read() local_version_file = open("route_optimizer_version", "r") local_version = local_version_file.read() if str(local_version) != str(version_response): result.insert( INSERT, "\nAn update for EvE Route Optimizer is available.\n") result.see("end") webbrowser.open( "https://sites.google.com/site/ustleveonline/route-optimizer", new=1, autoraise=True) else: result.insert(INSERT, "\nEvE Route Optimizer is up to date.\n") result.see("end") except: result.insert(INSERT, "\n" + "ERROR: Please check your internet connection!") result.see("end") #ADD A WAYPOINT def add_waypoint(Event=None): global o_system global d_system global waypoint_adding_done waypoint_adding_done = False o_system = start_field.get() d_system = end_field.get() if (o_system != "" and d_system != "" and o_system != "Origin" and d_system != "Destination"): try: number_of_routes = len(routes) start_field.delete(0, 'end') end_field.delete(0, 'end') start_field.insert(0, d_system) create_route(False) if len(routes) > number_of_routes: result.insert( INSERT, "\n" + "Added Route: " + o_system + " to " + d_system) result.see("end") else: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") waypoint_adding_done = True except: result.insert(INSERT, "\n" + "ERROR: Invalid!") result.see("end") #CREATE ROUTE USING GIVEN WAYPOINTS def create_route(optimizing): global routes global waypoints global o_system global d_system global prefstr #GET ORIGIN ID try: o_base = "https://esi.evetech.net/latest/search/?categories=solar_system&search=" o_end = "&strict=true" o_url = o_base + o_system + o_end o_response = urllib.urlopen(o_url).read() o_split_response = o_response.split(":") o_id_section = o_split_response[1] o_id_leftbracket = o_id_section.replace('[', '') o_id_rightbracket = o_id_leftbracket.replace(']', '') o_id_final = o_id_rightbracket.replace('}', '') except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #GET DESTINATION ID try: d_base = "https://esi.evetech.net/latest/search/?categories=solar_system&search=" d_end = "&strict=true" d_url = d_base + d_system + d_end d_response = urllib.urlopen(d_url).read() d_split_response = d_response.split(":") d_id_section = d_split_response[1] d_id_leftbracket = d_id_section.replace('[', '') d_id_rightbracket = d_id_leftbracket.replace(']', '') d_id_final = d_id_rightbracket.replace('}', '') except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #GET ROUTE try: r_base = "https://esi.evetech.net/latest/route/" r_end = "/?datasource=tranquility&flag=" r_type = prefstr r_slash = "/" r_url = r_base + o_id_final + r_slash + d_id_final + r_end + r_type except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #IF THIS ROUTE IS PART OF THE ORIGINAL REQUEST, ADD IT TO THE LIST try: if optimizing == False: r_response = urllib.urlopen(r_url).read() routes.append(r_response) waypoints.append(o_system) else: r_response = urllib.urlopen(r_url).read() return r_response except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #OPTIMIZE THE ROUTE def optimize(): global o_system global d_system global routes global waypoints global optimized_routes global previous_routes global tested_routes global total_routes global final_routes global origins global destinations global initialized global cycles global final_best_route global fixed_endpoint_name result.insert(INSERT, "\n") last_destination = "" last_route = [None] * 10000 best_route = [None] * 10000 sys1 = "" sys2 = "" waypoints.append(d_system) #GET AND DISPLAY THE TOTAL ROUTE DISTANCE IN NUMBER OF JUMPS total_distance = 0 for route in routes: split_route = route.split(",") total_distance += len(split_route) result.insert(INSERT, "\n" + "Number of jumps: " + str(total_distance)) result.see("end") if fixed_endpoint == False: #GET ID FOR THE ORIGIN split_for_origin = routes[0].split(",") first_origin = split_for_origin[0].split("[")[1] #GET ID FOR THE LAST STOP final_route = routes[len(routes) - 1] split_final_route = final_route.split(",") last_stop = split_final_route[len(split_final_route) - 1].split("]")[0] try: #CONVERT ID TO NAME FOR ORIGIN first_begin_url = "https://esi.evetech.net/latest/universe/systems/" first_end_url = "/?datasource=tranquility&language=en-us" first_final_url = first_begin_url + first_origin + first_end_url first_response = urllib.urlopen(first_final_url).read() first_final_origin = first_response.split(":")[2].split( ",")[0].replace('"', "") d_system = first_final_origin #CONVERT ID TO NAME FOR DESTINATION endpoint_begin_url = "https://esi.evetech.net/latest/universe/systems/" endpoint_end_url = "/?datasource=tranquility&language=en-us" endpoint_final_url = endpoint_begin_url + last_stop + endpoint_end_url endpoint_response = urllib.urlopen(endpoint_final_url).read() endpoint_final_response = endpoint_response.split( ":")[2].split(",")[0].replace('"', "") o_system = endpoint_final_response except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #GET AND DISPLAY THE TOTAL ROUTE DISTANCE INCLUDING RETURN TO ORIGIN return_route = create_route(True) return_distance = len(return_route.split(",")) result.insert( INSERT, "\n" + "Including return to origin: " + str(total_distance + return_distance) + "\n") result.see("end") else: #SET DESTINATION TO THE FIXED ENDPOINT if fixed_endpoint_name != "" and fixed_endpoint_name != "Fixed End Point": try: d_system = fixed_endpoint_name except: result.insert(INSERT, "\n" + "ERROR: Invalid Fixed End Point!") result.see("end") #GET THE ID FOR THE LAST STOP final_route = routes[len(final_routes) - 1] split_final_route = final_route.split(",") last_stop = split_final_route[len(split_final_route) - 1].split("]")[0] try: #CONVERT ID TO NAME FOR DESTINATION endpoint_begin_url = "https://esi.evetech.net/latest/universe/systems/" endpoint_end_url = "/?datasource=tranquility&language=en-us" endpoint_final_url = endpoint_begin_url + last_stop + endpoint_end_url endpoint_response = urllib.urlopen(endpoint_final_url).read() endpoint_final_response = endpoint_response.split( ":")[2].split(",")[0].replace('"', "") o_system = endpoint_final_response except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #GET AND DISPLAY THE TOTAL TRIP DISTANCE INCLUDING RETURN TO ORIGIN return_route = create_route(True) return_distance = len(return_route.split(",")) result.insert( INSERT, "\n" + "Including fixed end point: " + str(total_distance + return_distance) + "\n") result.see("end") try: cycles = int(iteration_field.get()) except: cycles = 1 count = 0 while count < cycles: count += 1 result.insert(INSERT, "\nCycle " + str(count) + ":\n") result.see("end") for route in routes: try: #CONVERT ID TO NAME FOR ORIGIN split_route = route.split(",") origin = split_route[0].split("[")[1] begin_url = "https://esi.evetech.net/latest/universe/systems/" end_url = "/?datasource=tranquility&language=en-us" final_url = begin_url + origin + end_url response = urllib.urlopen(final_url).read() final_origin = response.split(":")[2].split( ",")[0].replace('"', "") o_system = final_origin except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #ADD THE ORIGIN AS A DESTINATION SO IT'S NOT INCLUDED IN POTENTIAL ROUTES if initialized == False: destinations.append(o_system) initialized = True last_destination = o_system #WHEN THE ROUTE IS CHANGED, THE PREVIOUS WAYPOINT MUST BE UPDATED elif o_system != last_destination: o_system = last_destination #RESET THE BOOLEAN VALUES FOR ROUTE UPDATES optimized = False passed = False result.insert( INSERT, "\n" + "Finding the shortest route from " + o_system + " to another waypoint.\n") result.see("end") for waypoint in waypoints: if o_system != waypoint and passed == False: #PREVENT ROUTING TO THE CURRENT SYSTEM d_system = waypoint potential_route = create_route( True ) #CREATE A ROUTE TO GET THE LENGTH IN NUMBER OF JUMPS split_pot = potential_route.split(",") #FIND THE SHORTEST ROUTE FROM THE CURRENT LOCATION TO ANOTHER LOCATION IN THE LIST if optimized == True: split_best = best_route.split(",") if d_system not in destinations and o_system not in origins and len( best_route ) != 10000 and potential_route not in tested_routes: result.insert( INSERT, "\nChecking route " + str(o_system) + " to " + str(d_system) + ": " + str(len(split_pot)) + " jumps. Best found: " + str(len(split_best)) + " jumps.") result.see("end") if len(split_pot) < len( split_best ) and d_system not in destinations and o_system not in origins: best_route = potential_route sys1 = o_system sys2 = d_system elif len(split_pot) == len( split_best ) and d_system not in destinations and o_system not in origins: passed = True optimized = False else: if len(split_pot) < len( last_route ) and d_system not in destinations and o_system not in origins: if d_system not in destinations and o_system not in origins and len( best_route ) != 10000 and potential_route not in tested_routes: result.insert( INSERT, "\nChecking route " + str(o_system) + " to " + str(d_system) + ": " + str(len(split_pot)) + " jumps. Best found: " + str(len(last_route)) + " jumps.") result.see("end") best_route = potential_route sys1 = o_system sys2 = d_system optimized = True elif len(split_pot) == len( last_route ) and d_system not in destinations and o_system not in origins: passed = True optimized = False else: last_route = split_pot #OPTIMAL ROUTE WAS FOUND if optimized == True: result.insert( INSERT, "\n\n" + "Optimized route: " + sys1 + " to " + sys2 + "\n") result.see("end") optimized_routes.append(best_route) origins.append(sys1) destinations.append(sys2) last_destination = sys2 #OPTIMAL ROUTE WAS NOT FOUND, SO THE NEXT WAYPOINT IN THE LIST IS USED elif optimized == False: finished = False for waypoint in waypoints: if finished == False: if o_system != waypoint and waypoint not in destinations: #GET THE FIRST UNUSED WAYPOINT d_system = waypoint potential_route = create_route(True) if potential_route not in tested_routes: #THIS ROUTE HAS NOT YET BEEN EXAMINED tested_routes.append(potential_route) optimized_routes.append(potential_route) result.insert( INSERT, "\n\n" + "No exceptional route found. Creating route: " + o_system + " to " + d_system + "\n") result.see("end") origins.append(o_system) destinations.append(d_system) last_destination = d_system finished = True if finished == False: #ALL POSSIBLE ROUTES HAVE BEEN EXAMINED FOR THIS WAYPOINT SO THE SHORTEST ONE IS SELECTED previous_best_route = [None] * 10000 best_tested_route = [] for route in tested_routes: split_route = str(route).split(",") origin = split_route[0].split("[")[1] try: o_begin_url = "https://esi.evetech.net/latest/universe/systems/" o_end_url = "/?datasource=tranquility&language=en-us" o_final_url = o_begin_url + origin + o_end_url o_response = urllib.urlopen(o_final_url).read() o_final_response = o_response.split( ":")[2].split(",")[0].replace('"', "") except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!" ) result.see("end") if o_final_response == o_system: if len(previous_best_route) != 10000: result.insert( INSERT, "\n" + "Comparing potential routes for this waypoint: " + str(len(split_route)) + " jumps VS " + str(len(previous_best_route)) + " jumps.") result.see("end") s_destination = split_route[len(split_route) - 1].split("]")[0] try: s_d_begin_url = "https://esi.evetech.net/latest/universe/systems/" s_d_end_url = "/?datasource=tranquility&language=en-us" s_d_final_url = s_d_begin_url + s_destination + s_d_end_url s_d_response = urllib.urlopen( s_d_final_url).read() s_d_final_response = s_d_response.split( ":")[2].split(",")[0].replace('"', "") except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!" ) result.see("end") if s_d_final_response not in destinations and len( split_route) < len( previous_best_route): best_tested_route = route previous_best_route = split_route split_best_route = str(best_tested_route).split(",") origin = split_best_route[0].split("[")[1] destination = split_best_route[len(split_best_route) - 1].split("]")[0] try: o_begin_url = "https://esi.evetech.net/latest/universe/systems/" o_end_url = "/?datasource=tranquility&language=en-us" o_final_url = o_begin_url + origin + o_end_url o_response = urllib.urlopen(o_final_url).read() t_o_final_response = o_response.split( ":")[2].split(",")[0].replace('"', "") d_begin_url = "https://esi.evetech.net/latest/universe/systems/" d_end_url = "/?datasource=tranquility&language=en-us" d_final_url = d_begin_url + destination + d_end_url d_response = urllib.urlopen(d_final_url).read() t_d_final_response = d_response.split( ":")[2].split(",")[0].replace('"', "") except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!" ) result.see("end") optimized_routes.append(best_tested_route) result.insert( INSERT, "\n\n" + "All possible routes considered. Using route: " + t_o_final_response + " to " + t_d_final_response + "\n") result.see("end") origins.append(t_o_final_response) destinations.append(t_d_final_response) last_destination = t_d_final_response finished = True total_routes.append(optimized_routes) previous_routes = optimized_routes optimized_routes = [] origins = [] destinations = [] optimized = False initialized = False #SELECT THE BEST ROUTE FROM ALL CYCLES previous_best_distance = 10000 for route in total_routes: total_route_distance = 0 for r in route: s_r = r.split(",") total_route_distance += len(s_r) if previous_best_distance != 10000: result.insert( INSERT, "\n" + "Comparing optimized routes: " + str(total_route_distance) + " jumps VS " + str(previous_best_distance) + " jumps.") result.see("end") if total_route_distance < previous_best_distance: final_best_route = route previous_best_distance = total_route_distance #DISPLAY THE OPTIMIZED ROUTE previous_destination = "" for route in final_best_route: split_route = str(route).split(",") origin = split_route[0].split("[")[1] destination = split_route[len(split_route) - 1].split("]")[0] #CONVERT THE ID TO NAME FOR EACH ROUTE try: o_begin_url = "https://esi.evetech.net/latest/universe/systems/" o_end_url = "/?datasource=tranquility&language=en-us" o_final_url = o_begin_url + origin + o_end_url o_response = urllib.urlopen(o_final_url).read() o_final_response = o_response.split(":")[2].split( ",")[0].replace('"', "") d_begin_url = "https://esi.evetech.net/latest/universe/systems/" d_end_url = "/?datasource=tranquility&language=en-us" d_final_url = d_begin_url + destination + d_end_url d_response = urllib.urlopen(d_final_url).read() d_final_response = d_response.split(":")[2].split( ",")[0].replace('"', "") #SET THE CURRENT SYSTEM TO INITIALIZE ITERATION if previous_destination == "": previous_destination = o_final_response result.insert(INSERT, "\n\n" + "New Route:" + "\n") result.see("end") #SET THE CURRENT SYSTEM TO THE PREVIOUS DESTINATION if o_final_response == previous_destination: final_routes.append(route) previous_destination = d_final_response result.insert( INSERT, "\n" + o_final_response + " to " + d_final_response) result.see("end") else: #THIS IS FOR DEBUGGING AND SHOULD NEVER HAPPEN result.insert( INSERT, "\n" + "ERROR: Out of order! " + o_final_response + ":" + d_final_response) result.see("end") except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #GET AND DISPLAY THE TOTAL TRIP DISTANCE IN NUMBER OF JUMPS total_distance = 0 for route in final_routes: split_route = route.split(",") total_distance += len(split_route) result.insert(INSERT, "\n\n" + "Number of jumps: " + str(total_distance)) result.see("end") if fixed_endpoint == False: #GET THE ID FOR THE ORIGIN split_for_origin = final_routes[0].split(",") first_origin = split_for_origin[0].split("[")[1] #GET THE ID FOR THE LAST STOP final_route = final_routes[len(final_routes) - 1] split_final_route = final_route.split(",") last_stop = split_final_route[len(split_final_route) - 1].split("]")[0] try: #CONVERT ID TO NAME FOR ORIGIN first_begin_url = "https://esi.evetech.net/latest/universe/systems/" first_end_url = "/?datasource=tranquility&language=en-us" first_final_url = first_begin_url + first_origin + first_end_url first_response = urllib.urlopen(first_final_url).read() first_final_origin = first_response.split(":")[2].split( ",")[0].replace('"', "") d_system = first_final_origin #CONVERT ID TO NAME FOR DESTINATION endpoint_begin_url = "https://esi.evetech.net/latest/universe/systems/" endpoint_end_url = "/?datasource=tranquility&language=en-us" endpoint_final_url = endpoint_begin_url + last_stop + endpoint_end_url endpoint_response = urllib.urlopen(endpoint_final_url).read() endpoint_final_response = endpoint_response.split( ":")[2].split(",")[0].replace('"', "") o_system = endpoint_final_response except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #GET AND DISPLAY THE TOTAL TRIP DISTANCE INCLUDING RETURN TO ORIGIN return_route = create_route(True) return_distance = len(return_route.split(",")) result.insert( INSERT, "\n" + "Including return to origin: " + str(total_distance + return_distance) + "\n") result.see("end") else: #SET DESTINATION TO THE FIXED ENDPOINT d_system = fixed_endpoint_name #GET THE ID FOR THE LAST STOP final_route = final_routes[len(final_routes) - 1] split_final_route = final_route.split(",") last_stop = split_final_route[len(split_final_route) - 1].split("]")[0] try: #CONVERT ID TO NAME FOR DESTINATION endpoint_begin_url = "https://esi.evetech.net/latest/universe/systems/" endpoint_end_url = "/?datasource=tranquility&language=en-us" endpoint_final_url = endpoint_begin_url + last_stop + endpoint_end_url endpoint_response = urllib.urlopen(endpoint_final_url).read() endpoint_final_response = endpoint_response.split( ":")[2].split(",")[0].replace('"', "") o_system = endpoint_final_response except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #GET AND DISPLAY THE TOTAL TRIP DISTANCE INCLUDING RETURN TO ORIGIN return_route = create_route(True) return_distance = len(return_route.split(",")) result.insert( INSERT, "\n" + "Including fixed end point: " + str(total_distance + return_distance) + "\n") result.see("end") #RESET VARIABLES SO ANOTHER SET OF WAYPOINTS CAN BE ENTERED previous_routes = [] total_routes = [] tested_routes = [] final_best_route = [] routes = [] optimized_routes = [] final_routes = [] waypoints = [] o_system = "" d_system = "" origins = [] destinations = [] initialized = False start_field.delete(0, 'end') end_field.delete(0, 'end') start_field.insert(0, "Origin") end_field.insert(0, "Destination") result.insert(INSERT, "\n") result.see("end") #START THE OPTIMIZATION THREAD def begin_optimization(): global waypoint_adding_done if waypoint_adding_done == True: optimization_thread = threading.Thread(target=optimize) optimization_thread.start() #CHANGE THE ROUTE PREFERENCE def change_preference(): global prefstr if preference.get() == 1: prefstr = "shortest" if preference.get() == 2: prefstr = "secure" if preference.get() == 3: prefstr = "insecure" #CHANGE THE FIXED ENDPOINT def set_fixed_endpoint(): global fixed_endpoint_name global fixed_endpoint if fixed.get() == 1: fixed_endpoint = True fixed_end_field.configure(state=NORMAL) else: fixed_endpoint = False fixed_end_field.configure(state=DISABLED) #FINALIZE FIXED ENDPOINT def lock_fixed_endpoint(Event=None): global fixed_endpoint_name fixed_endpoint_name = fixed_end_field.get() fixed_end_field.configure(state=DISABLED) #SETUP BUTTONS fixed = IntVar() fixed_end_button = Checkbutton(window, text="Fixed End-Point", variable=fixed, command=set_fixed_endpoint, onvalue=1, offvalue=0, bg="gray", font=("Arial Bold", 12)) fixed_end_button.pack() preference = IntVar() R1 = Radiobutton(window, text="Shortest", variable=preference, value=1, command=change_preference, bg="gray", font=("Arial Bold", 12)) R1.pack() R2 = Radiobutton(window, text="Secure", variable=preference, value=2, command=change_preference, bg="gray", font=("Arial Bold", 12)) R2.pack() R3 = Radiobutton(window, text="Insecure", variable=preference, value=3, command=change_preference, bg="gray", font=("Arial Bold", 12)) R3.pack() button = Button(window, text="Optimize", font=("Arial Bold", 12), bg="gray", fg="blue", command=begin_optimization) button.pack() end_field.bind( "<Return>", add_waypoint ) #ALLOWS THE RETURN KEY TO ADD A WAYPOINT INSTEAD OF CLICKING THE BUTTON fixed_end_field.bind("<Return>", lock_fixed_endpoint) window.mainloop()
class Tk_Table(Frame, object): def __init__(self, master, columns, data=None, command=None, editable=True, sort=True, select_mode=None, autoscroll=True, vscrollbar=True, hscrollbar=False, heading_anchor = CENTER, cell_anchor=W, style=None, scrollbar_background=None, scrollbar_troughcolor=None, height=None, padding=None, adjust_heading_to_content=False, stripped_rows=None, selection_background=None, selection_foreground=None, cell_background=None, cell_foreground=None, cell_font=None, field_background=None, heading_font= None, heading_background=None, heading_foreground=None, cell_pady=2, column_header=True, row_numbers=True, entry_background="#d6d6d6", entry_foreground=None, entry_validatecommand=None, entry_selectbackground="#1BA1E2", entry_selectborderwidth=None, entry_selectforeground=None, entry_font = "TkDefaultFont", rowlabel_anchor=E, rowlabel_minwidth=0, rowlabel_hoverbackground="#FFFFFF",frame_relief=None, frame_borderwidth=None, frame_background=None): frame_kwargs = {} if frame_relief is not None: frame_kwargs["relief"] = frame_relief if frame_borderwidth is not None: frame_kwargs["borderwidth"] = frame_borderwidth if frame_background is not None: frame_kwargs["background"] = frame_background Frame.__init__(self, master, class_="Multicolumn_Listbox", **frame_kwargs) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(1, weight=1) self._multicolumn_listbox = Multicolumn_Listbox(self, columns, data=data, command=command, sort=sort, select_mode=select_mode, heading_anchor = heading_anchor, cell_anchor=cell_anchor, style=style, height=height, padding=padding, adjust_heading_to_content=adjust_heading_to_content, stripped_rows=stripped_rows, selection_background=selection_background, selection_foreground=selection_foreground, cell_background=cell_background, cell_foreground=cell_foreground, cell_font=cell_font, field_background=field_background, heading_font=heading_font, heading_background=heading_background, heading_foreground=heading_foreground, cell_pady=cell_pady, headers=column_header) self._multicolumn_listbox.interior.grid(row=0, column=1, sticky= N+E+W+S) self._mousewheel_detection = True if row_numbers: self._row_numbers = Row_Header(self, font=self._multicolumn_listbox.font, row_height=self._multicolumn_listbox.row_height, row_minwidth=rowlabel_minwidth, hover_background = rowlabel_hoverbackground, anchor=rowlabel_anchor, onclick=self._on_click_row_label) self._row_numbers.grid(row=0, column=0, sticky= N+S+E) self._multicolumn_listbox.interior.bind("<Map>", self._place_vertically_row_numbers) else: self._row_numbers = None if editable: self._selected_cell = None self._entry_popup = None self._multicolumn_listbox.interior.bind("<1>", self._edit_cell) def configure(event): """ if self._entry_popup: self._entry_popup.destroy() return """ self._multicolumn_listbox.interior.update_idletasks() self._update_position_of_entry() self._multicolumn_listbox.interior.bind("<Configure>", configure) self._entry_kwargs = entry_kwargs = {} if entry_background is not None: entry_kwargs["background"] = entry_background if entry_foreground is not None: entry_kwargs["foreground"] = entry_foreground if entry_validatecommand is not None: entry_kwargs["validatecommand"] = entry_validatecommand if entry_selectbackground is not None: entry_kwargs["selectbackground"] = entry_selectbackground if entry_selectforeground is not None: entry_kwargs["selectforeground"] = entry_selectforeground if entry_font is not None: entry_kwargs["font"] = entry_font if command is not None: self._command = command self._multicolumn_listbox.interior.bind("<<TreeviewSelect>>", self._on_select) scrollbar_kwargs = {} if scrollbar_background is not None: scrollbar_kwargs["background"] = scrollbar_background if scrollbar_troughcolor is not None: scrollbar_kwargs["throughcolor"] = scrollbar_troughcolor if vscrollbar: if editable: if row_numbers: def yview_command(*args): self._multicolumn_listbox.interior.yview(*args) self._row_numbers.yview(*args) self._update_position_of_entry() else: def yview_command(*args): self._multicolumn_listbox.interior.yview(*args) self._update_position_of_entry() else: if row_numbers: def yview_command(*args): self._multicolumn_listbox.interior.yview(*args) self._row_numbers.yview(*args) else: yview_command = self._multicolumn_listbox.interior.yview self._vbar=Scrollbar(self,takefocus=0, command=yview_command, **scrollbar_kwargs) self._vbar.grid(row=0, column=2, sticky= N+S) def yscrollcommand(first,last): first, last = float(first), float(last) if first <= 0 and last >= 1: if self._mousewheel_detection: if autoscroll: self._vbar.grid_remove() if row_numbers: unbind_function_onMouseWheel(self._multicolumn_listbox.interior) self._mousewheel_detection = False else: if not self._mousewheel_detection: if autoscroll: self._vbar.grid() if row_numbers: bind_function_onMouseWheel(self._row_numbers, "y", binding_widget=self._multicolumn_listbox.interior, unit="pages") self._mousewheel_detection = True self._vbar.set(first, last) if editable: self._update_position_of_entry() self._multicolumn_listbox.interior.config(yscrollcommand=yscrollcommand) if hscrollbar: if editable: def xview_command(*args): self._multicolumn_listbox.interior.xview(*args) self._update_position_of_entry() else: xview_command = self._multicolumn_listbox.interior.xview self._hbar=Scrollbar(self,takefocus=0, command=xview_command, **scrollbar_kwargs) self._hbar.grid(row=1, column=1, sticky= E+W) if autoscroll: if editable: def xscrollcommand(f,l, self=self): make_autoscroll(self._hbar, f, l) self._update_position_of_entry() else: def xscrollcommand(f,l, hbar=self._hbar): make_autoscroll(hbar, f, l) self._multicolumn_listbox.interior.config(xscrollcommand=xscrollcommand) else: self._multicolumn_listbox.interior.config(xscrollcommand=self._hbar.set) def _place_vertically_row_numbers(self, event): self._multicolumn_listbox.interior.unbind("<Map>") item_ID = self._multicolumn_listbox.interior.insert('', 0, values=[""]*self._multicolumn_listbox.number_of_columns) self._multicolumn_listbox.interior.update() x,y,w,h = self._multicolumn_listbox.interior.bbox(item_ID) self._multicolumn_listbox.interior.delete(item_ID) self._row_numbers.grid_configure(pady=(y,0)) def _edit_cell(self, event): '''Executed, when a row is clicked. Opens an entry popup above the cell, so it is possible to select text ''' # close previous popups if self._entry_popup: self._destroy_entry() # what row and column was clicked on item_ID = self._multicolumn_listbox.interior.identify_row(event.y) if not item_ID: return column = self._multicolumn_listbox.interior.identify_column(event.x) if column == "": return # get column position info x,y,width,height = self._multicolumn_listbox.interior.bbox(item_ID, column) # place Entry popup properly column_number = int(column[1:])-1 cell_data = self._multicolumn_listbox.item_ID_to_row_data(item_ID)[column_number] self._entry_popup = Entry(self._multicolumn_listbox.interior, exportselection=True, borderwidth=0, **self._entry_kwargs) self._entry_popup.place(x=x, y=y, width=width, height=height) self._entry_popup.insert(0, cell_data) self._entry_popup.focus_force() self._entry_popup.bind("<Control-a>", lambda event: self._select_all_entry_data) self._entry_popup.bind("<Escape>", lambda event: self._destroy_entry()) self._entry_popup.bind("<FocusOut>", lambda event: self._destroy_entry()) bind_function_onMouseWheel(self._multicolumn_listbox.interior, "y", binding_widget=self._entry_popup, callback=self._update_position_of_entry, unit="pages") if self._row_numbers: bind_function_onMouseWheel(self._row_numbers, "y", binding_widget=self._entry_popup, unit="pages") self._entry_popup.bind("<Return>", self._on_update_cell) self._selected_cell = item_ID, column, column_number def _on_click_row_label(self, index): if self._selected_cell and self._multicolumn_listbox.item_ID(index) == self._selected_cell[0]: self._destroy_entry() self._multicolumn_listbox.toogle_selection(index) def _select_all_entry_data(self): ''' Set selection on the whole text ''' self._entry_popup.selection_range(0, 'end') # returns 'break' to interrupt default key-bindings return 'break' def _destroy_entry(self): self._entry_popup.destroy() self._entry_popup = None self._selected_cell = None def _on_update_cell(self, event): item_ID, column, column_number = self._selected_cell data = self._entry_popup.get() row_data = self._multicolumn_listbox.item_ID_to_row_data(item_ID) row_data[column_number] = data self._multicolumn_listbox.interior.item(item_ID, values=row_data) self._destroy_entry() def _update_position_of_entry(self): if self._selected_cell: bbox = self._multicolumn_listbox.interior.bbox(self._selected_cell[0], self._selected_cell[1]) if bbox == "": self._entry_popup.place_forget() else: x,y,width,height = bbox self._entry_popup.place(x=x, y=y, width=width, height=height) def configure_column(self, index, width=None, minwidth=None, anchor=None, stretch=None): self._multicolumn_listbox.configure_column(self, index, width=None, minwidth=None, anchor=None, stretch=None) def row_data(self, index): return self._multicolumn_listbox.row_data(index) def update_row(self, index, data): self._multicolumn_listbox.update_row(index,data) def delete_row(self, index): self._multicolumn_listbox.delete_row(index) if self._row_numbers: self._row_numbers.pop() def insert_row(self, data, index=None): self._multicolumn_listbox.insert_row(data, index) if self._row_numbers: self._row_numbers.new_label() def column_data(self, index): return self._multicolumn_listbox.column_data(index) def update_column(self, index, data): self._multicolumn_listbox.update_column(index, data) def clear(self): self._multicolumn_listbox.clear() if self._row_numbers: self._row_numbers.delete_labels() def update(self, data): current_number_of_rows = self._multicolumn_listbox.number_of_rows self._multicolumn_listbox.update(data) if self._row_numbers: number_of_rows = len(data) if current_number_of_rows < number_of_rows: for i in range(number_of_rows - current_number_of_rows): self._row_numbers.new_label() else: n_labels = current_number_of_rows - number_of_rows self._row_numbers.pop(n_labels =n_labels) def focus(self, index=None): self._multicolumn_listbox.focus(index) def state(self, state=None): self._multicolumn_listbox.state(state) @property def number_of_rows(self): return self._multicolumn_listbox.number_of_rows @property def number_of_columns(self): return self._multicolumn_listbox.number_of_columns def toogle_selection(self, index): self._multicolumn_listbox.toogle_selection(index) def select_row(self, index): self._multicolumn_listbox.select_row(index) def deselect_row(self, index): self._multicolumn_listbox.deselect_row(index) def deselect_all(self): self._multicolumn_listbox.deselect_all() def set_selection(self, indices): self._multicolumn_listbox.set_selection(indices) @property def selected_rows(self): return self._multicolumn_listbox.selected_rows @property def indices_of_selected_rows(self): return self._multicolumn_listbox.indices_of_selected_rows def delete_all_selected_rows(self): number_of_deleted_rows = self._multicolumn_listbox.delete_all_selected_rows() if self._row_numbers: self._row_numbers.pop(n_labels=number_of_deleted_rows) @property def table_data(self): return self._multicolumn_listbox.table_data @table_data.setter def table_data(self, data): self.update(data) def cell_data(self, row, column): return self._multicolumn_listbox.cell_data(row, column) def update_cell(self, row, column, value): self._multicolumn_listbox.update_cell(row, column, value) def __getitem__(self, index): return self._multicolumn_listbox[index] def __setitem__(self, index, value): self._multicolumn_listbox[index] = value def bind(self, event, handler): self._multicolumn_listbox.bind(event, handler) def sort_by(self, col, descending): self._multicolumn_listbox.sort_by(col, descending)
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 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 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)
def gui(): from Tkinter import Tk, Label, Entry, Button, Scale, Checkbutton, W, HORIZONTAL, Frame, StringVar, IntVar, DoubleVar, Radiobutton, BooleanVar, E global root root = Tk() root.wm_title("Compute R_complete") line = 0 global insFile, hklFile, nHKL, nParams, nHKLLabel, fracFree, status, nParamsLabel, nCPU, rCompleteLabel, cycles, lsType, cleanup, nFree, nRunsLabel, mergeCheck, compileMap insFile = StringVar() hklFile = StringVar() nHKL = IntVar() nParams = IntVar() nFree = IntVar() fracFree = DoubleVar() fracFree.set(5.0) nCPU = IntVar() nCPU.set(maxCPU) cycles = IntVar() cycles.set(10) lsType = IntVar() lsType.set(1) cleanup = BooleanVar() cleanup.set(True) mergeCheck = BooleanVar() mergeCheck.set(True) compileMap = BooleanVar() compileMap.set(True) Label(root, text='Instruction File:').grid(row=line, column=0, sticky=E) Entry(root, textvariable=insFile).grid(row=line, column=1) Button(root, text='Browse', command=browseINS).grid(row=line, column=2) line += 1 Label(root, text='Reflection File:').grid(row=line, column=0, sticky=E) Entry(root, textvariable=hklFile).grid(row=line, column=1) Button(root, text='Browse', command=browseHKL).grid(row=line, column=2) line += 1 Checkbutton(root, var=mergeCheck, text='Merge Reflections').grid(row=line, column=1, sticky=W) line += 1 Button(root, text='Load', command=load).grid(row=line, columnspan=3) line += 1 Frame(root, height=20).grid(row=line) line += 1 Label(root, text='# of reflections:').grid(row=line, sticky=E) nHKLLabel = Label(root, text='???') nHKLLabel.grid(row=line, column=1, sticky=W) line += 1 Label(root, text='# of atoms:').grid(row=line, sticky=E) nParamsLabel = Label(root, text='???') nParamsLabel.grid(row=line, column=1, sticky=W) line += 1 Frame(root, height=20).grid(row=line) line += 1 Label(root, text='Select Parameters').grid(row=line, column=1) line += 1 Frame(root, height=20).grid(row=line) line += 1 Label(root, text='# of free reflections:').grid(row=line, sticky=E) nFreeEntry = Entry(root, width=5, textvariable=nFree) nFreeEntry.grid(row=line, column=1, sticky=W) nFreeEntry.bind('<Return>', setScale) nRunsLabel = Label(root, text='# runs') nRunsLabel.grid(row=line, column=2) line += 1 Label(root, text='% of free reflections:').grid(row=line, column=0, sticky=E) w = Scale(root, from_=0.1, to=10.0, resolution=0.1, orient=HORIZONTAL, length=200, var=fracFree, command=percentScale) w.grid(row=line, column=1, columnspan=2, sticky=W) line += 1 Label(root, text='stable <-------------------------------> fast').grid( row=line, column=1, columnspan=2, sticky=W) line += 1 Frame(root, height=10).grid(row=line) line += 1 Label(root, text='Refinement cycles:').grid(row=line, column=0, sticky=E) ls = Scale(root, from_=0, to=50, resolution=1, orient=HORIZONTAL, length=200, var=cycles) ls.grid(row=line, column=1, columnspan=2, sticky=W) line += 1 Label(root, text='fast <--------------------> less model bias').grid( row=line, column=1, columnspan=2, sticky=W) line += 1 Frame(root, height=10).grid(row=line) line += 1 Label(root, text='# of CPUs:').grid(row=line, column=0, sticky=E) ww = Scale(root, from_=1, to=maxCPU, orient=HORIZONTAL, length=200, var=nCPU) ww.grid(row=line, column=1, columnspan=2, sticky=W) line += 1 Label(root, text='Refinement Type:').grid(row=line, column=0, sticky=E) Radiobutton(root, text='CGLS', var=lsType, value=1).grid(row=line, column=1, sticky=W) Radiobutton(root, text='L.S.', var=lsType, value=2).grid(row=line, column=2, sticky=W) line += 1 Frame(root, height=10).grid(row=line) line += 1 Label(root, text='Compile map:').grid(row=line, column=0, sticky=E) Checkbutton(root, var=compileMap).grid(row=line, column=1, sticky=W) line += 1 Label(root, text='Cleanup:').grid(row=line, column=0, sticky=E) Checkbutton(root, var=cleanup).grid(row=line, column=1, sticky=W) line += 1 Button(root, text='RUN', command=run, width=25).grid(row=line, columnspan=3) line += 1 Frame(root, height=20).grid(row=line) line += 1 Label(root, text='R_complete:').grid(row=line, column=0, sticky=E) rCompleteLabel = Label(root, text='???') rCompleteLabel.grid(row=line, column=1, sticky=W) line += 1 Frame(root, height=20).grid(row=line) line += 1 Label(root, text='Status:').grid(row=line, column=0, sticky=E) status = Label(root, text='Idle... Please load files.') status.grid(row=line, column=1, columnspan=2, sticky=W) global IDLE IDLE = True root.mainloop()
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 Chatbox(object): def __init__(self, master, my_nick=None, command=None, topic=None, entry_controls=None, maximum_lines=None, timestamp_template=None, scrollbar_background=None, scrollbar_troughcolor=None, history_background=None, history_font=None, history_padx=None, history_pady=None, history_width=None, entry_font=None, entry_background=None, entry_foreground=None, label_template=u"{nick}", label_font=None, logging_file=None, tags=None): self.interior = Frame(master, class_="Chatbox") self._command = command self._is_empty = True self._maximum_lines = maximum_lines self._timestamp_template = timestamp_template self._command = command self._label_template = label_template self._logging_file = logging_file if logging_file is None: self._log = None else: try: self._log = open(logging_file, "r") except: self._log = None top_frame = Frame(self.interior, class_="Top") top_frame.pack(expand=True, fill=BOTH) self._textarea = Text(top_frame, state=DISABLED) self._vsb = Scrollbar(top_frame, takefocus=0, command=self._textarea.yview) self._vsb.pack(side=RIGHT, fill=Y) self._textarea.pack(side=RIGHT, expand=YES, fill=BOTH) self._textarea["yscrollcommand"] = self._vsb.set entry_frame = Frame(self.interior, class_="Chatbox_Entry") entry_frame.pack(fill=X, anchor=N) if entry_controls is not None: controls_frame = Frame(entry_frame, class_="Controls") controls_frame.pack(fill=X) entry_controls(controls_frame, chatbox=self) bottom_of_entry_frame = Frame(entry_frame) self._entry_label = Label(bottom_of_entry_frame) self._entry = Entry(bottom_of_entry_frame) else: self._entry_label = Label(entry_frame) self._entry = Entry(entry_frame) self._entry.pack(side=LEFT, expand=YES, fill=X) self._entry.bind("<Return>", self._on_message_sent) self._entry.focus() if history_background: self._textarea.configure(background=history_background) if history_font: self._textarea.configure(font=history_font) if history_padx: self._textarea.configure(padx=history_padx) if history_width: self._textarea.configure(width=history_width) if history_pady: self._textarea.configure(pady=history_pady) if scrollbar_background: self._vsb.configure(background=scrollbar_background) if scrollbar_troughcolor: self._vsb.configure(troughcolor=scrollbar_troughcolor) if entry_font: self._entry.configure(font=entry_font) if entry_background: self._entry.configure(background=entry_background) if entry_foreground: self._entry.configure(foreground=entry_foreground) if label_font: self._entry_label.configure(font=label_font) if tags: for tag, tag_config in tags.items(): self._textarea.tag_config(tag, **tag_config) self.set_nick(my_nick) @property def topic(self): return @topic.setter def topic(self, topic): return def focus_entry(self): self._entry.focus() def bind_entry(self, event, handler): self._entry.bind(event, handler) def bind_textarea(self, event, handler): self._textarea.bind(event, handler) def bind_tag(self, tagName, sequence, func, add=None): self._textarea.tag_bind(tagName, sequence, func, add=add) def focus(self): self._entry.focus() def user_message(self, nick, content): if self._timestamp_template is None: self._write((u"%s:" % nick, "nick"), " ", (content, "user_message")) else: timestamp = datetime.datetime.now().strftime( self._timestamp_template) self._write((timestamp, "timestamp"), " ", (u"%s:" % nick, "nick"), " ", (content, "user_message")) def notification_message(self, content, tag=None): if tag is None: tag = "notification" self._write((content, tag)) notification = notification_message def notification_of_private_message(self, content, from_, to): if self._timestamp_template is None: self.notification_message( u"{from_} -> {to}: {content}".format(from_=from_, to=to, content=content), "notification_of_private_message") else: timestamp = datetime.datetime.now().strftime( self._timestamp_template) self.notification_message( u"{timestamp} {from_} -> {to}: {content}".format( timestamp=timestamp, from_=from_, to=to, content=content), "notification_of_private_message") def new_message(self, message): if isinstance(message, User_Message): self.user_message(message.content, message.nick) elif isinstance(message, Notification_Message): self.notification(message.content, message.tag) elif isinstance(message, Notification_Of_Private_Message): self.notification_of_private_message(message.from_, message.to, message.content) else: raise Exception("Bad message") def tag(self, tag_name, **kwargs): self._textarea.tag_config(tag_name, **kwargs) def clear(self): self._is_empty = True self._textarea.delete('1.0', END) @property def logging_file(self): return self._logging_file def send(self, content): if self._my_nick is None: raise Exception("Nick not set") self.user_message(self._my_nick, content) def _filter_text(self, text): return "".join(ch for ch in text if ch <= u"\uFFFF") def _write(self, *args): if len(args) == 0: return relative_position_of_scrollbar = self._vsb.get()[1] self._textarea.config(state=NORMAL) if self._is_empty: self._is_empty = False else: self._textarea.insert(END, "\n") if self._log is not None: self._log.write("\n") for arg in args: if isinstance(arg, tuple): text, tag = arg # Parsing not allowed characters text = self._filter_text(text) self._textarea.insert(END, text, tag) else: text = arg text = self._filter_text(text) self._textarea.insert(END, text) if self._log is not None: self._log.write(text) if self._maximum_lines is not None: start_line = int(self._textarea.index('end-1c').split('.') [0]) - self._maximum_lines if lines_to_delete >= 1: self._textarea.delete('%s.0' % start_line, END) self._textarea.config(state=DISABLED) if relative_position_of_scrollbar == 1: self._textarea.yview_moveto(1) def _on_message_sent(self, event): message = self._entry.get() self._entry.delete(0, END) self.send(message) if self._command: self._command(message) def set_nick(self, my_nick): self._my_nick = my_nick if my_nick: text = self._label_template.format(nick=my_nick) self._entry_label["text"] = text self._entry_label.pack(side=LEFT, padx=(5, 5), before=self._entry) else: self._entry_label.pack_forget()
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 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
def ask_basic_info(): root = Tk() # username left_frame = Frame(root) user_frame = Frame(left_frame) user_frame.pack() Label(user_frame, text=u"用户名:").pack(side=LEFT, padx=5) username = StringVar() ue = Entry(user_frame, textvariable=username) ue.pack(side=RIGHT, padx=5) username.set("") ue.focus_force() user_frame.pack(expand=1, fill=X, pady=5, padx=5) # passworkd pass_frame = Frame(left_frame) pass_frame.pack() Label(pass_frame, text=u" 密码:").pack(side=LEFT, padx=5) password = StringVar() pe = Entry(pass_frame, textvariable=password, show="*") pe.pack(side=RIGHT, padx=5) def ask(_=None): if len(username.get()) * len(password.get())== 0: pass else: root.destroy() pe.bind("<Key-Return>", ask) password.set("password") pass_frame.pack(expand=1, fill=X, pady=5, padx=5) # dumu / cixun level_frame = Frame(left_frame) main_level = IntVar() Radiobutton(level_frame, text=u"雌雄双煞", value=2, variable=main_level).pack(side=LEFT) Radiobutton(level_frame, text=u"杜姆之巢", value=3, variable=main_level).pack(side=LEFT) main_level.set(2) level_frame.pack() # minor minor_level_frame = Frame(left_frame) minor_level = IntVar() Label(minor_level_frame, text=u"子关选择:").pack(side=LEFT, padx=5) Radiobutton(minor_level_frame, text=u"1", value=1, variable=minor_level).pack(side=LEFT) Radiobutton(minor_level_frame, text=u"3", value=3, variable=minor_level).pack(side=LEFT) Radiobutton(minor_level_frame, text=u"5", value=5, variable=minor_level).pack(side=LEFT) Radiobutton(minor_level_frame, text=u"随机", value=0, variable=minor_level).pack(side=LEFT) minor_level.set(5) minor_level_frame.pack() # misc misc_item = [u"使用自动验证码识别(不可用)", u"提高时间参数(防封号)", u"只抓丽丽牛牛阿迪龙"] default_var = [0, 0, 0] misc_bar = Checckbar(left_frame, misc_item, default=default_var, side=TOP) misc_bar.pack() # left_frame.pack(side=LEFT) # bool config config_item = [u"捉鱼", u"访问鱼缸", u"换鱼食", u"点化鱼", u"合成鱼"] default_var = [1, 1, 0, 0, 1] config_bar = Checckbar(root, config_item, default=default_var, side=TOP) config_bar.pack(side=LEFT) # login Button(root, text=u"登录", command=ask).pack(side=LEFT) root.title(u"欢迎使用杯具渔民 %s" % __VERSION__) root.mainloop() return (username.get(), password.get(), main_level.get(), minor_level.get(), misc_bar.state() + config_bar.state())
class TaskList(Frame): def __init__(self, master, client): Frame.__init__(self, master) # Connect to Dropbox and open datastore. self.manager = DatastoreManager(client) # Try to load serialized datastore first. datastore = self.load_serialized_datastore(SERIALIZED_DATASTORE) if datastore is not None: try: datastore.load_deltas() except DatastoreNotFoundError: print 'This datastore has been deleted. Exiting now.' sys.exit(1) except HTTPError: print 'We are offline. Proceed with caution.' else: datastore = self.manager.open_default_datastore() self.datastore = datastore self.table = self.datastore.get_table('tasks') # Set up communication with background thread. self.queue = Queue() # Holds deltas sent from background thread. self.display_rev = 0 # Last revision displayed. self.refresh() # Initial display update. self.bind(REFRESH_EVENT, self.refresh) # Respond to background thread. # Create, configure and start background thread. self.bg_thread = Thread(name='bgthread', target=self.bg_run) self.bg_thread.setDaemon(True) self.bg_thread.start() def load_serialized_datastore(self, filename): try: f = open(filename, 'rb') except IOError as exc: # Don't print an error if the file doesn't exist. if os.path.exists(filename): print 'Cannot load saved datastore:', exc return None with f: try: data = json.load(f) id, handle, rev, snapshot = data except ValueError as exc: print 'Bad JSON on %s: %s' % (filename, exc) return None datastore = self.manager.open_raw_datastore(id, handle) # If this fails, the save file is bad -- you must manually delete it. datastore.apply_snapshot(rev, snapshot) print 'Loaded datastore from', filename return datastore def save_serialized_datastore(self, datastore, filename): id = datastore.get_id() handle = datastore.get_handle() rev = datastore.get_rev() snapshot = datastore.get_snapshot() data = [id, handle, rev, snapshot] try: f = open(filename, 'wb') except IOError as exc: print 'Cannot save datastore:', exc return with f: json.dump(data, f) print 'Saved datastore to', filename def bg_run(self): # This code runs in a background thread. No other code does. deltamap = None backoff = 0 while True: cursor_map = DatastoreManager.make_cursor_map([self.datastore], deltamap) try: _, _, deltamap = self.manager.await(datastores=cursor_map) except Exception as exc: if isinstance(exc, HTTPError): if not backoff: print 'We have gone offline.' else: print 'We are still offline.' else: print 'bg_run():', repr(exc), str(exc) # Randomized exponential backoff, clipped to 5 minutes. backoff = min(backoff*2, 300) + random.random() time.sleep(backoff) continue else: if backoff: print 'We have come back online.' backoff = 0 if deltamap and self.datastore in deltamap: deltas = deltamap[self.datastore] if deltas is None: # Stop the bg thread. print 'This datastore has been deleted.' print 'Please exit.' break if deltas: self.queue.put(deltas) self.event_generate(REFRESH_EVENT, when='tail') def save(self, event=None): self.save_serialized_datastore(self.datastore, SERIALIZED_DATASTORE) def refresh(self, event=None): # This is called directly when we have made a change, # and when the background thread sends a REFRESH_EVENT. self.load_queue() # Update the datastore. if self.datastore.get_rev() == self.display_rev: return # Nothing to do. self.forget() # Hide the frame to reduce flashing. for w in self.winfo_children(): w.destroy() # Delete the old widgets. self.redraw() # Create new widgets. self.pack(fill=BOTH, expand=1) # Show the frame. self.display_rev = self.datastore.get_rev() title = self.datastore.get_title() mtime = self.datastore.get_mtime() if not title: title = 'My Tasks' if mtime: fmtime = mtime.to_datetime_local().strftime('%H:%M, %d %b %Y') title = '%s (%s)' % (title, fmtime) self.master.title(title) self.input.focus_set() def load_queue(self): # Incorporate queued deltas into the datastore. while True: try: deltas = self.queue.get_nowait() except Empty: break else: self.datastore.apply_deltas(deltas) def redraw(self): # Even though there are never more than three widgets per row, # we have four columns, to allow the taskname label and the # input widget to stretch. self.grid_columnconfigure(2, weight=1) row = 0 # Add a new row of widgets for each task. for rec in sorted(self.table.query(), key=lambda rec: rec.get('created')): # Extract the fields we need. completed = rec.get('completed') taskname = rec.get('taskname') # Create a button with an 'X' in it, to delete the task. close_btn = Button(self, text='X', command=lambda rec=rec: self.delete_rec(rec)) close_btn.grid(row=row, column=0) # Create a checkbox, to mark it completed (or not). var = BooleanVar(self, value=completed) completed_btn = Checkbutton(self, variable=var, command=lambda rec=rec, var=var: self.toggle_rec(rec, var)) completed_btn.grid(row=row, column=1) # Create a label showing the task name. taskname_lbl = Label(self, text=taskname, anchor=W) taskname_lbl.grid(row=row, column=2, columnspan=2, sticky=W) row += 1 # Bump row index. # Add a final row with the input and button to add new tasks. self.input = Entry(self) self.input.bind('<Return>', self.add_rec) self.input.grid(row=row, column=0, columnspan=3, sticky=W+E) add_btn = Button(self, text='Add Task', command=self.add_rec) add_btn.grid(row=row, column=3) # Add save button. (Auto-save is left as an exercise.) save_btn = Button(self, text='Save local snapshot', command=self.save) save_btn.grid(row=row+1, column=0, columnspan=3, sticky=W) def add_rec(self, event=None): # Callback to add a new task. self.do_transaction(self.table.insert, completed=False, taskname=self.input.get(), created=Date()) def delete_rec(self, rec): # Callback to delete a task. self.do_transaction(rec.delete_record) def toggle_rec(self, rec, var): # Callback to toggle a task's completed flag. try: self.do_transaction(rec.set, 'completed', var.get()) finally: # In case the transaction failed, flip the variable back. var.set(rec.get('completed')) def do_transaction(self, func, *args, **kwds): self.update_idletasks() # Refresh screen without handling more input. def call_func(): func(*args, **kwds) try: self.datastore.transaction(call_func, max_tries=4) except Exception as exc: # Maybe the server is down, or we experience extreme conflicts. # NOTE: A more user-friendly way would be to show an error dialog. print 'do_transaction():', repr(exc) else: self.refresh()
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()
def createWidgets(): nRow = 0 Frame1 = Frame(root, height=200, width=200) Frame1.grid(sticky=W) Label7 = Label(Frame1, text='(V1)类型说明:') Label7.grid( row=nRow, column=0, ) Label7 = Label(Frame1, text='(0:oracle / 1:SQL)') Label7.grid( row=nRow, column=1, ) nRow += 1 Label7 = Label(Frame1, text='数据库类型:') Label7.grid( row=nRow, column=0, ) Dbtype = Entry(Frame1, textvariable=varDBType) Dbtype.grid(row=nRow, column=1) Label1 = Label(Frame1, text='数据库地址:') # Label1.pack(anchor=W) Label1.grid(row=nRow, column=0) IPInput = Entry(Frame1, textvariable=varIP) IPInput.grid(row=nRow, column=1) nRow += 1 # Label2 = Label(Frame1, text='数据库名称:') Label2.grid( row=nRow, column=0, ) ServerName = Entry(Frame1, textvariable=varDateBase) ServerName.grid(row=nRow, column=1) nRow += 1 Label3 = Label(Frame1, text='用户名:') Label3.grid( row=nRow, column=0, ) User = Entry(Frame1, textvariable=varUser) User.grid(row=nRow, column=1) nRow += 1 Label4 = Label(Frame1, text='数据库密码:') Label4.grid( row=nRow, column=0, ) DBPass = Entry(Frame1, show='*', textvariable=varPaswd) DBPass.grid(row=nRow, column=1) nRow += 1 Label5 = Label(Frame1, text='接口地址:') Label5.grid( row=nRow, column=0, ) WebSerIp = Entry(Frame1, textvariable=varWebSerIp) WebSerIp.grid(row=nRow, column=1) nRow += 1 Label12 = Label(Frame1, text=' 上传间隔:') Label12.grid(row=nRow, column=0) Input3 = Entry(Frame1, textvariable=varSleeptime) Input3.bind('<KeyRelease>', keyPress) Input3.grid(row=nRow, column=1) nRow += 1 Frame2 = Frame(Frame1, height=50, width=200) Frame2.grid(sticky=W, row=nRow, column=1) nRow = 0 BtnConnet = Button(Frame2, text='写入配置', command=Connet) BtnConnet.grid(row=nRow, column=0) Frame3 = Frame(root, height=50, width=300) Frame3.grid(sticky=N) LabMess = Label(Frame3, text='等待连接。。', font=13, fg='red') LabMess.grid(row=0, column=0) TestBtn = Button(Frame3, text='数据库连接', command=lambda: TestDBConnet(LabMess)) TestBtn.grid(row=1, column=0) Btn1 = Button(Frame3, text='接口测试', command=lambda: IntfConnetTest(LabMess)) Btn1.grid(row=1, column=2, padx=10) Btn2 = Button(Frame3, text='开始上传', command=lambda: Thread_SaveLoad(LabMess)) Btn2.grid(row=1, column=4, padx=10) quitButton = Button(Frame3, text='关闭', command=Quit) quitButton.grid(row=1, column=5, padx=10) #接口部分 nRow = 0 Label8 = Label(Frame1, text=' 接口参数: ') Label8.grid(row=nRow, column=2, columnspan=2) nRow += 1 Label9 = Label(Frame1, text=' 景区编码:') Label9.grid(row=nRow, column=2) IPInput = Entry(Frame1, textvariable=varParkCode) IPInput.grid(row=nRow, column=3) nRow += 1 Label10 = Label(Frame1, text=' 业务编码:') Label10.grid(row=nRow, column=2) combox1 = Combobox( Frame1, textvariable=varinfoCode, values=GetinfoCode(), width=18, ) combox1.bind( "<<ComboboxSelected>>", comboxChanged, ) combox1.grid( row=nRow, column=3, ) nRow += 1 Label11 = Label(Frame1, text=' 存储过程:') Label11.grid(row=nRow, column=2) Input3 = Entry(Frame1, textvariable=varProc) Input3.grid(row=nRow, column=3) nRow += 2 SaveBtn = Button(Frame1, text='保存存储过程', command=SaveProc) SaveBtn.grid(row=nRow, column=3)
item = sortable_list.create_item(value=i) label = Label(item, text="this is a label %s"%i) label.pack(anchor=W, padx= (4,0), pady= (4,0)) sortable_list.add_item(item) frame = Frame(root) frame.pack(fill=X, pady=(0, 10)) indexVar = IntVar() label = Label(frame, text="Entry index of item to delete:") label.pack(side=LEFT, padx=(10,6)) entry_of_index = Entry(frame,textvariable= indexVar, width=3) def delete_item(): try: index = indexVar.get() except ValueError: messagebox.showerror("Error", "Not a valid integer") return entry_of_index.delete(0, END) sortable_list.delete_item(index) entry_of_index.bind('<Return>', delete_item) entry_of_index.pack(side=LEFT) Button(frame, text="Delete", command=delete_item).pack(side=LEFT, padx=(3,0)) root.mainloop()
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 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)
def __init__(self): self.error = True window = Tk() window.title("Tub_Calculator") window.configure(background='orange') self.string = StringVar() entry = Entry(window, textvariable=self.string, font="Helvetica 17 bold") entry.grid(row=0, column=0, columnspan=6) entry.bind('<KeyPress>', self.keyPress) entry.focus() values = [ "7", "8", "9", "/", "Clear", "<-", "4", "5", "6", "*", "(", ")", "1", "2", "3", "-", "=", "0", ".", "%", "+" ] i = 0 row = 1 col = 0 for txt in values: padx = 10 pady = 10 if (i == 6): row = 2 col = 0 if (i == 12): row = 3 col = 0 if (i == 17): col = 0 row = 4 if (txt == "="): btn = Button(window, height=1, width=2, padx=23, pady=23, text=txt, command=lambda txt=txt: self.equals()) btn.grid(row=row, column=col, columnspan=2, rowspan=2, padx=1, pady=1) elif (txt == "Clear"): btn = Button(window, height=1, width=2, padx=padx, pady=pady, text=txt, command=lambda txt=txt: self.clearTxt()) btn.grid(row=row, column=col, padx=1, pady=1) elif (txt == "<-"): btn = Button(window, height=1, width=2, padx=padx, pady=pady, text=txt, command=lambda txt=txt: self.delete()) btn.grid(row=row, column=col, padx=1, pady=1) else: btn = Button(window, height=1, width=2, padx=padx, pady=pady, text=txt, command=lambda txt=txt: self.addChar(txt)) btn.grid(row=row, column=col, padx=1, pady=1) col = col + 1 i = i + 1 window.mainloop()
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 PodSearch(object): '''This is the GUI class''' # Initialization of variables filename = "" # Initialization of GUI def __init__(self, master): '''Init of the GUI''' # Frame for progress bar self.bottomframe = Frame(master, highlightbackground="green", highlightcolor="green", highlightthickness=1, width=500, height=200) self.bottomframe.pack(side=BOTTOM) # Frame for buttons and entry self.leftframe = Frame(master, highlightbackground="blue", highlightcolor="blue", highlightthickness=1, width=400, height=400) self.leftframe.pack(side=LEFT) # Sub frame for buttons self.leftsubframe_top = Frame(self.leftframe, highlightbackground="yellow", highlightcolor="yellow", highlightthickness=1) self.leftsubframe_top.pack(side=TOP) # Sub frame for entry self.leftsubframe_bot = Frame(self.leftframe, highlightbackground="purple", highlightcolor="purple", highlightthickness=1) self.leftsubframe_bot.pack(side=BOTTOM) # Frame for wordcloud rightframe = Frame(master, highlightbackground="red", highlightcolor="red", highlightthickness=1, width=250, height=250) rightframe.pack(side=RIGHT) # Browse button self.browsebtn = Button(self.leftsubframe_top, text="Browse", command=self.browse) self.browsebtn.pack(side=LEFT) # Quit button self.quitbtn = Button(self.leftsubframe_top, text="Quit", command=self.leftframe.quit) self.quitbtn.pack(side=LEFT) # Filepath label self.pathlabel = Label(self.leftsubframe_bot, text="filename") self.pathlabel.pack() # Textbox self.searchentry = Entry(self.leftsubframe_bot) self.searchentry.pack() self.searchentry.bind('<Return>', lambda _: self.search()) # Search button self.searchbtn = Button(self.leftsubframe_bot, text="Search", command=self.search) self.searchbtn.pack() # Word label self.wordlabel = Label(self.bottomframe) self.wordlabel.pack() # Timestamp label self.timestamplabel = Label(self.bottomframe) self.timestamplabel.pack() # estimate label self.estimatelabel = Label(self.bottomframe) self.estimatelabel.pack() # Working Label self.workinglabel = Label(self.bottomframe) self.workinglabel.pack() # Progress Bar self.pbar_det = ttk.Progressbar(self.bottomframe, orient="horizontal", length=400, mode="indeterminate") # Wordcloud preparation self.imagefile = "wordcloudTools/black_background.png" self.imagefile = Image.open(self.imagefile) self.image1 = self.imagefile.resize((400, 400), Image.ANTIALIAS) self.image1 = ImageTk.PhotoImage(self.image1) self.panel1 = Label(rightframe, image=self.image1) self.display = self.image1 self.panel1.pack(side=TOP, fill=BOTH, expand=YES) # Non GUI initializations self.duration = 0 self.transcription = "" self.stemmed = "" self.transcription = "" self.imagefile2 = 0 self.image2 = 0 # Browse function def browse(self): '''browse for file''' if self.wordlabel != "": # clear the labels if necessary self.wordlabel.config(text="") self.pathlabel.config(text="") self.timestamplabel.config(text="") self.estimatelabel.config(text="") self.filename = askopenfilename( ) # openfile dialog and put file in filename if not self.filename: # leave method if cancel is clicked return self.pathlabel.config(text=basename( self.filename)) # show filename as label if self.filename.endswith('.txt'): return self.workinglabel.config(text="WORKING", font=("Helvetica", 20)) # Show WORKING when transcribing self.pbar_det.pack() # show the progress bar self.pbar_det.start() # Start the progress bar root.update() self.transcription = transcribe(self.filename) # Call transcribe wordcloud_path = wordcloud_create(self.transcription) self.transcription = removerlap(self.transcription.split(' ')) self.new_image(wordcloud_path) self.workinglabel.config(text="") # remove working label self.pbar_det.stop() # Stop progress bar self.pbar_det.pack_forget() # Remove progress bar # Search function def search(self): '''Search using text domain''' if not self.transcription == '': if not self.searchentry.get() == '': keyword = self.searchentry.get() # Get entry from textbox # ********************************************************************************* # Here coes code # ********************************************************************************* # Write result to label if wordlabel != "Word number": self.wordlabel.config(text=wordlabel) self.estimatelabel.config(text=time) self.timestamplabel.config(text=timestamplabel) else: self.wordlabel.config(text="Word not found") self.timestamplabel.config(text="") self.estimatelabel.config(text="") else: self.wordlabel.config(text="Enter word in search field") else: self.timestamplabel.config(text="No file selected") def new_image(self, path): '''Word Cloud image''' self.imagefile2 = Image.open(path) self.image2 = self.imagefile2.resize((400, 400), Image.ANTIALIAS) self.image2 = ImageTk.PhotoImage(self.image2) self.panel1.configure(image=self.image2) self.display = self.image2
class AuthPage(BasePage): def __init__(self, parent, controller): self.is_auth = False self.mutex = Lock() BasePage.__init__(self, parent, controller) def prepare(self): mode = self.mode.get() user = self.userVar.get() pwd = self.pwdVar.get() if mode is 1 and user and pwd: self.confirm(mode, user, pwd) self.userInput.focus_force() def printErr(self, message): self.errLog.config(text=message) def entryToggle(self, toggle, target): if(toggle): for t in target: t.configure(state='normal') else: for t in target: t.configure(state='disabled') def confirm(self, mode, user, pwd): self.mutex.acquire() try: if mode == 1 and not self.is_auth: # mode:1 flash from pvt # TODO: the GUI do not updated due to the correct way to update the UI in tk is to use the after method. self.logger.log('Logging into server...', status_callback=self.printErr) if self.controller.setAuth(user, pwd): self.is_auth = True self.ok.config(state="disabled") self.userInput.config(state="disabled") self.pwdInput.config(state="disabled") self.controller.transition(self) else: self.printErr("Auththentication failed") else: # mode:2, flash from local pass finally: self.mutex.release() def pressReturnKey(self, event=None): if len(self.userVar.get()) > 0 and len(self.pwdVar.get()) > 0: self.confirm(self.mode.get(), self.userVar.get(), self.pwdVar.get()) elif len(self.userVar.get()) == 0: self.logger.log('Please enter username.', status_callback=self.printErr) self.userInput.focus_set() else: self.logger.log('Please enter password.', status_callback=self.printErr) self.pwdInput.focus_set() def setupView(self, title="Test Auth Page", user='', pwd_ori=''): self.mode = IntVar() self.mode.set(1) Label(self, width=25).grid(row=1, column=0, columnspan=2) self.errLog = Label(self, text="") self.errLog.grid( row=4, column=1, columnspan=3, rowspan=3, sticky="NWSE" ) self.userVar = StringVar() self.pwdVar = StringVar() Label(self, text="Account").grid(row=2, column=1, sticky='E') self.userInput = Entry( self, textvariable=self.userVar, width="30") self.userInput.grid( row=2, column=2, columnspan=2, sticky="W") Label(self, text="Password").grid(row=3, column=1, sticky='E') self.pwdInput = Entry( self, textvariable=self.pwdVar, show="*", width="30") self.pwdInput.grid( row=3, column=2, columnspan=2, sticky="W") self.userVar.set(user) self.pwdVar.set(pwd_ori) Label( self, text=' Welcome to fxos flash tool', font=TITLE_FONT ).grid( row=0, column=1, columnspan=3, sticky="WE") Radiobutton(self, state='disabled', text='Download build from pvt', variable=self.mode, value=1, command=lambda: self.entryToggle( True, [self.userInput, self.pwdInput]) ).grid(row=1, column=2, columnspan=2, sticky="E") Radiobutton(self, state='disabled', text='Flash build from local', variable=self.mode, value=2, command=lambda: self.entryToggle( False, [self.userInput, self.pwdInput]) ).grid(row=1, column=4, sticky="W") self.ok = Button(self, text='Next', command=lambda: self. confirm(self.mode.get(), self.userVar.get(), self.pwdVar.get())) self.ok.grid(row=4, column=4, sticky="W") self.userInput.bind('<Return>', self.pressReturnKey) self.pwdInput.bind('<Return>', self.pressReturnKey) self.ok.bind('<Return>', self.pressReturnKey)
class GameFrame(Frame): def __init__(self, parent): Frame.__init__(self, parent, width=600, height=250) self.parent = parent def init_gui(self): correct = """R0lGODlhQABAAOeqAAAAAAABAAACAAADAAAEAAAFAAAFAQAGAQAHAQEHAQEIAQEJAQEKAQEKAgEL AgEMAgENAgEPAgIPAgIQAgIRAwITAwIUAwIVBAMVBAIWAwIWBAIXBAMXBAMYAwIZBAMZBAMaBQMb BAMdBQMeBQMfBQMgBQQgBQQiBgQkBgQlBgQmBwQnBwUnBgUoBwUqBwUrBwUsBwUsCAUtCAUuCAUv CAYvCAUxCAYyCQYzCAY0CQY1CgY2CQY3CQc3CgY5Cgc5Cgc7Cgc+Cwg/CwdACwhACwhBCwhCCwhG DAhHDAhIDQlLDQlMDglNDglPDglQDglRDglSDgpUDwpWDwtWDwpXDwpZDwtaEAtfEQtgEQthEQxk EQxkEgxlEgxnEgxoEw1oEgxpEgxqEw1qEg1rEwxsEw1sEg1tEw1vEw1wFA1yFA5yFA1zFA50FA50 FQ51FA52FQ95Fg56FQ57Fg97FQ99Fg9+Fg9/Fg+AFhCAFg+BFhCCFhCEFxCGFxCHGBCIGBCKGBGK GBCLGBGMGRGNGRGOGRGQGRGRGRGRGhGSGRGTGhKTGRKTGhGUGhKVGhKXGhKXGxKYGhKaGxKbGxKc GxKdGxKdHBOdGxOdHBKeHBOeGxOeHBOfHBOgHBOhHBOiHBOiHROjHBOjHROkHRSkHROlHRSlHRSm HRSnHRSoHRSrHv////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////yH+EUNyZWF0ZWQgd2l0aCBH SU1QACH5BAEKAP8ALAAAAABAAEAAAAj+AP8JHEiwoMGDCBMqPAhgocOHEB0CaBixosWFEyde3MhR YEaKHUNC/CiyJMYHCTSaXGkQgAcVKVnKHAhgBZIIIGeanAiki4acOkVOlJInBNCgHQEIELOIxFGk GwFASLNJxVOoFgFUiFOKx1WsEQFY0GOqiQCwIQF0ECSqi4KvaDGKWNRJjgW4cRMCOEGI06AWePMy ROGnU6QggQUXBIBij6dPUBIrptk4lKkuAiRPBpCCT6hQdipoVgxgBB9PnAzBGC0YQAY7mzRJWsI6 L4AIazTpVkNg8kgFXDhpwqTorm+JA6aE0kRpk47acQEkMUVJU6cs0NEC8FGKEiVOfQb+ZMcKgMWk TM0joRgPFQCIQMw1bXpy9rjC22+Ea+IUZwJ7pAZcIVx1jdjwX1AAKFHJJt5lgsWBOgGwAyScUHKJ JoJIAKFMpRlSIXOj3LAhSwAkgMeHlIDixYgkauGdJpds4ggFLO5EhCOaWMKcKUMEEGFaJfzBoG6d vAEBgipl9cAZoFRXXSQ41OgRAAHUJgATp1Sn2yZjJNBeARi8FZYMoGByoW6IrEbeD04Y9RAAFBwy JHOYdCFlS1T8UQROCwVgxocwapIIB3cuBsAWppgxQ5KLGfGibpSI4kShLTnQRiqEWPHBUQCYAJ9u zHHCxwGUtiQCH6RwYscRBOS0QBjKsYGqCSk1lMpQDoxs0okjaVjVEABCVBIfc6CwccBxADwxCaiF VEHqBosAqhsnMdiaUABoDCsJIDq40YmZkIJCBgP2/VMiIAxWd4kkTsr6SA7W3ndBJMPJai8naSBQ Lk0zxKalvZo00kO8DgXAxID2UmLJHARLtAAYsdorCQ0NS/TBHcMytwkdFb8JgyHDYuKJCx2/OcQm mFhCSScM73tfFNRhMsoLJY+UwBeneAKHly7fZ0EdqOxQc0UAvFBGBT0/JEAD9SWN0XEBAQA7 """ wrong = """R0lGODlhQABAAOexAAAAAAEAAAIAAAMAAAQAAAUAAAYAAAgAAAkAAAoAAAwAAA0AAA4AAA8AABAA ABEAABIAABMAABQAABUAABYAABcAABgAABkAABoAABsAABwAAB0AAB4AAB8AACAAACEAACIAACMA ACQAACUAACYAACgAACkAACoAACsAACwAAC0AAC4AADEAADMAADQAADUAADYAADgAADkAADoAADsA ADwAAD0AAD4AAD8AAEEAAEIAAEQAAEUAAEkAAEoAAEsAAFQAAFUAAFgAAFkAAF0AAF8AAGEAAGIA AGQAAGcAAGgAAGoAAGsAAG0AAG4AAG8AAHAAAHMAAHgAAHsAAHwAAIEAAIYAAIoAAI4AAJMAAJQA AJUAAJYAAJcAAJgAAJkAAJoAAJsAAJwAAJ0AAJ4AAKAAAKEAAKQAAKcAAKgAAKkAAKoAAK0AAK4A AK8AALAAALEAALMAALUAALcAALgAALkAALoAALsAAL4AAL8AAMAAAMEAAMQAAMUAAMYAAMgAAMkA AMoAAMwAAM0AAM4AAM8AANAAANEAANIAANMAANQAANUAANYAANcAANgAANkAANoAANsAAN0AAN4A AOAAAOEAAOIAAOMAAOQAAOYAAOgAAOkAAOoAAOwAAO0AAO4AAO8AAPAAAPEAAPIAAPMAAPQAAPUA APYAAPcAAPgAAPkAAPoAAPsAAPwAAP0AAP4AAP8AAP////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////yH+EUNyZWF0ZWQgd2l0aCBH SU1QACH5BAEKAP8ALAAAAABAAEAAAAj+AP8JHEhwIAAABRMqXLjwIMOHCQFAgIAQosWGFjRUvNhQ A5sxDTZyvAggwhpAK0SOFAigwxxXo7aEXGmxZBlSqwbFUMmx5Z1To0qN4oKAJ02DCsiQEmqKUA2j DwFsoFOKFKlRpE55CQB1JQABZE5dtVqqEIyuES28STXW6ihWXxweNQhAzCqsVq+eMpQCrUEKamCN wpt3VKsvBPwyBEDASyvChVcdKuEXQIU0giEXVtVFgWKFCbKo0lyY1SEVXQFcaJM5r+u8pbY4+ExQ AZbXuK+uQjTDKAAMckaTdh00pueRCK6IEpqb+ClEOVSqliN0+OugpbgkrinASinmzYn+l0KEYyMA Cm3EWseNVZUXuQ0BVFnVNvxrU4peIATQ4AzM9c0ZtlVqVAhmX4CpKBLCQR8UYkp9BxLHShdFKUTA FDBFyB4ppugBwn4m8CGWhuydIpNKBkxhCoD2mXLHhwad8MeKJLKnBQMbFSAFKODVeJUpe4ggHQiH 0OjjVUJtcQBCAkTBI4u5jXLKIBz4VsEjQB05FipdHLTEKdUdKWUjE6QmQSMPQskeK1sQ4QqEGmJl SiMSVKbBIOppOYoqj6lJXFaFbPAZACT0kaeYcEaI1SmBnEDbPwCgYKiWlOZ1iiAsPMoSCYMYWSmJ QTGS0lwAaNBIlp8qWoolJGhaEAD+EjziaapRlpIJjHMZVEGRiaYqJyWU5foqCH8cSuuWjrTgalQn iHisa6csYsOyEAFgAiCzVhqUJOUJG5UHiWSL6Ca9eVstBYw8mKonZ5lbUxOspJoKGvC5q1AASbDi Z4CrgFGhvQkN0ESatI6CChgPUAvRAFB40uOxYkSg8EIBONGJuNpWZcYCE7+qxFKDPesWh2psZy4A R7TS67F7viFAxwAg8UrIIrO3ShwJKCwAE6nQXDN7qLxBwbIDPBHKyj9bZUobGq0kwBOdPJz0dUvB cQFtADARSpg+yrlvYRzaMVtNSLDlM6ikdJLu1yOfwse/DR0xM9tYlcLJCxIgQrD+mKgAMtO9SvSJ 6CmUTAsAB37s3TUqfmTA0wBOjKwlKpDsUBGheIyo5yl6tEoQw1Gz/eMkPIgEwAh5oKrlKXl4/s8B DWN8IFaadPtqBn2gIrqcf6BwUAaCCIdoKDs1xMAfPW+uiQv7vaCIumiX8ol+USHg7NelYPKDeTgg InWAWWFSbrUN1KG4fVhVIoR0OSCiOvioRKID1mpVxWJQlhDhmwyI3HXgKZEonVcywAboBegUmghC alRwCH0FKHvzOwoAJuAG3R3QEz2oTAkM4T+qfWJ8EkwAHDronE9EsCYpKMT7sBIK6gkLAAFow2jE wwkfPAoAMCBEVcZiCk0U72RWBEiD4jAxBFcBgAaEoBEqJmE7dwFgATcRSikuYQRqASAGg1DFKSAh QIBBCgJh4NAmijAxAKxAEJiwnBcN4gAwdAIIHYNUB24Qx8U8QFn2guEaI/KZgAAAOw==""" self.correct_img = PhotoImage(data=correct) self.wrong_img = PhotoImage(data=wrong) self.entry = Entry(self.parent, width=15, font=('Helvetica', 20, 'normal'), justify=CENTER) self.entry.bind("<Return>", lambda x:self.buttonSubmit.invoke()) self.buttonNext = Button(self.parent, width=10, text="Next Word", command=self.next_word, state=DISABLED) self.buttonSubmit = Button(self.parent, width=10, text="Submit", command=self.submit_word) buttonReplay = Button(self.parent, width=10, text="Repeat Word", command=self.replay_word) self.game_canvas = Canvas(self, width=600, height=250, bg="#FFFFFF") self.word_display = self.game_canvas.create_text((300, 105), text="?", font=("Helvetica", 50, "bold"), fill="#004183") self.progress_display = self.game_canvas.create_text((593, 5), text="%d/%d"%(1, self.parent.list_length), font=("Helvetica", 25, "bold"), anchor=NE) self.timer_display = self.game_canvas.create_text(10, 5, anchor=NW, font=("Helvetica", 25)) self.progress_bar = ProgressBar(self, width=300, increments=len(self.parent.current_list.words)) self.game_canvas.create_window(500, 10, anchor=NE, window=self.progress_bar) self.game_canvas.create_window(300, 180, window=self.entry) self.game_canvas_image = self.game_canvas.create_image(500, 170) self.game_canvas.create_window(150, 230, window=buttonReplay) self.game_canvas.create_window(300, 230, window=self.buttonSubmit) self.game_canvas.create_window(450, 230, window=self.buttonNext) self.game_canvas.pack() def start(self): self.current_list_iter = iter(self.parent.current_list.words) self.current_word = self.current_list_iter.next() self.parent.festival.speech(self.current_word) self.time_elapsed = 0 self.init_gui() self.tick() def next_word(self): try: self.current_word = self.current_list_iter.next() index = self.parent.current_list.words.index(self.current_word) + 1 self.game_canvas.itemconfig(self.progress_display, text="%d/%d" %(index, self.parent.list_length)) if index == self.parent.list_length: self.buttonNext.configure(text="Finish") self.game_canvas.itemconfig(self.word_display, text="?", fill="#004183") self.game_canvas.itemconfig(self.game_canvas_image, state=HIDDEN) self.buttonSubmit.configure(state=NORMAL) self.buttonNext.configure(state=DISABLED) self.parent.festival.speech(self.current_word) except StopIteration: self.list_complete() def list_complete(self): self.parent.after_cancel(self.timer) self.parent.show_results(self.time_elapsed) def replay_word(self): self.parent.festival.speech(self.current_word) def submit_word(self, event=None): guess = self.entry.get() self.entry.delete(0, END) if guess == self.current_word.word: self.correct(guess) else: self.incorrect(guess) self.game_canvas.itemconfig(self.word_display, text='%s'%(self.current_word)) self.buttonNext.configure(state=NORMAL) self.buttonSubmit.configure(state=DISABLED) self.game_canvas.itemconfig(self.game_canvas_image, state=NORMAL) def correct(self, guess): self.current_word.setAnswer(guess, True) self.game_canvas.itemconfig(self.game_canvas_image, image=self.correct_img) self.game_canvas.itemconfig(self.word_display, fill="#139E1C") self.progress_bar.increment(True) def incorrect(self, guess): self.current_word.setAnswer(guess, False) self.game_canvas.itemconfig(self.game_canvas_image, image=self.wrong_img) self.game_canvas.itemconfig(self.word_display, fill="#F30000") self.progress_bar.increment(False) def tick(self): seconds = (self.time_elapsed)%60 minutes = self.time_elapsed/60 separator = ":" if seconds > 9 else ":0" formatted_time = "%d%s%d"%(minutes, separator, seconds) self.game_canvas.itemconfig(self.timer_display, text=formatted_time) self.time_elapsed +=1 self.timer = self.parent.after(1000, self.tick)
def maximize(self): self.text_box.pack(expand=YES, fill=BOTH) self.iconifyButton['command'] = self.minimize self.iconifyButton['image'] = self.minimize_IMG if __name__ == '__main__': try: from Tkinter import Tk, Entry, StringVar, Button, Label from Tkconstants import LEFT except ImportError: from tkinter import Tk, Entry, StringVar, Button, Label from tkinter.constants import LEFT def create_a_new_note(): DesktopNote.new_window(title_var.get()) root = Tk() Label(root, text="Title:").pack(side=LEFT) title_var = StringVar() title_var.set('TITLE') entry_title = Entry(root, textvariable=title_var) entry_title.pack(side=LEFT) entry_title.bind('<Return>', lambda event: create_a_new_note()) Button(root, text="Create another note", command=create_a_new_note).pack(side=LEFT) root.mainloop()
class ListPage(BasePage): def __init__(self, parent, controller): BasePage.__init__(self, parent, controller) self.mutex = Lock() def prepare(self): self.deviceList.config(state='normal') self.versionList.config(state='disabled') self.engList.config(state='disabled') self.packageList.config(state='disabled') self.ok.config(state='disabled') self.setData(self.controller.data) self.setDeviceList(self.data.keys()) self.controller.setDefault(self, self.controller.loadOptions()) self.deviceList.focus_force() def printErr(self, message): self.errLog.config(text=message) def setData(self, data): self.data = data def setupView(self, title="Select your flash", data=None): if(data): self.setData(data) self.errLog = Label(self, text="") self.errLog.grid(row=4, column=1, columnspan=3, sticky="NWSE") self.desc = Label(self, text=title, font=TITLE_FONT) self.desc.grid(row=0, column=0, columnspan=2) self.ok = Button(self, text='Next', command=lambda: self. confirm()) self.ok.grid(row=4, column=3, sticky="E") self.ok.config(state="disabled") self.deviceLabel = Label(self, text="Device", font=TITLE_FONT) self.deviceLabel.grid(row=1, column=0) self.deviceList = Listbox(self, exportselection=0) self.deviceList.grid(row=2, column=0) self.deviceList.bind('<<ListboxSelect>>', self.deviceOnSelect) self.deviceList.config(state="disabled") self.versionLabel = Label(self, text="Branch", font=TITLE_FONT) self.versionLabel.grid(row=1, column=1) self.versionList = Listbox(self, exportselection=0) self.versionList.grid(row=2, column=1) self.versionList.bind('<<ListboxSelect>>', self.versionOnSelect) self.versionList.config(state="disabled") self.engLabel = Label(self, text="Build Type", font=TITLE_FONT) self.engLabel.grid(row=1, column=2) self.engList = Listbox(self, exportselection=0) self.engList.grid(row=2, column=2) self.engList.bind('<<ListboxSelect>>', self.engOnSelect) self.engList.config(state="disabled") self.packageLabel = Label( self, text="Gecko/Gaia/Full", font=TITLE_FONT) self.packageLabel.grid(row=1, column=3) self.packageList = Listbox(self, exportselection=0) self.packageList.grid(row=2, column=3) self.packageList.bind('<<ListboxSelect>>', self.packageOnSelect) self.packageList.config(state="disabled") self.bidVar = StringVar() Label(self, text="Build ID").grid(row=3, column=0, sticky='E') self.bidInput = Entry( self, textvariable=self.bidVar, width="30") self.bidInput.grid( row=3, column=1, columnspan=2, sticky="W") self.bidVar.set('latest') # binding unfocus for build id field self.bidInput.bind('<FocusOut>', self.updateBuildId) # binding the Return Key to each componments self.deviceList.bind('<Return>', self.pressReturnKey) self.versionList.bind('<Return>', self.pressReturnKey) self.engList.bind('<Return>', self.pressReturnKey) self.packageList.bind('<Return>', self.pressReturnKey) self.bidInput.bind('<Return>', self.pressReturnKey) self.ok.bind('<Return>', self.pressReturnKey) def selection_all_checked(self): result = False if len(self.deviceList.curselection()) == 0: self.logger.log('Please select device.', status_callback=self.printErr) self.ok.config(state="disabled") self.deviceList.focus_set() elif len(self.versionList.curselection()) == 0: self.logger.log('Please select branch.', status_callback=self.printErr) self.ok.config(state="disabled") self.versionList.focus_set() elif len(self.engList.curselection()) == 0: self.logger.log('Please select user or engineer build.', status_callback=self.printErr) self.ok.config(state="disabled") self.engList.focus_set() elif len(self.packageList.curselection()) == 0: self.logger.log('Please select package to flash.', status_callback=self.printErr) self.ok.config(state="disabled") self.packageList.focus_set() elif len(self.bidVar.get()) == 0: self.logger.log('Please enter build ID to flash or use "latest" to get the newest', status_callback=self.printErr) self.bidVar.set('latest') else: result = True return result def updateBuildId(self, event=None): if len(self.engList.curselection()) != 0: self.refreshPackageList() def pressReturnKey(self, event=None): if self.selection_all_checked(): self.ok.config(state="disabled") self.confirm() def deviceOnSelect(self, evt): self.setVersionList() def versionOnSelect(self, evt): self.setEngList() def engOnSelect(self, evt): self.refreshPackageList() # hard coded right now def packageOnSelect(self, evt): self.ok.config(state="normal") def confirm(self): self.mutex.acquire() try: if self.selection_all_checked(): self.ok.config(state="disabled") params = [] package = self.packageList.get(self.packageList.curselection()[0]) self.logger.log('Start to flash [' + package + '].', status_callback=self.printErr) if(PathParser._IMAGES in package): params.append(PathParser._IMAGES) else: if(PathParser._GAIA in package): params.append(PathParser._GAIA) if(PathParser._GECKO in package): params.append(PathParser._GECKO) self.controller.doFlash(params) self.packageList.select_clear(0, END) self.controller.transition(self) finally: self.mutex.release() def setDeviceList(self, device=[]): self.deviceList.delete(0, END) for li in device: self.deviceList.insert(END, li) def setVersionList(self, version=[]): if len(version) == 0: version = self.data[ self.deviceList.get(self.deviceList.curselection()) ] self.versionList.config(state="normal") self.engList.config(state="disabled") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.versionList.delete(0, END) for li in version: self.versionList.insert(END, li) def setEngList(self, eng=[]): if len(eng) == 0: device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.data[device][version] self.engList.config(state="normal") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.engList.delete(0, END) for li in eng: self.engList.insert(END, li) def refreshPackageList(self): self.mutex.acquire() try: self.packageList.config(state="normal") self.ok.config(state="normal") self.packageList.delete(0, END) device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.engList.get(self.engList.curselection()) # if the value is '' or 'latest', the set the build_id option as ''. buildId = '' if (len(self.bidVar.get()) == 0 or self.bidVar.get() == 'latest') else self.bidVar.get() package = self.controller.getPackages(self.data[device][version][eng]['src'], build_id=buildId) if len(package) == 0: package = [PathParser._GAIA_GECKO, PathParser._GAIA, PathParser._GECKO, PathParser._IMAGES] for li in package: self.packageList.insert(END, li) finally: self.mutex.release()
#-------- 1) Initialisation --------------------------- from Tkinter import Tk, Entry, Label from math import * #-------- 2) Composants graphiques -------------------- mw = Tk() mw.title("Eval") entry = Entry(mw) label = Label(mw) #-------- 3) Positionnement des composants ------------ entry.pack() label.pack() #-------- 4) Definition des interactions -------------- def evaluer(event): label.configure(text="Resultat = " + str(eval(entry.get()))) #-------- 5) Gestion des evenements ------------------ entry.bind("<Return>", evaluer) mw.mainloop() exit(0)
class SearchBox(Frame): def __init__(self, master, entry_width=30, entry_font=None, entry_background="white", entry_highlightthickness=1, button_text="Search", button_ipadx=10, button_background="#009688", button_foreground="white", button_font=None, opacity=0.8, placeholder=None, placeholder_font=None, placeholder_color="grey", spacing=3, command=None): Frame.__init__(self, master) self._command = command self.entry = Entry(self, width=entry_width, background=entry_background, highlightcolor=button_background, highlightthickness=entry_highlightthickness) self.entry.pack(side=LEFT, fill=BOTH, ipady=1, padx=(0, spacing)) if entry_font: self.entry.configure(font=entry_font) if placeholder: add_placeholder_to(self.entry, placeholder, color=placeholder_color, font=placeholder_font) self.entry.bind("<Escape>", lambda event: self.entry.nametowidget(".").focus()) self.entry.bind("<Return>", self._on_execute_command) opacity = float(opacity) if button_background.startswith("#"): r, g, b = hex2rgb(button_background) else: # Color name r, g, b = master.winfo_rgb(button_background) r = int(opacity * r) g = int(opacity * g) b = int(opacity * b) if r <= 255 and g <= 255 and b <= 255: self._button_activebackground = '#%02x%02x%02x' % (r, g, b) else: self._button_activebackground = '#%04x%04x%04x' % (r, g, b) self._button_background = button_background self.button_label = Label(self, text=button_text, background=button_background, foreground=button_foreground, font=button_font) if entry_font: self.button_label.configure(font=button_font) self.button_label.pack(side=LEFT, fill=Y, ipadx=button_ipadx) self.button_label.bind("<Enter>", self._state_active) self.button_label.bind("<Leave>", self._state_normal) self.button_label.bind("<ButtonRelease-1>", self._on_execute_command) def get_text(self): entry = self.entry if hasattr(entry, "placeholder_state"): if entry.placeholder_state.contains_placeholder: return "" else: return entry.get() else: return entry.get() def set_text(self, text): entry = self.entry if hasattr(entry, "placeholder_state"): entry.placeholder_state.contains_placeholder = False entry.delete(0, END) entry.insert(0, text) def clear(self): self.entry_var.set("") def focus(self): self.entry.focus() def _on_execute_command(self, event): text = self.get_text() self._command(text) def _state_normal(self, event): self.button_label.configure(background=self._button_background) def _state_active(self, event): self.button_label.configure(background=self._button_activebackground)
class pump_ui(object): def __init__(self): master = Tk() master.style = ttk.Style() master.style.theme_use("default") master.config(bg=background_colour) master.resizable( 0, 0 ) # Disable resizing the UI to prevent having to make widget placing dynamic master.winfo_toplevel().title(frame_title) master.iconbitmap("bitcoin.ico") # Create pumper assistant to store data on the current BTC and alt holdings. self.pumper = pumper() self.create_title(master) self.create_api_info(master, previous_row=0) self.create_auto_sell(master, previous_row=3) self.create_stop_loss(master, previous_row=4) self.create_order_type(master, previous_row=6) self.create_fee_type(master, previous_row=7) self.create_btc_balance_picker(master, previous_row=8) self.create_alt_ticker(master, previous_row=10) self.create_pump_and_sell_buttons(master, previous_row=11) self.create_current_profit(master, previous_row=12) self.create_output_box(master, rightmost_column=1) # Can hardcode API key and Secret #self.api_key_entry.delete(0,END) #self.api_key_entry.insert(0,"KEY") #self.api_key_entry.config(state=DISABLED) #self.api_secret_entry.delete(0, END) #self.api_secret_entry.insert(0, "SECRET") #self.api_secret_entry.config(state=DISABLED) # Display the UI, this can only be called once per program. # Nothing in the main Python script will be run after creating the UI because of this. master.mainloop() def create_title(self, master, previous_row=-1, previous_column=-1): empty = Label(master, text=frame_title) empty.grid(row=previous_row + 1, column=previous_column + 2, columnspan=1) empty.config(bg=background_colour, fg=label_font_colour) def create_api_info(self, master, previous_row=-1, previous_column=-1): api_key_lbl = Label(master, text="API Key:") api_key_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0)) api_key_lbl.config(bg=background_colour, fg=label_font_colour) self.api_key_entry = Entry(master, highlightthickness=0, bd=0, width=21, show="*") self.api_key_entry.config(borderwidth=2, relief=default_relief) self.api_key_entry.grid(row=previous_row + 1, column=previous_column + 2) api_secret_lbl = Label(master, text="API Secret:") api_secret_lbl.grid(row=previous_row + 2, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0)) api_secret_lbl.config(bg=background_colour, fg=label_font_colour) self.api_secret_entry = Entry(master, highlightthickness=0, bd=0, width=21, show="*") self.api_secret_entry.config(borderwidth=2, relief=default_relief) self.api_secret_entry.grid(row=previous_row + 2, column=previous_column + 2) self.api_connect_btn = Button(master, text="Connect To Binance", command=self.on_connect_api) self.api_connect_btn.grid(row=previous_row + 3, column=previous_column + 2, columnspan=1, sticky=W + E, padx=10, pady=(0, 3)) self.api_connect_btn.config(highlightbackground=background_colour) def create_auto_sell(self, master, previous_row=-1, previous_column=-1): auto_sell_lbl = Label(master, text="Auto Sell (%):") auto_sell_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0)) auto_sell_lbl.config(bg=background_colour, fg=label_font_colour) self.auto_sell_spinbox = Spinbox(master, from_=1.0, to=300.0, increment=1.0, highlightbackground=background_colour) self.auto_sell_spinbox.config(borderwidth=2, relief=default_relief) self.auto_sell_spinbox.grid(row=previous_row + 1, column=previous_column + 2) self.auto_sell_spinbox.delete(0, "end") self.auto_sell_spinbox.insert(0, 50) def create_stop_loss(self, master, previous_row=-1, previous_column=-1): stop_loss_lbl = Label(master, text="Stop Loss (%):") stop_loss_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0)) stop_loss_lbl.config(bg=background_colour, fg=label_font_colour) self.stop_loss_spinbox = Spinbox(master, from_=-100.0, to=-10.0, increment=1.0, highlightbackground=background_colour) self.stop_loss_spinbox.config(borderwidth=2, relief=default_relief) self.stop_loss_spinbox.grid(row=previous_row + 1, column=previous_column + 2) self.stop_loss_spinbox.delete(0, "end") self.stop_loss_spinbox.insert(0, -10) def create_btc_balance_picker(self, master, previous_row=-1, previous_column=-1): self.btc_balance_str = StringVar() btc_balance_lbl = Label(master, textvar=self.btc_balance_str) btc_balance_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=2, sticky=W + E, padx=(3, 0)) btc_balance_lbl.config(bg=background_colour, fg=label_font_colour) self.set_available_btc_balance(Decimal(0)) btc_to_use_label = Label(master, text="BTC to spend:", bg=background_colour, fg=label_font_colour) btc_to_use_label.grid(row=previous_row + 2, column=previous_column + 1, sticky=E, padx=(3, 0)) self.btc_to_use_spinbox = Spinbox( master, from_=minimum_trade, to=minimum_trade, increment=btc_to_use_increment, highlightbackground=background_colour) self.btc_to_use_spinbox.config(borderwidth=2, relief=default_relief) self.btc_to_use_spinbox.grid(row=previous_row + 2, column=previous_column + 2) def create_order_type(self, master, previous_row=-1, previous_column=-1): order_type_lbl = Label(master, text="Entry Type:") order_type_lbl.grid(row=previous_row + 1, column=previous_column + 1, sticky=E, padx=(3, 0)) order_type_lbl.config(bg=background_colour, fg=label_font_colour) self.is_entry_market = True def change_order_type(*args): self.is_entry_market = (self.order_type.get() == "Market Buy \/") self.order_type = StringVar() self.order_type.trace( "w", change_order_type ) # Reduces how much work is done when the pump starts choices = {"Market Buy \/", "Limit Buy \/"} self.entry_type_option_menu = OptionMenu(master, self.order_type, *choices) self.entry_type_option_menu.grid(row=previous_row + 1, column=previous_column + 2, sticky=W + E, padx=8) self.entry_type_option_menu.config(highlightthickness=0) self.entry_type_option_menu.configure(indicatoron=0) self.order_type.set("Market Buy \/") def create_fee_type(self, master, previous_row=-1, previous_column=-1): fee_type_lbl = Label(master, text="Fee Type:") fee_type_lbl.grid(row=previous_row + 1, column=previous_column + 1, sticky=E, padx=(3, 0)) fee_type_lbl.config(bg=background_colour, fg=label_font_colour) self.is_using_bnb = True def change_fee_type(*args): self.is_using_bnb = ( self.order_type.get() == "Binance Coin (BNB) \/") self.fee_type = StringVar() self.fee_type.trace( "w", change_fee_type ) # Reduces how much work is done when the pump starts choices = {"Binance Coin (BNB) \/", "0.1% Of All Trades \/"} self.fee_type_option_menu = OptionMenu(master, self.fee_type, *choices) self.fee_type_option_menu.grid(row=previous_row + 1, column=previous_column + 2, sticky=W + E, padx=8) self.fee_type_option_menu.config(highlightthickness=0) self.fee_type_option_menu.configure(indicatoron=0) self.fee_type.set("Binance Coin (BNB) \/") def create_pump_and_sell_buttons(self, master, previous_row=-1, previous_column=-1): # Manual sell button can only be activated after initiating a pump. self.manual_sell_btn = Button(master, text="Sell", state=DISABLED, command=self.on_manual_sell) self.manual_sell_btn.grid(row=previous_row + 1, column=previous_column + 1, sticky=W + E, padx=(3, 0)) self.manual_sell_btn.config(highlightbackground=background_colour) self.pump_btn = Button(master, text="Pump", command=self.on_pump) self.pump_btn.grid(row=previous_row + 1, column=previous_column + 2, sticky=W + E, padx=8) self.pump_btn.config(highlightbackground=background_colour, state=DISABLED) def create_alt_ticker(self, master, previous_row=-1, previous_column=-1): ticker_lbl = Label(master, text="Ticker To Pump:") ticker_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0), pady=(0, 8)) ticker_lbl.config(bg=background_colour, fg=label_font_colour) self.ticker_entry = Entry(master, highlightthickness=0, bd=0, width=21) self.ticker_entry.config(borderwidth=2, relief=default_relief) self.ticker_entry.grid(row=previous_row + 1, column=previous_column + 2, pady=8) self.ticker_entry.bind('<Return>', self.on_pump_shortcut) def create_current_profit(self, master, previous_row=-1, previous_column=-1): self.current_profit_str = StringVar() current_profit_lbl = Label(master, textvar=self.current_profit_str) current_profit_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=2, sticky=W + E, padx=3, pady=(0, 3)) current_profit_lbl.config(bg=background_colour, fg=label_font_colour) self.current_profit_str.set("Current Profit: 0%") def create_output_box(self, master, rightmost_column): self.pump_output = StringVar() console_lbl = Label(master, textvar=self.pump_output, borderwidth=2, relief=default_relief, anchor=N) console_lbl.grid(row=0, column=rightmost_column + 1, columnspan=1, rowspan=14, padx=(10, 0), pady=0) console_lbl.config(width=50, height=22, bg="black", font=Font(family="Courier", size=9), fg="white") self.lines = 0 def disable_pre_pump_options(self): # Change the buttons that can be clicked to prevent the user # from trying to pump multiple coins with one bot. self.manual_sell_btn.config(state=NORMAL) self.pump_btn.config(state=DISABLED) self.btc_to_use_spinbox.config(state=DISABLED) self.ticker_entry.config(state=DISABLED) self.auto_sell_spinbox.config(state=DISABLED) self.stop_loss_spinbox.config(state=DISABLED) self.api_key_entry.config( state=DISABLED) # Comment out if hardcoding key self.api_secret_entry.config( state=DISABLED) # Comment out if hardcoding secret self.api_connect_btn.config(state=DISABLED) self.entry_type_option_menu.config(state=DISABLED) self.fee_type_option_menu.config(state=DISABLED) def enable_pump_options(self): # Change the buttons that can be clicked to prevent the user # from trying to pump multiple coins with one bot. self.manual_sell_btn.config(state=DISABLED) self.pump_btn.config(state=NORMAL) self.btc_to_use_spinbox.config(state=NORMAL) self.ticker_entry.config(state=NORMAL) self.auto_sell_spinbox.config(state=NORMAL) self.stop_loss_spinbox.config(state=NORMAL) self.api_key_entry.config( state=NORMAL) # Comment out if hardcoding key self.api_secret_entry.config( state=NORMAL) # Comment out if hardcoding secret self.api_connect_btn.config(state=NORMAL) self.entry_type_option_menu.config(state=NORMAL) self.fee_type_option_menu.config(state=NORMAL) def set_available_btc_balance(self, btc_balance): self.pumper.btc_balance = btc_balance self.btc_balance_str.set("Available Balance: " + readable_btc_balance(btc_balance)) def set_current_profit(self, current_profit): self.current_profit_str.set( "Current Profit: " + '{0:.3f}'.format(round(current_profit * Decimal(100), 3)) + "%") def write_to_console(self, line): self.lines += 1 if self.lines > max_lines_in_console: i = self.pump_output.get().index('\n') self.pump_output.set(self.pump_output.get()[i + 1:] + "\n" + line) elif self.lines == 1: self.pump_output.set(line) else: self.pump_output.set(self.pump_output.get() + "\n" + line) #### Button Behaviour #### def on_pump(self): try: api = self.api btc_to_use = Decimal(self.btc_to_use_spinbox.get()) except InvalidOperation: # The BTC to spend box is empty. self.write_to_console("Stop!") self.write_to_console("BTC to spend cannot be empty.") return except AttributeError: # There is no API object. self.write_to_console( "You need to connect to Binance before pumping.") return if btc_to_use >= minimum_trade: if btc_to_use <= self.pumper.btc_balance: target_profit_percentage = Decimal( float(self.auto_sell_spinbox.get()) / 100.0) # Validate auto-sell and stop loss if target_profit_percentage <= Decimal(0): self.write_to_console("Auto sell has to be positive.") return if Decimal(self.stop_loss_spinbox.get()) >= Decimal(0): self.write_to_console("Stop loss has to be negative.") return ticker = self.ticker_entry.get().upper() # Empty strings are False in Python if ticker: full_ticker = api.full_ticker_for(ticker) try: alt = self.api.get_ticker(symbol=full_ticker) except BinanceAPIException, e: logging.debug(str(e)) self.write_to_console("Invalid ticker.") return alt_value = Decimal(alt["askPrice"]) # Used in console output decimal_points = minimum_decimals_in_quantity.get( full_ticker, 0) self.pumper.decimal_points_in_alt = decimal_points self.pumper.set_up(btc_to_use, target_profit_percentage, alt_value, ticker) if self.is_entry_market: self.pumper.alt_holdings = api.market_buy( self.pumper.btc_to_use, full_ticker, self.is_using_bnb) self.write_to_console( "Bought " + readable_alt_balance( decimal_points, pumper=self.pumper) + " with " + readable_btc_balance(btc_to_use) + ".") else: highest_bid = Decimal(alt["bidPrice"]) if alt_value - highest_bid <= Decimal(0.00000001): to_bid = highest_bid else: # Bid between the highest bid and the lowest ask for the best odds of being filled. to_bid = (alt_value - highest_bid) / 2 + highest_bid to_bid = Decimal( floor(to_bid * Decimal(100000000.0)) ) / Decimal(100000000.0) self.pumper.starting_alt_value = to_bid expected = api.limit_buy( btc_to_alt(btc_to_use, alt_value), pumper, full_ticker, to_bid, self.is_using_bnb) self.write_to_console("Buying " + readable_alt_balance( decimal_points, alt_amount=expected, ticker=ticker ) + " for " + readable_btc_balance(btc_to_use) + ".") self.write_to_console( "This is a limit order, it may not get filled.") self.disable_pre_pump_options() self.set_stop_loss() self.start_monitoring_orderbook(full_ticker) else: # The user is trying to trade with more than they actually have. self.write_to_console("You did not enter a ticker.") else: # The user is trying to trade with more than they actually have. self.write_to_console("Stop!") self.write_to_console( "You are trying to spend more BTC than you have.") else:
class LoginFrame(Frame): """Class which controls the Login and Register screens of the spelling aid""" def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.db = self.parent.db #Create login screen widgets font = ("Helvetica", 20) self.userEntry = Entry(self.parent, width=15, font=font) self.passEntry = Entry(self.parent, width=15, show='*', font=font) self.passEntry.bind('<Return>', self.login) buttonSubmit = Button(self.parent, text="Login", command=self.login, width=10) buttonRegSwitch = Button(self.parent, text="New User", command=self.viewRegister, width=10) #Create register screen widgets self.userRegEntry = Entry(self.parent, width=15, font=font) self.passRegEntry = Entry(self.parent, width=15, show='*', font=font) self.passRegEntry.bind('<Return>', self.register) buttonRegister = Button(self.parent, text="Register", command=self.register, width=10) buttonBack = Button(self.parent, text="Back", command=self.viewLogin, width=10) #Create a canvas for each screen and populate self.login_canvas = Canvas(self, width=600, height=250, bg="#FFFFFF") self.register_canvas = Canvas(self, width=600, height=250, bg="#FFFFFF") self.login_canvas.create_text(300, 40, text="Login", font=font, fill="#004183") self.login_canvas.create_text(170, 80, text="Username:"******"Password:"******"Register", font=font, fill="#004183") self.register_canvas.create_text(170, 80, text="Username:"******"Password:"******"Check the user's input and allow access if it is correct""" usernameGiven = self.userEntry.get() passwordGiven = self.passEntry.get() userDetails = self.db.sql("""SELECT * FROM users WHERE username='******'""" %(usernameGiven.lower().strip())) #Check that the username exists if len(userDetails)==1: passHash = userDetails[0][2] #Check that the password is correct if (hashlib.sha1(passwordGiven).hexdigest() == passHash): #Details are correct, unlock application self.parent.login(User(userDetails[0])) loginFailed = False else: loginFailed = True else: loginFailed = True if loginFailed: #If details are incorrect show an error message tkMessageBox.showerror("Login Failed", "Invalid username or password") self.userEntry.delete(0, END) self.passEntry.delete(0, END) def register(self): """Register a new user with provided input""" username = self.userRegEntry.get() passwd = self.passRegEntry.get() if username != '' and passwd != '': username = username.lower().strip() passHash = hashlib.sha1(passwd).hexdigest() self.db.sql("""INSERT INTO users (username, passwd) VALUES ('%s', '%s')"""%(username, passHash)) self.viewLogin() def viewRegister(self): """Switch to the register screen""" self.login_canvas.pack_forget() self.register_canvas.pack() def viewLogin(self): """Switch to the login screen""" self.register_canvas.pack_forget() self.login_canvas.pack()
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 ListPage(BasePage): def __init__(self, parent, controller): BasePage.__init__(self, parent, controller) self.target_keep_profile_var = IntVar() self.mutex = Lock() def prepare(self): self.deviceList.config(state='normal') self.versionList.config(state='disabled') self.engList.config(state='disabled') self.packageList.config(state='disabled') self.ok.config(state='disabled') self.setData(self.controller.data) self.setDeviceList(self.data.keys()) self.controller.setDefault(self, self.controller.loadOptions()) self.deviceList.focus_force() def printErr(self, message): self.errLog.config(text=message) def setData(self, data): self.data = data def setupView(self, title="Select your flash", data=None): if (data): self.setData(data) self.errLog = Label(self, text="") self.errLog.grid(row=4, column=1, columnspan=3, sticky="NWSE") self.desc = Label(self, text=title, font=TITLE_FONT) self.desc.grid(row=0, column=0, columnspan=2) self.ok = Button(self, text='Next', command=lambda: self.confirm()) self.ok.grid(row=4, column=3, sticky="E") self.ok.config(state="disabled") # bind self.target_keep_profile_var (IntVar) to keepProfileCheckbutton, 1 is True, 0 is Flase self.keepProfileCheckbutton = Checkbutton( self, text="Keep User Profile (BETA)", variable=self.target_keep_profile_var) self.keepProfileCheckbutton.grid(row=5, column=0, columnspan=4, sticky="W") self.deviceLabel = Label(self, text="Device", font=TITLE_FONT) self.deviceLabel.grid(row=1, column=0) self.deviceList = Listbox(self, exportselection=0) self.deviceList.grid(row=2, column=0) self.deviceList.bind('<<ListboxSelect>>', self.deviceOnSelect) self.deviceList.config(state="disabled") self.versionLabel = Label(self, text="Branch", font=TITLE_FONT) self.versionLabel.grid(row=1, column=1) self.versionList = Listbox(self, exportselection=0) self.versionList.grid(row=2, column=1) self.versionList.bind('<<ListboxSelect>>', self.versionOnSelect) self.versionList.config(state="disabled") self.engLabel = Label(self, text="Build Type", font=TITLE_FONT) self.engLabel.grid(row=1, column=2) self.engList = Listbox(self, exportselection=0) self.engList.grid(row=2, column=2) self.engList.bind('<<ListboxSelect>>', self.engOnSelect) self.engList.config(state="disabled") self.packageLabel = Label(self, text="Gecko/Gaia/Full", font=TITLE_FONT) self.packageLabel.grid(row=1, column=3) self.packageList = Listbox(self, exportselection=0) self.packageList.grid(row=2, column=3) self.packageList.bind('<<ListboxSelect>>', self.packageOnSelect) self.packageList.config(state="disabled") self.bidVar = StringVar() Label(self, text="Build ID").grid(row=3, column=0, sticky='E') self.bidInput = Entry(self, textvariable=self.bidVar, width="30") self.bidInput.grid(row=3, column=1, columnspan=2, sticky="W") self.bidVar.set('latest') # binding unfocus for build id field self.bidInput.bind('<FocusOut>', self.updateBuildId) # binding the Return Key to each componments self.deviceList.bind('<Return>', self.pressReturnKey) self.versionList.bind('<Return>', self.pressReturnKey) self.engList.bind('<Return>', self.pressReturnKey) self.packageList.bind('<Return>', self.pressReturnKey) self.bidInput.bind('<Return>', self.pressReturnKey) self.ok.bind('<Return>', self.pressReturnKey) def selection_all_checked(self): result = False if len(self.deviceList.curselection()) == 0: self.logger.log('Please select device.', status_callback=self.printErr) self.ok.config(state="disabled") self.deviceList.focus_set() elif len(self.versionList.curselection()) == 0: self.logger.log('Please select branch.', status_callback=self.printErr) self.ok.config(state="disabled") self.versionList.focus_set() elif len(self.engList.curselection()) == 0: self.logger.log('Please select user or engineer build.', status_callback=self.printErr) self.ok.config(state="disabled") self.engList.focus_set() elif len(self.packageList.curselection()) == 0: self.logger.log('Please select package to flash.', status_callback=self.printErr) self.ok.config(state="disabled") self.packageList.focus_set() elif len(self.bidVar.get()) != 14 and self.bidVar.get() != 'latest': self.logger.log( 'Please enter build ID to flash or use "latest" to get the newest', status_callback=self.printErr) self.logger.log(self.bidVar.get() + ' is invalid: ' + str(len(self.bidVar.get()))) self.bidVar.set('latest') else: result = True return result def updateBuildId(self, event=None): # if the value is '' or 'latest', the set the build_id option as ''. buildId = self.bidVar.get() if buildId == 'latest': buildId = '' elif len(buildId) != 14: self.printErr("Invalid build ID: " + buildId + ", reset to latest") buildId = '' self.bidVar.set('latest') else: if len(self.engList.curselection()) != 0: self.refreshPackageList() def pressReturnKey(self, event=None): if self.selection_all_checked(): self.ok.config(state="disabled") self.confirm() def deviceOnSelect(self, evt): self.setVersionList() def versionOnSelect(self, evt): self.setEngList() def engOnSelect(self, evt): self.refreshPackageList() # hard coded right now def packageOnSelect(self, evt): self.ok.config(state="normal") def confirm(self): self.mutex.acquire() try: if self.selection_all_checked(): self.ok.config(state="disabled") params = [] package = self.packageList.get( self.packageList.curselection()[0]) self.logger.log('Start to flash [' + package + '].', status_callback=self.printErr) if (PathParser._IMAGES in package): params.append(PathParser._IMAGES) else: if (PathParser._GAIA in package): params.append(PathParser._GAIA) if (PathParser._GECKO in package): params.append(PathParser._GECKO) keep_profile = (self.target_keep_profile_var.get() == 1) archives = self.controller.do_download(params) self.controller.do_flash(params, archives, keep_profile=keep_profile) self.packageList.select_clear(0, END) self.controller.transition(self) finally: self.mutex.release() def setDeviceList(self, device=[]): self.deviceList.delete(0, END) for li in device: self.deviceList.insert(END, li) def setVersionList(self, version=[]): if len(version) == 0: version = self.data[self.deviceList.get( self.deviceList.curselection())] self.versionList.config(state="normal") self.engList.config(state="disabled") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.versionList.delete(0, END) for li in version: self.versionList.insert(END, li) def setEngList(self, eng=[]): if len(eng) == 0: device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.data[device][version] self.engList.config(state="normal") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.engList.delete(0, END) for li in eng: self.engList.insert(END, li) def refreshPackageList(self): self.mutex.acquire() try: self.packageList.config(state="normal") self.ok.config(state="normal") self.packageList.delete(0, END) device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.engList.get(self.engList.curselection()) buildId = '' if (len(self.bidVar.get()) == 0 or self.bidVar.get() == 'latest') else self.bidVar.get() package = self.controller.getPackages( self.data[device][version][eng]['src'], build_id=buildId) if len(package) == 0: self.logger.log('Invalid build ID: ' + buildId + ', reset to latest', status_callback=self.printErr) buildId = '' self.bidVar.set('latest') package = self.controller.getPackages( self.data[device][version][eng]['src'], build_id=buildId) for li in package: self.packageList.insert(END, li) finally: self.mutex.release()
class AuthPage(BasePage): def __init__(self, parent, controller): self.is_auth = False self.mutex = Lock() BasePage.__init__(self, parent, controller) def prepare(self): mode = self.mode.get() user = self.userVar.get() pwd = self.pwdVar.get() if mode is 1 and user and pwd: self.confirm(mode, user, pwd) self.userInput.focus_force() def printErr(self, message): self.errLog.config(text=message) def entryToggle(self, toggle, target): if (toggle): for t in target: t.configure(state='normal') else: for t in target: t.configure(state='disabled') def confirm(self, mode, user, pwd): self.mutex.acquire() try: if mode == 1 and not self.is_auth: # mode:1 flash from pvt # TODO: the GUI do not updated due to the correct way to update the UI in tk is to use the after method. self.logger.log('Logging into server...', status_callback=self.printErr) if self.controller.setAuth(user, pwd): self.is_auth = True self.ok.config(state="disabled") self.userInput.config(state="disabled") self.pwdInput.config(state="disabled") self.controller.transition(self) else: self.printErr("Auththentication failed") else: # mode:2, flash from local pass finally: self.mutex.release() def pressReturnKey(self, event=None): if len(self.userVar.get()) > 0 and len(self.pwdVar.get()) > 0: self.confirm(self.mode.get(), self.userVar.get(), self.pwdVar.get()) elif len(self.userVar.get()) == 0: self.logger.log('Please enter username.', status_callback=self.printErr) self.userInput.focus_set() else: self.logger.log('Please enter password.', status_callback=self.printErr) self.pwdInput.focus_set() def setupView(self, title="Test Auth Page", user='', pwd_ori=''): self.mode = IntVar() self.mode.set(1) Label(self, width=25).grid(row=1, column=0, columnspan=2) self.errLog = Label(self, text="") self.errLog.grid(row=4, column=1, columnspan=3, rowspan=3, sticky="NWSE") self.userVar = StringVar() self.pwdVar = StringVar() Label(self, text="Account").grid(row=2, column=1, sticky='E') self.userInput = Entry(self, textvariable=self.userVar, width="30") self.userInput.grid(row=2, column=2, columnspan=2, sticky="W") Label(self, text="Password").grid(row=3, column=1, sticky='E') self.pwdInput = Entry(self, textvariable=self.pwdVar, show="*", width="30") self.pwdInput.grid(row=3, column=2, columnspan=2, sticky="W") self.userVar.set(user) self.pwdVar.set(pwd_ori) Label(self, text=' Welcome to fxos flash tool', font=TITLE_FONT).grid(row=0, column=1, columnspan=3, sticky="WE") Radiobutton(self, state='disabled', text='Download build from pvt', variable=self.mode, value=1, command=lambda: self.entryToggle( True, [self.userInput, self.pwdInput])).grid( row=1, column=2, columnspan=2, sticky="E") Radiobutton(self, state='disabled', text='Flash build from local', variable=self.mode, value=2, command=lambda: self.entryToggle( False, [self.userInput, self.pwdInput])).grid( row=1, column=4, sticky="W") self.ok = Button(self, text='Next', command=lambda: self.confirm(self.mode.get( ), self.userVar.get(), self.pwdVar.get())) self.ok.grid(row=4, column=4, sticky="W") self.userInput.bind('<Return>', self.pressReturnKey) self.pwdInput.bind('<Return>', self.pressReturnKey) self.ok.bind('<Return>', self.pressReturnKey)
class App: def __init__(self, master): self.master = master self.file = 'grid.csv' self.ownZepName = "goud" self.updatingFlag = False self.btnUpPressed = False self.btnDownPressed = False self.btnLeftPressed = False self.btnRightPressed = False self.btnPlusPressed = False self.btnMinusPressed = False #keyListener aanzetten master.bind("<Key>", self.keyPressed) master.bind("<KeyRelease>", self.keyReleased) leftFrame = Frame(master, width = 200, height = 640) leftFrame.grid(row = 0, column = 0) debugFrame = Frame(leftFrame, width = 200, height = 400) debugFrame.grid(row = 0, column = 0) controlFrame = Frame(leftFrame, width = 200, height = 200) controlFrame.grid(row = 1, column = 0, pady = 10) rasterFrame = Frame(master, width = 600, height = 640) rasterFrame.grid(row = 0, column = 1) #Scrolledtext in leftTopFrame self.scrDebug = ScrolledText(debugFrame, wrap = WORD, state = "disabled", fg = "dark red", width=80) self.scrDebug.grid(row = 0, column = 0, padx = 10, pady = 10) #Buttons #simulator self.btnToggleSimu = Button(controlFrame, text = "Simulator", width = 14, bg = 'gray85', command = lambda: self.toggleSimulator()) self.btnToggleSimu.grid(row = 3, column = 2) self.btnMoveToSimu = Button(controlFrame, text = "Ga naar (Sim)", width = 14, bg = 'gray85', command = lambda: self.moveTo(Name = "goudsimu")) self.btnMoveToSimu.grid(row = 1, column = 4) self.btnHeightSimu = Button(controlFrame, text = "Kies hoogte (Sim)", width = 14, bg = 'gray85', command = lambda: self.setGewensteHoogte(Name ="goudsimu")) self.btnHeightSimu.grid(row = 2, column = 4) #hoogte self.gemetenHoogteString = StringVar() self.gemetenHoogteString.set(str(0)) self.lblGemetenHoogte = Label(controlFrame, text="Gemeten Hoogte: ", anchor = "w") self.lblGemetenHoogteVar = Label(controlFrame, textvariable = self.gemetenHoogteString, width = 20) self.lblGemetenHoogte.grid(row=0, column=2) self.lblGemetenHoogteVar.grid(row=0, column=3) #move to self.btnMoveTo = Button(controlFrame, text="Ga naar (Zep)", bg = 'gray85', width = 14, command = lambda: self.moveTo()) self.btnMoveTo.grid(row=1,column=2) self.txtMoveTo = Entry(controlFrame, width=24) self.txtMoveTo.grid(row=1, column=3) self.txtMoveTo.bind('<Return>', self.moveTo) #hoogte self.btnHeight = Button(controlFrame, text="Kies hoogte (Zep)", bg = 'gray85', width = 14, command = lambda: self.setGewensteHoogte()) self.btnHeight.grid(row=2,column=2) self.txtHeight = Entry(controlFrame, width=24) self.txtHeight.grid(row=2, column=3) self.txtHeight.bind('<Return>', self.setGewensteHoogte) #images self.display = Canvas(rasterFrame, width=600, height=570, bd=0, highlightthickness=0) self.display.grid(row=0, column = 0, sticky=W+E+N+S) foundFigures = Label(controlFrame, text = "Herkende figuren:") foundFigures.grid(row = 0, column = 0) self.display2 = Canvas(controlFrame, width = 220, height=165, bd=2, relief = "groove", highlightthickness=0) self.display2.grid(row=1, column = 0, sticky=W+E+N+S, rowspan=12) self.latestphoto = Image.new("RGB", (220,165), (150,150,150)) self.latestImage = ImageTk.PhotoImage(self.latestphoto) self.display2.create_image(0, 0, image=self.latestImage, anchor=NW) #goal original = Image.open('goalPin.png') resized = original.resize((60,60),Image.ANTIALIAS) self.goalImage = ImageTk.PhotoImage(resized) self.makeBackground() self.initZeppelins() self.paintCanvas() self.sim = None mq.setGUI(self) def initZeppelins(self): self.zeppelins = [] self.goal = (-100,-100) # self.zeppelins.append(AbstractZeppelin('red', 'simu')) self.zeppelins.append(AbstractZeppelin('#EBB400', self.ownZepName)) def convToPixelCoords(self, pos): cmHeight = 34.6410162 cmWidth = 40.0 xcm, ycm = pos x = self.evenXStart + (xcm/cmWidth)*self.triangleWidth y = self.yStart + (ycm/cmHeight)*self.triangleHeight result = (x,y) return result def createPhoto(self, cvresults): self.latestphoto = Image.new("RGB", (220,165), (150,150,150)) cv = eval(cvresults) width = cv[0] height = cv[1] figures = cv[2] coordinates = cv[3] for i in xrange(0,len(figures)): j = self.allShapes.index(figures[i]) image = self.shapeImages[j] xcoord = int(coordinates[i][0]/(width*1.0)*220) ycoord = int(coordinates[i][1]/(height*1.0)*165) self.latestphoto.paste(image, (xcoord-12, ycoord-12), mask = image) self.latestImage = ImageTk.PhotoImage(self.latestphoto) self.display2.create_image(0, 0, image=self.latestImage, anchor=NW) def makeBackground(self): #rooster inlezen: f = open("../positioning/"+ str(self.file), 'r') shapesText = f.read() self.raster = [] self.tabletLocations = [] nrows = 0 ncol = 0 for line in shapesText.split("\n"): temp = line.split(",") if not len(temp) == 2: nrows += 1 if ncol == 0: ncol = len(temp) for s in temp: self.raster.append(s.strip()) else: self.tabletLocations.append((int(temp[0]), int(temp[1]))) f.close() tempWidth1 = 600/ncol tempHeight1 = int(round((math.sqrt(tempWidth1**2 - (tempWidth1/2)**2)), 0)) tempHeight2 = 570/nrows+2 tempWidth2 = int(round((math.sqrt(4/3 * tempHeight2**2)),0)) #raster self.resizedRaster = Image.new("RGB", (600,570), (240,240,240)) #vormpjes self.allShapes = ['BC','BH','BR','BS','GC','GH','GR','GS','RC','RH','RR','RS','WC','WH','WR','WS','YC','YH','YR','YS'] self.shapeImages = [] for i in range(20): imgFile = "vormpjes/" + self.allShapes[i] + ".png" original = Image.open(imgFile) self.shapeImages.append(original.resize((24, 24),Image.ANTIALIAS)) original = Image.open("tablet.png") self.tabletIm = original.resize((40,40),Image.ANTIALIAS) self.xlen = ncol self.ylen = nrows self.triangleWidth = min(tempWidth1, tempWidth2) self.triangleHeight = min(tempHeight1, tempHeight2) self.evenXStart = (600-((ncol)*self.triangleWidth))/2 + self.triangleWidth/4 self.oddXStart = self.evenXStart + self.triangleWidth/2 self.yStart = (600-((nrows)*self.triangleHeight))/2 + self.triangleHeight/4 draw = ImageDraw.Draw(self.resizedRaster) #grid tekenen for y in range(self.ylen): for x in range(self.xlen): ycoord = self.yStart + y*self.triangleHeight zelf = self.raster[y*self.xlen + x] != "XX" if y>0: boven = self.raster[(y-1)*self.xlen + x] != "XX" if y<self.ylen-1: onder = self.raster[(y+1)*self.xlen + x] != "XX" if y>0 and x < self.xlen-1: oddboven = self.raster[(y-1)*self.xlen + x+1] != "XX" if y<self.ylen-1 and x < self.xlen-1: oddonder = self.raster[(y+1)*self.xlen + x+1] != "XX" if x<self.xlen-1: naast = self.raster[y*self.xlen + x+1] != "XX" if y % 2 == 0: xcoord = self.evenXStart + x*self.triangleWidth if x < self.xlen-1 and naast and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth, ycoord), fill = 0) if y < self.ylen-1 and onder and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord+self.triangleHeight), fill = 0) if y > 0 and boven and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord-self.triangleHeight), fill = 0) else: xcoord = self.oddXStart + x*self.triangleWidth if x < self.xlen-1 and naast and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth, ycoord), fill = 0) if y < self.ylen-1 and x < self.xlen-1 and oddonder and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord+self.triangleHeight), fill = 0) if y > 0 and x < self.xlen-1 and oddboven and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord-self.triangleHeight), fill = 0) del draw for loc in self.tabletLocations: conv = self.convToPixelCoords((loc[0]/10, loc[1]/10)) self.resizedRaster.paste(self.tabletIm, (int(conv[0])-20, int(conv[1])-20), mask = self.tabletIm) #vormpjes tekenen for y in range(self.ylen): for x in range(self.xlen): index = y*self.xlen + x if y % 2 == 0: xcoord = self.evenXStart + x*self.triangleWidth else: xcoord = self.oddXStart + x*self.triangleWidth ycoord = self.yStart + y*self.triangleHeight shape = self.raster[index] if shape != 'XX': image = self.shapeImages[self.allShapes.index(shape)] self.resizedRaster.paste(image, (xcoord-12, ycoord-12), mask = image) self.rasterImage = ImageTk.PhotoImage(self.resizedRaster) def updatePath(self): self.rasterBackup = self.rasterImage draw = ImageDraw.Draw(self.resizedRaster) for z in self.zeppelins: length = len(z.locations) if length > 1: prev = self.convToPixelCoords(z.locations[length-2]) current = self.convToPixelCoords(z.locations[length-1]) draw.line((prev[0], prev[1], current[0], current[1]), fill=z.color, width = 3) self.rasterImage = ImageTk.PhotoImage(self.resizedRaster) del draw def paintCanvas(self): #clear the canvas #self.display.delete('all') #rooster tekenen self.updatePath() self.display.create_image(0, 0, image=self.rasterImage, anchor=NW) #Testcode voor zeppelin locatie for z in self.zeppelins: if z.orientationFound: point1x = self.convToPixelCoords(z.location)[0]+16*math.sin(math.radians(z.orientation + 20)) point1y = self.convToPixelCoords(z.location)[1]+16*math.cos(math.radians(z.orientation + 20)) point2x = self.convToPixelCoords(z.location)[0]+16*math.sin(math.radians(z.orientation - 20)) point2y = self.convToPixelCoords(z.location)[1]+16*math.cos(math.radians(z.orientation - 20)) point3x = self.convToPixelCoords(z.location)[0]+28*math.sin(math.radians(z.orientation)) point3y = self.convToPixelCoords(z.location)[1]+28*math.cos(math.radians(z.orientation)) arrowPoints = [point1x, point1y, point2x, point2y, point3x, point3y] self.display.create_polygon(arrowPoints, fill=z.color, outline='black', width = 1) self.display.create_oval(self.convToPixelCoords(z.location)[0]-12, self.convToPixelCoords(z.location)[1]-12,self.convToPixelCoords(z.location)[0]+12, self.convToPixelCoords(z.location)[1]+12, fill=z.color) self.display.create_image(self.convToPixelCoords(self.goal)[0]+6, self.convToPixelCoords(self.goal)[1]-18, image = self.goalImage, anchor=CENTER) def toggleSimulator(self): if self.sim == None: enemy = "goudsimu" self.zeppelins.append(AbstractZeppelin("red", enemy)) mq.initEnemy(enemy) self.sim = simulator.simulator(100,100, enemy) return self.sim.toggleActive() def updateGoal(self, location, tablet): self.debugPrint("Nieuw doel voor simulator: " + str(tablet) + " " + str(location)) self.goal = self.convToPixelCoords(location) self.paintCanvas() def updateLocation(self, location, n): self.debugPrint("Nieuwe locatie voor " + n + " ontvangen: " + str(location)) for z in self.zeppelins: if z.name == n: z.updateLocation((location[0]/10, location[1]/10)) self.paintCanvas() def updateHeight(self, height, n): self.debugPrint("Nieuwe hoogte voor " + n + " ontvangen: " + str(height)) if self.ownZepName == n: self.gemetenHoogteString.set(str(height)) def updateAngle(self, angle, n): self.debugPrint("Nieuwe orientatie voor " + n + " ontvangen: " + str(angle) + " graden") for z in self.zeppelins: if z.name == n: z.updateAngle(angle) self.paintCanvas() def showCvResults(self, body): self.debugPrint("Nieuwe foto vertaling ontvangen: " + body) self.createPhoto(body) #gewenste hoogte aanpassen def setGewensteHoogte(self, event = None, Name = "goud"): x = self.txtHeight.get() self.txtHeight.delete(0, END) self.master.focus() try: x = int(x) except: return if isinstance(x, int) and x > 0 and x < 8000: global neededHeight neededHeight = x message = "Hoogte instellen op " + str(neededHeight) + " aangevraagd" self.debugPrint(message) mq.elevate(x, Name) #gewenste hoogte aanpassen def moveTo(self, event = None, Name = "goud"): st = self.txtMoveTo.get() self.txtMoveTo.delete(0, END) self.master.focus() try: xst, yst = st.split(',') x = int(xst) y = int(yst) except: return if isinstance(x, int) and isinstance(y, int): message = "Bewegen naar (" + str(x) + "," + str(y) + ") aangevraagd" self.debugPrint(message) self.goal = x/10,y/10 self.paintCanvas() mq.moveTo(x, y, Name) #tekst weergeven in debug venster def debugPrint(self, tekst): self.scrDebug.config(state = "normal") self.scrDebug.insert(END, ">> " + tekst + "\n") self.scrDebug.config(state = "disabled") self.scrDebug.yview_pickplace("end") def toggleAutomaticPilot(self): if not self.connected: return self.debugPrint("Automatische piloot toggle aangevraagd") self.client.toggleAutomaticPilot() def createClient(self): try: self.client = cl(self, self.ownZepName) self.zeppelins.append(AbstractZeppelin('red', self.ownZepName, self, self.client)) self.connected = True self.connectedString.set("Verbonden") self.lblConnected.config(fg = "green") self.debugPrint("Verbonden met Raspberry Pi") except: self.debugPrint("Verbinding met Rapsberry Pi niet mogelijk:\n -Staat de Raspberry Pi aan?\n -Staat de server aan?\n -Zit deze computer op de ad-hoc?") def moveForward(self): self.debugPrint("Voorwaarts vliegen aangevraagd") mq.setMotor1PWM(100) mq.setMotor2PWM(100) def moveBackward(self): self.debugPrint("Achterwaarts vliegen aangevraagd") mq.setMotor1PWM(-100) mq.setMotor2PWM(-100) def moveLeft(self): self.debugPrint("Links draaien aangevraagd") mq.setMotor1PWM(100) def moveRight(self): self.debugPrint("Rechts draaien aangevraagd") mq.setMotor2PWM(100) def moveUp(self): self.debugPrint("Omhoog vliegen aangevraagd") mq.setMotor3PWM(100) def moveDown(self): self.debugPrint("Omlaag vliegen aangevraagd") mq.setMotor3PWM(-100) def horizontalOff(self): self.debugPrint("Horizontale motors stoppen aangevraagd") mq.setMotor1PWM(0) mq.setMotor2PWM(0) def verticalOff(self): self.debugPrint("Verticale motor stoppen aangevraagd") mq.setMotor3PWM(0) #toetsenbord invoer def keyPressed(self, event): k = event.keysym if k == 'Up': if not self.btnUpPressed: self.btnUpPressed = True self.moveForward() elif k == 'Down': if not self.btnDownPressed: self.btnDownPressed = True self.moveBackward() elif k == 'Left': if not self.btnLeftPressed: self.btnLeftPressed = True self.moveLeft() elif k == 'Right': if not self.btnRightPressed: self.btnRightPressed = True self.moveRight() elif k == 'plus': if not self.btnPlusPressed: self.btnPlusPressed = True self.moveUp() elif k == 'minus': if not self.btnMinusPressed: self.btnMinusPressed = True self.moveDown() def keyReleased(self, event): k = event.keysym if k == 'Up': self.btnUpPressed = False self.horizontalOff() elif k == 'Down': self.btnDownPressed = False self.horizontalOff() elif k == 'Left': self.btnLeftPressed = False self.horizontalOff() elif k == 'Right': self.btnRightPressed = False self.horizontalOff() elif k == 'plus': self.btnPlusPressed = False self.verticalOff() elif k == 'minus': self.btnMinusPressed = False self.verticalOff()
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)