def instruction(): global rootB rootB = Tk() rootB.geometry('480x300+400+100') rootB.overrideredirect(True) def instruction_back(): rootB.destroy() w = Listbox(rootB, height=30, width=80) s = ''' CROSSWORD v2.0 game consists of a 15x15 matrix consisting of words. The player has to found out the words one by one. Here name of fruit, sports,movies,animals has been used. Checkbuttons sends the desired choice Check button check for its validity. Build button stsrts new game. This is a beta version so user might face bugs in the game. Developments are still going on. Recommendations is gladly accepted. Tamojit Das IEM CSE ''' s = s.split('\n') for c in range(len(s)): w.insert(c + 1, s[c]) #w.pack(expand='yes',fill='both') w.place(x=0, y=25) Button(rootB, text='<= Back', command=instruction_back).place(x=0, y=0) rootB.mainloop()
def showcontents(self): listbox = Listbox(self.tipwindow, background=idleConf.GetHighlight( theme, 'tooltip', 'bg')) listbox.pack() for item in self.items: listbox.insert(END, item)
def initUI(self): self.parent.title("Listbox") self.pack(fill=BOTH, expand=1) acts = ['Scarlett Johansson', 'Rachel Weiss', 'Natalie Portman', 'Jessica Alba'] #This is a list of actresses to be shown in the listbox. lb = Listbox(self) for i in acts: lb.insert(END, i) #We create an instance of the Listbox and insert all the items from the above mentioned list. lb.bind("<<ListboxSelect>>", self.onSelect) #When we select an item in the listbox, the <<ListboxSelect>> event is generated. #We bind the onSelect() method to this event. lb.place(x=20, y=20) self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) #A label and its value holder is created. #In this label we will display the currently selected item. self.label.place(x=20, y=210)
class ScrolledList(Frame): def __init__(self, master, d_list, a_function): Frame.__init__(self, master) scrl_bar = Scrollbar(self) self.listbox = Listbox(self) scrl_bar.config(command=self.listbox.yview) scrl_bar.pack(side=RIGHT, fill=Y) self.listbox.config(yscrollcommand=scrl_bar.set) self.listbox.pack(side=LEFT, expand=YES, fill=BOTH) #load the listbox idx = 0 for item in d_list: fparts = item.split('.') # DEBUG print fparts if fparts[-1] == 'csv': self.listbox.insert(idx, item) idx += 1 # link double click to the processList self.listbox.bind('<Double-1>', self.processList) # attach a function passed form the master # not this si done as passd function so it could be anything self.passed_function = a_function # get the index of the double clicked itenm and pass the item to # the passed function def processList(self, event): index = self.listbox.curselection() label = self.listbox.get(index) self.passed_function((index, label))
def startUI(self): self.parent.title("Testing") self.file_list = listdir(getcwd()) fileBox = Listbox(self.parent, selectmode=SINGLE) fileBox.pack() fileBox.grid(column=0, row=1, columnspan=3, rowspan=10, sticky=N + S) textBox = Text(self.parent) textBox.grid(column=4, row=0, columnspan=4, rowspan=10, sticky=N + S + E) ipBox = Entry(self.parent) ipBox.grid(column=0, row=0) btn = Button(text="Open ->", command=lambda: self.readFile(fileBox, textBox)) btn.grid(column=3, row=2) btnFire = Button(text="Fire away!", command=lambda: self.fireTorpedoes(ipBox, textBox)) btnFire.grid(column=3, row=3) scrlBar = Scrollbar(self.parent, command=textBox.yview) scrlBar.grid(column=8, row=0, rowspan=10, sticky=N + S) textBox.config(yscrollcommand=scrlBar.set) for i in self.file_list: fileBox.insert(END, i)
def recipebox(): global Box openit = Tk() openit.title("My recipes") label1 = Label(openit, text="Recipes") label1.pack() Box = Listbox(openit, width="30", height="25") Box.pack() '''Box2=Listbox(openit,width="30",height="25") Box2.grid(row=1,column=1)''' openBtn = Button(openit, text="Open", command=open_recipe) openBtn.pack() favsBtn = Button(openit, text="Add to Favourites") favsBtn.pack() delbtn = Button(openit, text="Delete recipe from the cookbook") delbtn.pack() if isfile("names.txt"): f = open("names.txt", "r") text = f.read() f.close() text = text.replace("//", "") #print text print "Data:", text text = text.split("\n") for i in range(len(text)): print text[i] Box.insert(END, text[i]) openit.mainloop()
def initUI(self): self.parent.title("Listbox + Scale + ChkBtn") self.pack(fill=BOTH, expand=1) acts = ['Scarlett Johansson', 'Rachel Weiss', 'Natalie Portman', 'Jessica Alba'] lb = Listbox(self) for i in acts: lb.insert(END, i) lb.bind("<<ListboxSelect>>", self.onSelect) lb.place(x=20, y=20) self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) self.label.place(x=20, y=190) scale = Scale(self, from_=0, to=100, command=self.onScale) scale.place(x=20, y=220) self.var_scale = IntVar() self.label_scale = Label(self, text=0, textvariable=self.var_scale) self.label_scale.place(x=180, y=220) self.var_chk = IntVar() cb = Checkbutton(self, text="Test", variable=self.var_chk, command=self.onClick) cb.select() cb.place(x=220, y=60)
def setPixelList(self): if "pixelListBox" in self.widgetDict.keys(): pixelListBox = self.widgetDict["pixelListBox"] pixelListBox.delete(0, "end") self.widgetDict["kernelListbox"].config(text="Pixels: %s" % len( self.RepLine.getKernel(self.activeCob, self.activeKernel).keys())) else: pixelListbox = Listbox(self) self.widgetDict["pixelListbox"] = pixelListbox scrollbar = Scrollbar(pixelListbox, orient="vertical") pixelListbox.config(yscrollcommand=scrollbar.set) scrollbar.config(command=pixelListbox.yview) self.widgetDict["pixelsLabel"].config(text="Pixels: %s" % len( self.RepLine.getKernel(self.activeCob, self.activeKernel).keys())) pixelListbox.grid(row=3, column=2, rowspan=3, sticky="nsew") pixelListbox.columnconfigure(0, weight=1) pixelListbox.bind("<<ListboxSelect>>", self.updateActivePixel) scrollbar.grid(column=2, sticky="e") cobNumber = self.activeCob[:self.activeCob.index("_")] kernelNumber = self.activeKernel[self.activeKernel.index(" ") + 1:] kernel = self.RepLine.getKernel(int(cobNumber), int(kernelNumber)) for pixelNumber in xrange(len(kernel.keys())): pixelListbox.insert(pixelNumber, "Pixel: %s" % pixelNumber)
def startUI(self): self.files = os.listdir(os.getcwd()) menubar = Menu(self.parent) self.parent.config(menu=menubar) fileMenu = Menu(menubar) fileMenu.add_command(label="Exit", command=self.quit) menubar.add_cascade(label="File", menu=fileMenu) listbox = Listbox(self.parent, selectmode=SINGLE) listbox.pack(fill=BOTH, expand=1) # listbox.insert(END, 'bebs') for i in self.files: listbox.insert(END, i) listbox.grid(column=0, columnspan=4, row=0, rowspan=10, sticky=N+S+E+W) txt = Text(self.parent) txt.grid(column=6, columnspan=8, row=0, rowspan=10, sticky=N+S+E+W) # txt.pack(fill=BOTH, expand=1) oBtn = Button(text="Open->", command=lambda: self.readContents(listbox, txt)) oBtn.grid(column=5, row=3)
class ScrolledList(Frame): ''' a customizable scrolled listbox compoent ''' def makeWidgets(self, width): scrbar_width = 30 scrbar = Scrollbar(self, width=scrbar_width) self.list = Listbox(self, relief=SUNKEN, width=width-30) scrbar.config(command=self.list.yview) self.list.config(yscrollcommand=scrbar.set) scrbar.pack(side=RIGHT, fill=Y) self.list.pack(side=LEFT, expand=YES, fill=BOTH) def __init__(self, parent, width): ''' Constructor ''' Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) self.makeWidgets(width) def log_line(self, msg): self.list.insert(END, msg) # if self.list.size(): # self.list.insert(1, msg) # else: # self.list.insert(END, msg) #
def __init__(self, container, main_ui): self.main_ui = main_ui self.nicknameLabel = Label(container, text="Welcome to Sudoku!") self.nicknameLabel.pack(side=TOP) self.frame_left = Frame(container) self.frame_left.pack(side=LEFT, padx=20, pady=20) self.nicknameLabel = Label(self.frame_left, text="Enter nickname: ") self.nicknameLabel.pack(side=LEFT) self.entry = Entry(self.frame_left, bd=5) self.entry.pack(side=LEFT) self.enterButton = Button(self.frame_left, text="Proceed", command=self.handle_enter) self.enterButton.pack(side=LEFT, padx=20, pady=20) self.frame_right = Frame(container) self.frame_right.pack(side=RIGHT) self.nicknameLabel = Label(self.frame_right, text="Previously used names:") self.nicknameLabel.pack() nickname_lb = Listbox(self.frame_right) for idx, val in enumerate(read_usernames( )): # Insert all previously used usernames to list nickname_lb.insert(idx, val) nickname_lb.pack() nickname_lb.bind('<<ListboxSelect>>', self.fill_nickname)
class ScrolledList(object): # TODO add columns to the Scrolled list: # http://stackoverflow.com/questions/5286093/display-listbox-with-columns-using-tkinter def __init__(self, parent_frame): self._vsbar = Scrollbar(parent_frame) self._hsbar = Scrollbar(parent_frame, orient='horizontal') self._list = Listbox(parent_frame, relief=SUNKEN, font=('courier', 12)) self._vsbar.config(command=self._list.yview, relief=SUNKEN) self._hsbar.config(command=self._list.xview, relief=SUNKEN) self._list.config(yscrollcommand=self._vsbar.set, relief=SUNKEN) self._list.config(xscrollcommand=self._hsbar.set) self._vsbar.pack(side=RIGHT, fill=Y) self._hsbar.pack(side=BOTTOM, fill=X) self._list.pack(side=LEFT, expand=YES, fill=BOTH) #self._list.bind('<Double-1>', self.handlelist) self._list_pos = 0 def clear(self): self._list.delete(0, END) self._list_pos = 0 def append_list_entry(self, entry_str, fg=None): pos = self._list_pos self._list_pos += 1 self._list.insert(END, entry_str) if fg: self._list.itemconfig(pos, fg=fg) return pos def highlight_entry(self, entry_index, bg): self._list.itemconfig(index=entry_index, bg=bg)
def documentation(version, w, h): def _setdoc(evt): w = evt.widget index = int(w.curselection()[0]) doc = w.get(index) textfield.config(state=NORMAL) textfield.delete('1.0', END) textfield.insert('1.0', docdic[doc]) textfield.config(state=DISABLED) r = Toplevel() w = int(w/2) h = int(h/2) r.geometry('{}x{}+{}+{}'.format(w, h, int(w/2), int(h/2))) r.wm_title('Documentation accpy version {}'.format(version)) lf = Frame(r) lf.pack(side=LEFT, fill=BOTH, expand=False) rf = Frame(r) rf.pack(side=RIGHT, fill=BOTH, expand=True) docmenuopts = ['General', 'Lattice editor', 'Citation'] docmenu = Listbox(lf) for entry in docmenuopts: docmenu.insert(END, entry) docmenu.pack(fill=BOTH, expand=True) docmenu.bind('<<ListboxSelect>>', _setdoc) scrollbar = Scrollbar(orient="vertical") textfield = Text(rf, xscrollcommand=scrollbar.set) textfield.pack(fill=BOTH, expand=True)
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 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='')
def initUI(self): self.title("Listbox") self.pack(fill=BOTH, expand=1) self.pack() acts = ["Scarlet Johansson", "Rachel Weiss", "Natalie Portman", "Jessica Alba"] lb = Listbox(self) for i in acts: lb.insert(END, i)
class LBChoice(object): '''This is a listbox for returning projects to be unarchived.''' def __init__(self, list_=None, master=None, title=None): '''Must have master, title is optional, li is too.''' self.master = master if self.master is not None: self.top = Toplevel(self.master) else: return self.v = None if list_ is None or not isinstance(list_, list): self.list = [] else: self.list = list_[:] self.top.transient(self.master) self.top.grab_set() self.top.bind("<Return>", self._choose) self.top.bind("<Escape>", self._cancel) if title: self.top.title(title) lf = Frame(self.top) #Sets up the list. lf.pack(side=TOP) scroll_bar = Scrollbar(lf) scroll_bar.pack(side=RIGHT, fill=Y) self.lb = Listbox(lf, selectmode=SINGLE) self.lb.pack(side=LEFT, fill=Y) scroll_bar.config(command=self.lb.yview) self.lb.config(yscrollcommand=scroll_bar.set) self.list.sort() for item in self.list: self.lb.insert(END, item) #Inserts items into the list. bf = Frame(self.top) bf.pack(side=BOTTOM) Button(bf, text="Select", command=self._choose).pack(side=LEFT) Button(bf, text="New", command=self._new).pack(side=LEFT) Button(bf, text="Cancel", command=self._cancel).pack(side=LEFT) def _choose(self, event=None): try: first = self.lb.curselection()[0] self.v = self.list[int(first)] except IndexError: self.v = None self.top.destroy() def _new(self, event=None): self.v = "NEW" self.top.destroy() def _cancel(self, event=None): self.top.destroy() def return_value(self): self.master.wait_window(self.top) return self.v
def generate_listbox(row, fill_list): scrollbar = Scrollbar(row, orient=VERTICAL) Flistbox = Listbox(row, yscrollcommand=scrollbar.set, height=1) #, scrollbar.config(command=Flistbox.yview) scrollbar.pack(side='right', fill=Y) for item in fill_list: Flistbox.insert(END, item) Flistbox.pack(side='left', fill=X, expand=1) return Flistbox
def set_listTop(Listbox,sMap): try: index=Listbox.curselection()[0] #Check if there is an existing entry in the listbox except IndexError: index=END for i,listbox_entry in enumerate(Listbox.get(0, END)): if listbox_entry == sMap: tkMessageBox.showinfo("Entry", "There is already an entry for this transition.") return Listbox.insert(index, sMap)
def addPortfolioList(self, companies): portfolioFrame = Frame(self.stocksFrame) scrollbar = Scrollbar(portfolioFrame, orient="vertical") companyList = Listbox(portfolioFrame, yscrollcommand=scrollbar.set) scrollbar.config(command=companyList.yview) scrollbar.pack(side="right", fill="y") #lb = Listbox(root, width=50, height=20, yscrollcommand=scrollbar.set) companyList.pack(fill=X, expand=0, side=TOP, padx=PAD, pady=PAD) for company in companies: companyList.insert(END,company) portfolioFrame.pack(fill=BOTH, expand=1, side=TOP)
class SelectionDialog(_TkDialog): def __init__(self, message, values): _TkDialog.__init__(self, message, values) def _create_selector(self, parent, values): self._listbox = Listbox(parent) for item in values: self._listbox.insert(END, item) return self._listbox def _validate_value(self): return bool(self._listbox.curselection()) def _get_value(self): return self._listbox.get(self._listbox.curselection())
class MultipleSelectionDialog(_TkDialog): def __init__(self, message, values): _TkDialog.__init__(self, message, values) def _create_selector(self, parent, values): self._listbox = Listbox(parent, selectmode='multiple') for item in values: self._listbox.insert(END, item) self._listbox.config(width=0) return self._listbox def _get_value(self): selected_values = [self._listbox.get(i) for i in self._listbox.curselection()] return selected_values
def initUI(self): self.parent.title("ListBox") self.pack(fill=BOTH, expand=1) eagles = ["Sam Bradford", "Jordan Matthews", "LeBron James", "Donnie Jones"] lb = Listbox(self) for i in eagles: lb.insert(END, i) lb.bind("<<ListboxSelect>>", self.onSelect) lb.pack(pady=15) self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) self.label.pack()
class Window(object): def __init__(self, master): self.master = master self.master.wm_title('PEP8 checker') self.master.resizable(False, True) self.frame = Frame(master) self.frame.pack(fill=BOTH, expand=1) home_dir = expanduser("~") self.directory = StringVar(value=home_dir) directory_frame = Frame(self.frame) directory_frame.grid() self.frame.grid_rowconfigure(2, weight=1) self.entry_directory = Entry(directory_frame, textvariable=self.directory) self.entry_directory.pack(anchor=W, side=LEFT) self.select_directory = Button(directory_frame, text="Select directory to scan", command=self.select_directory) self.select_directory.pack(anchor=E, side=RIGHT) self.run_button = Button(self.frame, text='Run PEP8!', command=self.run_pep) self.run_button.grid(sticky=W + E) self.errors_list = Listbox(self.frame) self.errors_list.grid(sticky=W + E) self.status_label = Label(self.frame) def select_directory(self): directory = askdirectory(initialdir=self.directory.get()) if directory: self.directory.set(directory) def run_pep(self): self.errors_list.delete(0, END) process = Popen('$(which pep8) {}'.format(self.directory.get()), shell=True, stderr=PIPE, stdout=PIPE) output = process.communicate()[0] selected_dir = ''.join((self.directory.get(), '/')) if output: self.errors_list.configure(background='red') for i, error in enumerate(output.split('\n')): self.errors_list.insert(i, error.replace(selected_dir, '')) else: self.errors_list.configure(background='green') self.errors_list.insert(0, 'Directory is OK!')
class MultipleSelectionDialog(_TkDialog): def __init__(self, message, values): _TkDialog.__init__(self, message, values) def _create_selector(self, parent, values): self._listbox = Listbox(parent, selectmode='multiple') for item in values: self._listbox.insert(END, item) self._listbox.config(width=0) return self._listbox def _get_value(self): selected_values = [ self._listbox.get(i) for i in self._listbox.curselection() ] return selected_values
def load(): """ Handle the load key on the main window. """ def save_select(): """ Select key hit. Set fname and exit if a field is high-lighted. """ sel = mylist.curselection() if not sel: return fname.append(olist[int(sel[0])]) top.quit() olist = sorted(os.listdir(getdir())) if len(olist) == 0: showwarning('Error', 'No files to load') return top = Toplevel() top.geometry('200x180+800+200') fname = [] top.title('Sudoku Loader') tpart = Frame(top) tpart.pack(side=Tkinter.TOP) bpart = Frame(top) bpart.pack(side=Tkinter.BOTTOM) scrollbar = Scrollbar(tpart) scrollbar.pack(side=Tkinter.RIGHT, fill=Tkinter.Y) mylist = Listbox(tpart, yscrollcommand=scrollbar.set) for line in olist: mylist.insert(Tkinter.END, line) mylist.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH) scrollbar.config(command=mylist.yview) picker = Button(bpart, text='SELECT', command=save_select) picker.pack(pady=5) top.mainloop() if fname: retvec = [] fyle = '%s%s%s' % (getdir(), os.path.sep, fname[0]) top.destroy() with open(fyle, 'r') as infile: inline = infile.readline() while inline: retvec.append(inline.split(':')) inline = infile.readline() return retvec
def printAnts(self): frameAnts = Frame(self.FrameInfo) Text_A = Label(frameAnts, text="Fourmie :") s1 = Scrollbar(frameAnts) l1 = Listbox(frameAnts) id_ants = self.checkAnts() for i in id_ants: l1.insert(i, str(i)) s1.config(command = l1.yview) l1.config(yscrollcommand = s1.set) l1.bind('<ButtonRelease-1>',self.choiceAnt) self.listbox = l1 Text_A.pack(side = TOP) l1.pack(side = LEFT) s1.pack(side = RIGHT) frameAnts.pack() self.printInfoAnt(id_ants[0]) self.frameAnts = frameAnts
def initUI(self): self.parent.title("Listbox") self.pack(fill=BOTH, expand=1) acts = ['Scarlett Johansson', 'Rachel Weiss', 'Natalie Portman', 'Jessica Alba'] lb = Listbox(self) for i in acts: lb.insert(END, i) lb.bind("<<ListboxSelect>>", self.onSelect) lb.pack(pady=15) self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) self.label.pack()
def tk_main(): candidates = make_transform(make_candidate_dict()) sorted_dict = sorted(candidates.items(), key=lambda x: float(x[1][0]), reverse=True) def on_select(evt): w = evt.widget index = int(w.curselection()[0]) txt = '' for n in range(len(sorted_dict[index][1][1])): #txt += sorted_dict[index][1][1][n] #txt += '\n' #txt += repr(sorted_dict[index][1][4][n]) #txt += '\n' #txt += repr(sorted_dict[index][1][5][n]) #txt += '\n\n' txt1 = '' txt2 = '' if sorted_dict[index][1][4][n]: txt1 += 'A' txt2 += 'N: ' + ', '.join(sorted_dict[index][1][4][n]) + '\n' if sorted_dict[index][1][5][n]: txt1 += 'N' txt2 += 'A: ' + ', '.join(sorted_dict[index][1][5][n]) + '\n' if txt1: txt1 = '[' + txt1 + ']' + sorted_dict[index][1][1][n].upper() txt += txt1 + '\n' + txt2 + '\n' textbox = Label(root, name='textbox', text=txt, width=125) textbox.pack(side=LEFT) root = Tk() listbox = Listbox(root, name='listbox', width=50, exportselection=0) listbox.bind('<<ListboxSelect>>', on_select) for i, c in enumerate(sorted_dict): listbox.insert(i, c[0] + ' ' + c[1][0]) listbox.pack(side=LEFT) txt = 'Hola Mundo Cruel!' textbox = Label(root, name='textbox', text=txt, width=125) textbox.pack(side=LEFT)
def init(self): self.parent.title('FuzzyOctoDubstep') self.style = Style() self.style.theme_use('default') self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(3, weight=1) self.rowconfigure(5, pad=7) lbl = Label(self, text="Windows") lbl.grid(sticky=W, pady=4, padx=5) conv_scrollbar = Scrollbar(self) conv_scrollbar.grid(row=1, column=2) conv = Listbox(self, width=80, height=30, yscrollcommand=conv_scrollbar.set) conv.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N) conv.insert(END, 'Hello') conv_scrollbar.config(command=conv.yview) abtn = Button(self, text="Activate") abtn.grid(row=1, column=3) cbtn = Button(self, text="Close") cbtn.grid(row=2, column=3, pady=4) hbtn = Button(self, text="Help") hbtn.grid(row=5, column=0, padx=5) obtn = Button(self, text="OK") obtn.grid(row=5, column=3)
def printAnts(self): frameAnts = Frame(self.FrameInfo) Text_A = Label(frameAnts, text="Fourmie :") s1 = Scrollbar(frameAnts) l1 = Listbox(frameAnts) id_ants = self.checkAnts() for i in id_ants: l1.insert(i, str(i)) s1.config(command=l1.yview) l1.config(yscrollcommand=s1.set) l1.bind('<ButtonRelease-1>', self.choiceAnt) self.listbox = l1 Text_A.pack(side=TOP) l1.pack(side=LEFT) s1.pack(side=RIGHT) frameAnts.pack() self.printInfoAnt(id_ants[0]) self.frameAnts = frameAnts
def get_Pro(): Get_Pro_window = tk.Toplevel() Get_Pro_window.title('查询所有接口支持省份') Get_Pro_window.geometry('230x250') Get_Pro_window.resizable(False, False) #GP_Text = Message(Get_Pro_window,width=610,text=ProvinceAre()).place(x=0,y=0) #ProvinceAre() # v = StringVar() sl = Scrollbar(Get_Pro_window) sl.pack(side='right', fill='y') lb = Listbox(Get_Pro_window,height=300,width=230) lb['yscrollcommand'] = sl.set # v.set(ProvinceAre()) for item in ProvinceAre(): lb.insert(END,item) lb.pack(side='left') sl['command'] = lb.yview Get_Pro_window.mainloop()
def run(): roboveroConfig() # draw a listbox root = Tk() root.title("Tone Generator") # populate the list with available frequencies tone_listbox = Listbox(root) tone_listbox.insert(END, "OFF") for freq in range(100, 1000, 100): tone_listbox.insert(END, "%d Hz" % freq) tone_listbox.pack() # set the callback function for left button clicks tone_listbox.bind('<ButtonRelease-1>', playSelection) root.mainloop()
class TKParent(): def __init__(self,filename): self.dialog = None self.todolist = None self.filename = filename def refresh_list(self): from Tkinter import END if not self.todolist: return todo = json.loads(open(self.filename,"r").read()) self.todolist.delete(0,END) for item in todo: text = item["message"] if "category" in item and item["category"]: text = "{0}: {1}".format(item["category"], text) self.todolist.insert(END,text) def get_box(self): if not self.dialog: from Tkinter import Tk,Listbox,Button,Scrollbar,X,Y,BOTTOM,RIGHT,HORIZONTAL,VERTICAL self.dialog = Tk() self.dialog.title("TODO") scrollbar = Scrollbar(self.dialog,orient=HORIZONTAL) yscrollbar = Scrollbar(self.dialog,orient=VERTICAL) self.todolist = Listbox(self.dialog,width=50,xscrollcommand=scrollbar.set,yscrollcommand=yscrollbar.set) scrollbar.config(command=self.todolist.xview) scrollbar.pack(side=BOTTOM,fill=X) yscrollbar.config(command=self.todolist.yview) yscrollbar.pack(side=RIGHT,fill=Y) self.todolist.pack(side="left",fill="both",expand=True) btn = Button(self.dialog,text="Refresh",command=self.refresh_list) btn.pack() self.refresh_list() return (self.dialog,self.todolist) def add(self,msg): from Tkinter import END self.todolist.insert(END,msg)
def initUI(self): self.parent.title("Listbox") self.pack(fill=BOTH, expand=1) acts = ['Scarlett Johansson', 'Rachel Weiss', 'Natalie Portman', 'Jessica Alba'] lb = Listbox(self) for i in acts: lb.insert(END, i) lb.bind("<<ListboxSelect>>", self.onSelect) lb.place(x=20, y=20) self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) self.label.place(x=20, y=210)
class ScrolledList(Frame): def __init__(self, master,a_function): Frame.__init__(self,master) scrl_bar = Scrollbar(self) self.listbox = Listbox(self) scrl_bar.config(command=self.listbox.yview) scrl_bar.pack(side=RIGHT, fill=Y) self.listbox.config(yscrollcommand=scrl_bar.set) self.listbox.pack(side=LEFT, expand=YES, fill=BOTH) # link double click to the processList self.listbox.bind('<Double-1>', self.processList) # attach a function passed form the master # not this si done as passd function so it could be anything self.passed_function = a_function # get the index of the double clicked itenm and pass the item to # the passed function def processList(self, event): index = self.listbox.curselection() label = self.listbox.get(index) self.passed_function((index,label)) def load_data(self,d_list): #load the listbox idx = 0 for item in d_list: fparts = item.split('.') # DEBUG print fparts if fparts[-1] == 'csv': # only display thoes files that have not been processed if not(item.startswith("done-")): self.listbox.insert(idx, item) idx += 1 def remove_item(self,idx): self.listbox.delete(idx)
def initUI(self): self.parent.title("Listbox") self.pack(fill=BOTH, expand=1) # put our data in from our global data object lb = Listbox(self) for i in data: lb.insert(END, i) # add event listener with call back to show # when the list object is selected, show visual feedback lb.bind("<<ListboxSelect>>", self.onSelect) # absolute positioning lb.place(x=20, y=20) self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) self.label.place(x=20, y=210)
class SelectionDialog(_AbstractTkDialog): _left_button = 'OK' _right_button = 'Cancel' def __init__(self, message, values): self._message = message self._values = values _AbstractTkDialog.__init__(self, "Select one option") def create_components(self, parent): Label(parent, text=self._message).pack(fill=BOTH) self._listbox = Listbox(parent) self._listbox.pack(fill=BOTH) for item in self._values: self._listbox.insert(END, item) return self._listbox def validate(self): return bool(self._listbox.curselection()) def apply(self): self.result = self._listbox.get(self._listbox.curselection())
def initUI(self): self.parent.title("Listbox") self.pack(fill=BOTH, expand=1) acts = ['Scarlett Johansson', 'Rachel Weiss', 'Natalie Portman', 'Jessica Alba', 'Someone Else'] with open('test.txt', 'rb') as f: lb = Listbox(self) for i in f: lb.insert(END, i) lb.bind("<<ListboxSelect>>", self.onSelect) lb.pack(pady=15) self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) self.label.pack()
def setKernelList(self): self.kernelList = [] for i in xrange(len(self.RepLine.cobs[self.activeCob])): self.kernelList.append("Kernel: " + str(i + 1)) if "kernelListbox" in self.widgetDict.keys(): kernelListbox = self.widgetDict["kernelListbox"] kernelListbox.delete(0, "end") self.widgetDict["kernelsLabel"].config(text="Kernels: %s" % len(self.kernelList)) else: kernelListbox = Listbox(self) self.widgetDict["kernelListbox"] = kernelListbox scrollbar = Scrollbar(kernelListbox, orient="vertical") kernelListbox.config(yscrollcommand=scrollbar.set) scrollbar.config(command=kernelListbox.yview) self.widgetDict["kernelsLabel"].config(text="Kernels: %s" % len(self.kernelList)) kernelListbox.grid(row=3, column=1, rowspan=3, sticky="nsew") kernelListbox.columnconfigure(0, weight=1) kernelListbox.bind("<<ListboxSelect>>", self.updateActiveKernel) scrollbar.grid(column=1, sticky="e") for kernel in self.kernelList: kernelListbox.insert(self.kernelList.index(kernel), kernel)
class GUIListbox: def __init__(self, parent, items=None, **kwargs): self.listbox = Listbox(parent, **kwargs) if items: self.setItems(items) def setItems(self, items): self.listbox.delete(0, END) for item in items: self.listbox.insert(END, item) def getSelected(self): return self.listbox.get(ACTIVE) def bindDoubleClick(self, func): self.listbox.bind("<Double-Button-1>", func) def grid(self, **kwargs): self.listbox.grid(kwargs) def pack(self, **kwargs): self.listbox.pack(kwargs)
def init(self): self.parent.title('FuzzyOctoDubstep') self.style = Style() self.style.theme_use('default') self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(3, weight=1) self.rowconfigure(5, pad=7) lbl = Label(self, text="Windows") lbl.grid(sticky=W, pady=4, padx=5) conv_scrollbar = Scrollbar(self) conv_scrollbar.grid(row=1, column=2) conv = Listbox(self, width=80, height=30, yscrollcommand=conv_scrollbar.set) conv.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E+W+S+N) conv.insert(END, 'Hello') conv_scrollbar.config(command=conv.yview) abtn = Button(self, text="Activate") abtn.grid(row=1, column=3) cbtn = Button(self, text="Close") cbtn.grid(row=2, column=3, pady=4) hbtn = Button(self, text="Help") hbtn.grid(row=5, column=0, padx=5) obtn = Button(self, text="OK") obtn.grid(row=5, column=3)
class ABFChannelSelector(Toplevel): def __init__(self, pathname, channels): Toplevel.__init__(self) x = (self.winfo_screenwidth() - 200) / 2 y = (self.winfo_screenheight() - 200) / 2 self.geometry("+%d+%d" % (x, y)) self.channels = channels header = Label(self, text="Select channel from '%s':" % os.path.basename(pathname), width=30, anchor='w') self.chanbox = Listbox(self, width=30, height=5, bg='white') ok_button = Button(self, text="OK", command=self.ok) cancel_button = Button(self, text="Cancel", command=self.cancel) header.pack(side='top', padx=10, pady=10) self.chanbox.pack(side='top', padx=10) cancel_button.pack(side='right', padx=10, pady=10) ok_button.pack(side='right') for n, name, units in channels: self.chanbox.insert('end', "%d %-10s %-8s" % (n + 1, name, units)) self.channel = None self.tkraise() self.focus_set() def present(self): self.wait_window() def ok(self): sel = self.chanbox.curselection() if sel: self.channel = self.channels[int(sel[0])][0] self.destroy() def cancel(self): self.destroy()
def menu_press_acc_reqs(): global row, listbox, lab root.geometry('220x170') F1 = Frame() lab = Label(root) s = Scrollbar(F1) listbox = Listbox(F1) s.pack(side=RIGHT, fill=Y) listbox.bind('<<ListboxSelect>>', onselect) listbox.pack(side=LEFT, fill=Y) F1.grid(column=0, row=0) s['command'] = listbox.yview listbox['yscrollcommand'] = s.set apprbtt = Button(root, text="Approved", command=app_acc) denybtt = Button(root, text="Denied") lab.place(relx=0.77, x=1, y=30, anchor=W) apprbtt.place(relx=0.67, x=1, y=60, anchor=W) denybtt.place(relx=0.7, x=1, y=100, anchor=W) forget_all() cursor.execute('''SELECT `username` FROM db_REQ''') while row is not None: for item in [row]: listbox.insert(END, row) row = cursor.fetchone()
def setCobList(self): self.cobList = [] for cob in xrange(len(self.RepLine.cobs.keys())): self.cobList.append( str(cob + 1) + "_" + self.RepLine.accessionName) if "cobListbox" in self.widgetDict.keys(): cobListbox = self.widgetDict["cobListbox"] cobListbox.delete(0, "end") self.widgetDict["cobsLabel"].config(text="Cobs: %s" % len(self.cobList)) else: cobListbox = Listbox(self) self.widgetDict["cobListbox"] = cobListbox scrollbar = Scrollbar(cobListbox, orient="vertical") cobListbox.config(yscrollcommand=scrollbar.set) scrollbar.config(command=cobListbox.yview) self.widgetDict["cobsLabel"].config(text="Cobs: %s" % len(self.cobList)) cobListbox.grid(row=3, column=0, rowspan=3, sticky="nsew") cobListbox.columnconfigure(0, weight=1) cobListbox.bind("<<ListboxSelect>>", self.updateActiveCob) scrollbar.grid(column=0, sticky="e") for cob in self.cobList: cobListbox.insert(self.cobList.index(cob), cob)
def startUI(self): self.files = os.listdir(os.getcwd()) menubar = Menu(self.parent) self.parent.config(menu=menubar) fileMenu = Menu(menubar) fileMenu.add_command(label="Exit", command=self.quit) menubar.add_cascade(label="File", menu=fileMenu) listbox = Listbox(self.parent, selectmode=SINGLE) listbox.pack(fill=BOTH, expand=1) # listbox.insert(END, 'bebs') for i in self.files: listbox.insert(END, i) listbox.grid(column=0, columnspan=4, row=0, rowspan=10, sticky=N + S + E + W) txt = Text(self.parent) txt.grid(column=6, columnspan=8, row=0, rowspan=10, sticky=N + S + E + W) # txt.pack(fill=BOTH, expand=1) oBtn = Button(text="Open->", command=lambda: self.readContents(listbox, txt)) oBtn.grid(column=5, row=3)
def imprimir_etiqueta(cursor): v = Toplevel() sc = Scrollbar(v) sc.pack(side=RIGHT, fill=Y) lb = Listbox(v, width=150, yscrollcommand=sc.set) for row in cursor: lb.insert(END, row[0]) lb.insert(END, row[1]) lb.insert(END, row[2]) lb.insert(END, '') lb.pack(side=LEFT, fill=BOTH) sc.config(command=lb.yview)
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 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 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 RecursiveDescentApp(object): """ A graphical tool for exploring the recursive descent parser. The tool displays the parser's tree and the remaining text, and allows the user to control the parser's operation. In particular, the user can expand subtrees on the frontier, match tokens on the frontier against the text, and backtrack. A "step" button simply steps through the parsing process, performing the operations that ``RecursiveDescentParser`` would use. """ def __init__(self, grammar, sent, trace=0): self._sent = sent self._parser = SteppingRecursiveDescentParser(grammar, trace) # Set up the main window. self._top = Tk() self._top.title('Recursive Descent Parser Application') # Set up key bindings. self._init_bindings() # Initialize the fonts. self._init_fonts(self._top) # Animations. animating_lock is a lock to prevent the demo # from performing new operations while it's animating. self._animation_frames = IntVar(self._top) self._animation_frames.set(5) self._animating_lock = 0 self._autostep = 0 # The user can hide the grammar. self._show_grammar = IntVar(self._top) self._show_grammar.set(1) # Create the basic frames. self._init_menubar(self._top) self._init_buttons(self._top) self._init_feedback(self._top) self._init_grammar(self._top) self._init_canvas(self._top) # Initialize the parser. self._parser.initialize(self._sent) # Resize callback self._canvas.bind('<Configure>', self._configure) ######################################### ## Initialization Helpers ######################################### def _init_fonts(self, root): # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html> self._sysfont = tkFont.Font(font=Button()["font"]) root.option_add("*Font", self._sysfont) # TWhat's our font size (default=same as sysfont) self._size = IntVar(root) self._size.set(self._sysfont.cget('size')) self._boldfont = tkFont.Font(family='helvetica', weight='bold', size=self._size.get()) self._font = tkFont.Font(family='helvetica', size=self._size.get()) if self._size.get() < 0: big = self._size.get()-2 else: big = self._size.get()+2 self._bigfont = tkFont.Font(family='helvetica', weight='bold', size=big) def _init_grammar(self, parent): # Grammar view. self._prodframe = listframe = Frame(parent) self._prodframe.pack(fill='both', side='left', padx=2) self._prodlist_label = Label(self._prodframe, font=self._boldfont, text='Available Expansions') self._prodlist_label.pack() self._prodlist = Listbox(self._prodframe, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._prodlist.pack(side='right', fill='both', expand=1) self._productions = list(self._parser.grammar().productions()) for production in self._productions: self._prodlist.insert('end', (' %s' % production)) self._prodlist.config(height=min(len(self._productions), 25)) # Add a scrollbar if there are more than 25 productions. if len(self._productions) > 25: listscroll = Scrollbar(self._prodframe, orient='vertical') self._prodlist.config(yscrollcommand = listscroll.set) listscroll.config(command=self._prodlist.yview) listscroll.pack(side='left', fill='y') # If they select a production, apply it. self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select) def _init_bindings(self): # Key bindings are a good thing. self._top.bind('<Control-q>', self.destroy) self._top.bind('<Control-x>', self.destroy) self._top.bind('<Escape>', self.destroy) self._top.bind('e', self.expand) #self._top.bind('<Alt-e>', self.expand) #self._top.bind('<Control-e>', self.expand) self._top.bind('m', self.match) self._top.bind('<Alt-m>', self.match) self._top.bind('<Control-m>', self.match) self._top.bind('b', self.backtrack) self._top.bind('<Alt-b>', self.backtrack) self._top.bind('<Control-b>', self.backtrack) self._top.bind('<Control-z>', self.backtrack) self._top.bind('<BackSpace>', self.backtrack) self._top.bind('a', self.autostep) #self._top.bind('<Control-a>', self.autostep) self._top.bind('<Control-space>', self.autostep) self._top.bind('<Control-c>', self.cancel_autostep) self._top.bind('<space>', self.step) self._top.bind('<Delete>', self.reset) self._top.bind('<Control-p>', self.postscript) #self._top.bind('<h>', self.help) #self._top.bind('<Alt-h>', self.help) self._top.bind('<Control-h>', self.help) self._top.bind('<F1>', self.help) #self._top.bind('<g>', self.toggle_grammar) #self._top.bind('<Alt-g>', self.toggle_grammar) #self._top.bind('<Control-g>', self.toggle_grammar) self._top.bind('<Control-g>', self.edit_grammar) self._top.bind('<Control-t>', self.edit_sentence) def _init_buttons(self, parent): # Set up the frames. self._buttonframe = buttonframe = Frame(parent) buttonframe.pack(fill='none', side='bottom', padx=3, pady=2) Button(buttonframe, text='Step', background='#90c0d0', foreground='black', command=self.step,).pack(side='left') Button(buttonframe, text='Autostep', background='#90c0d0', foreground='black', command=self.autostep,).pack(side='left') Button(buttonframe, text='Expand', underline=0, background='#90f090', foreground='black', command=self.expand).pack(side='left') Button(buttonframe, text='Match', underline=0, background='#90f090', foreground='black', command=self.match).pack(side='left') Button(buttonframe, text='Backtrack', underline=0, background='#f0a0a0', foreground='black', command=self.backtrack).pack(side='left') # Replace autostep... # self._autostep_button = Button(buttonframe, text='Autostep', # underline=0, command=self.autostep) # self._autostep_button.pack(side='left') def _configure(self, event): self._autostep = 0 (x1, y1, x2, y2) = self._cframe.scrollregion() y2 = event.height - 6 self._canvas['scrollregion'] = '%d %d %d %d' % (x1,y1,x2,y2) self._redraw() def _init_feedback(self, parent): self._feedbackframe = feedbackframe = Frame(parent) feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3) self._lastoper_label = Label(feedbackframe, text='Last Operation:', font=self._font) self._lastoper_label.pack(side='left') lastoperframe = Frame(feedbackframe, relief='sunken', border=1) lastoperframe.pack(fill='x', side='right', expand=1, padx=5) self._lastoper1 = Label(lastoperframe, foreground='#007070', background='#f0f0f0', font=self._font) self._lastoper2 = Label(lastoperframe, anchor='w', width=30, foreground='#004040', background='#f0f0f0', font=self._font) self._lastoper1.pack(side='left') self._lastoper2.pack(side='left', fill='x', expand=1) def _init_canvas(self, parent): self._cframe = CanvasFrame(parent, background='white', #width=525, height=250, closeenough=10, border=2, relief='sunken') self._cframe.pack(expand=1, fill='both', side='top', pady=2) canvas = self._canvas = self._cframe.canvas() # Initially, there's no tree or text self._tree = None self._textwidgets = [] self._textline = None def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label='Reset Parser', underline=0, command=self.reset, accelerator='Del') filemenu.add_command(label='Print to Postscript', underline=0, command=self.postscript, accelerator='Ctrl-p') filemenu.add_command(label='Exit', underline=1, command=self.destroy, accelerator='Ctrl-x') menubar.add_cascade(label='File', underline=0, menu=filemenu) editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label='Edit Grammar', underline=5, command=self.edit_grammar, accelerator='Ctrl-g') editmenu.add_command(label='Edit Text', underline=5, command=self.edit_sentence, accelerator='Ctrl-t') menubar.add_cascade(label='Edit', underline=0, menu=editmenu) rulemenu = Menu(menubar, tearoff=0) rulemenu.add_command(label='Step', underline=1, command=self.step, accelerator='Space') rulemenu.add_separator() rulemenu.add_command(label='Match', underline=0, command=self.match, accelerator='Ctrl-m') rulemenu.add_command(label='Expand', underline=0, command=self.expand, accelerator='Ctrl-e') rulemenu.add_separator() rulemenu.add_command(label='Backtrack', underline=0, command=self.backtrack, accelerator='Ctrl-b') menubar.add_cascade(label='Apply', underline=0, menu=rulemenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_checkbutton(label="Show Grammar", underline=0, variable=self._show_grammar, command=self._toggle_grammar) viewmenu.add_separator() viewmenu.add_radiobutton(label='Tiny', variable=self._size, underline=0, value=10, command=self.resize) viewmenu.add_radiobutton(label='Small', variable=self._size, underline=0, value=12, command=self.resize) viewmenu.add_radiobutton(label='Medium', variable=self._size, underline=0, value=14, command=self.resize) viewmenu.add_radiobutton(label='Large', variable=self._size, underline=0, value=18, command=self.resize) viewmenu.add_radiobutton(label='Huge', variable=self._size, underline=0, value=24, command=self.resize) menubar.add_cascade(label='View', underline=0, menu=viewmenu) animatemenu = Menu(menubar, tearoff=0) animatemenu.add_radiobutton(label="No Animation", underline=0, variable=self._animation_frames, value=0) animatemenu.add_radiobutton(label="Slow Animation", underline=0, variable=self._animation_frames, value=10, accelerator='-') animatemenu.add_radiobutton(label="Normal Animation", underline=0, variable=self._animation_frames, value=5, accelerator='=') animatemenu.add_radiobutton(label="Fast Animation", underline=0, variable=self._animation_frames, value=2, accelerator='+') menubar.add_cascade(label="Animate", underline=1, menu=animatemenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label='About', underline=0, command=self.about) helpmenu.add_command(label='Instructions', underline=0, command=self.help, accelerator='F1') menubar.add_cascade(label='Help', underline=0, menu=helpmenu) parent.config(menu=menubar) ######################################### ## Helper ######################################### def _get(self, widget, treeloc): for i in treeloc: widget = widget.subtrees()[i] if isinstance(widget, TreeSegmentWidget): widget = widget.node() return widget ######################################### ## Main draw procedure ######################################### def _redraw(self): canvas = self._canvas # Delete the old tree, widgets, etc. if self._tree is not None: self._cframe.destroy_widget(self._tree) for twidget in self._textwidgets: self._cframe.destroy_widget(twidget) if self._textline is not None: self._canvas.delete(self._textline) # Draw the tree. helv = ('helvetica', -self._size.get()) bold = ('helvetica', -self._size.get(), 'bold') attribs = {'tree_color': '#000000', 'tree_width': 2, 'node_font': bold, 'leaf_font': helv,} tree = self._parser.tree() self._tree = tree_to_treesegment(canvas, tree, **attribs) self._cframe.add_widget(self._tree, 30, 5) # Draw the text. helv = ('helvetica', -self._size.get()) bottom = y = self._cframe.scrollregion()[3] self._textwidgets = [TextWidget(canvas, word, font=self._font) for word in self._sent] for twidget in self._textwidgets: self._cframe.add_widget(twidget, 0, 0) twidget.move(0, bottom-twidget.bbox()[3]-5) y = min(y, twidget.bbox()[1]) # Draw a line over the text, to separate it from the tree. self._textline = canvas.create_line(-5000, y-5, 5000, y-5, dash='.') # Highlight appropriate nodes. self._highlight_nodes() self._highlight_prodlist() # Make sure the text lines up. self._position_text() def _redraw_quick(self): # This should be more-or-less sufficient after an animation. self._highlight_nodes() self._highlight_prodlist() self._position_text() def _highlight_nodes(self): # Highlight the list of nodes to be checked. bold = ('helvetica', -self._size.get(), 'bold') for treeloc in self._parser.frontier()[:1]: self._get(self._tree, treeloc)['color'] = '#20a050' self._get(self._tree, treeloc)['font'] = bold for treeloc in self._parser.frontier()[1:]: self._get(self._tree, treeloc)['color'] = '#008080' def _highlight_prodlist(self): # Highlight the productions that can be expanded. # Boy, too bad tkinter doesn't implement Listbox.itemconfig; # that would be pretty useful here. self._prodlist.delete(0, 'end') expandable = self._parser.expandable_productions() untried = self._parser.untried_expandable_productions() productions = self._productions for index in range(len(productions)): if productions[index] in expandable: if productions[index] in untried: self._prodlist.insert(index, ' %s' % productions[index]) else: self._prodlist.insert(index, ' %s (TRIED)' % productions[index]) self._prodlist.selection_set(index) else: self._prodlist.insert(index, ' %s' % productions[index]) def _position_text(self): # Line up the text widgets that are matched against the tree numwords = len(self._sent) num_matched = numwords - len(self._parser.remaining_text()) leaves = self._tree_leaves()[:num_matched] xmax = self._tree.bbox()[0] for i in range(0, len(leaves)): widget = self._textwidgets[i] leaf = leaves[i] widget['color'] = '#006040' leaf['color'] = '#006040' widget.move(leaf.bbox()[0] - widget.bbox()[0], 0) xmax = widget.bbox()[2] + 10 # Line up the text widgets that are not matched against the tree. for i in range(len(leaves), numwords): widget = self._textwidgets[i] widget['color'] = '#a0a0a0' widget.move(xmax - widget.bbox()[0], 0) xmax = widget.bbox()[2] + 10 # If we have a complete parse, make everything green :) if self._parser.currently_complete(): for twidget in self._textwidgets: twidget['color'] = '#00a000' # Move the matched leaves down to the text. for i in range(0, len(leaves)): widget = self._textwidgets[i] leaf = leaves[i] dy = widget.bbox()[1] - leaf.bbox()[3] - 10.0 dy = max(dy, leaf.parent().node().bbox()[3] - leaf.bbox()[3] + 10) leaf.move(0, dy) def _tree_leaves(self, tree=None): if tree is None: tree = self._tree if isinstance(tree, TreeSegmentWidget): leaves = [] for child in tree.subtrees(): leaves += self._tree_leaves(child) return leaves else: return [tree] ######################################### ## Button Callbacks ######################################### def destroy(self, *e): self._autostep = 0 if self._top is None: return self._top.destroy() self._top = None def reset(self, *e): self._autostep = 0 self._parser.initialize(self._sent) self._lastoper1['text'] = 'Reset Application' self._lastoper2['text'] = '' self._redraw() def autostep(self, *e): if self._animation_frames.get() == 0: self._animation_frames.set(2) if self._autostep: self._autostep = 0 else: self._autostep = 1 self._step() def cancel_autostep(self, *e): #self._autostep_button['text'] = 'Autostep' self._autostep = 0 # Make sure to stop auto-stepping if we get any user input. def step(self, *e): self._autostep = 0; self._step() def match(self, *e): self._autostep = 0; self._match() def expand(self, *e): self._autostep = 0; self._expand() def backtrack(self, *e): self._autostep = 0; self._backtrack() def _step(self): if self._animating_lock: return # Try expanding, matching, and backtracking (in that order) if self._expand(): pass elif self._parser.untried_match() and self._match(): pass elif self._backtrack(): pass else: self._lastoper1['text'] = 'Finished' self._lastoper2['text'] = '' self._autostep = 0 # Check if we just completed a parse. if self._parser.currently_complete(): self._autostep = 0 self._lastoper2['text'] += ' [COMPLETE PARSE]' def _expand(self, *e): if self._animating_lock: return old_frontier = self._parser.frontier() rv = self._parser.expand() if rv is not None: self._lastoper1['text'] = 'Expand:' self._lastoper2['text'] = rv self._prodlist.selection_clear(0, 'end') index = self._productions.index(rv) self._prodlist.selection_set(index) self._animate_expand(old_frontier[0]) return 1 else: self._lastoper1['text'] = 'Expand:' self._lastoper2['text'] = '(all expansions tried)' return 0 def _match(self, *e): if self._animating_lock: return old_frontier = self._parser.frontier() rv = self._parser.match() if rv is not None: self._lastoper1['text'] = 'Match:' self._lastoper2['text'] = rv self._animate_match(old_frontier[0]) return 1 else: self._lastoper1['text'] = 'Match:' self._lastoper2['text'] = '(failed)' return 0 def _backtrack(self, *e): if self._animating_lock: return if self._parser.backtrack(): elt = self._parser.tree() for i in self._parser.frontier()[0]: elt = elt[i] self._lastoper1['text'] = 'Backtrack' self._lastoper2['text'] = '' if isinstance(elt, Tree): self._animate_backtrack(self._parser.frontier()[0]) else: self._animate_match_backtrack(self._parser.frontier()[0]) return 1 else: self._autostep = 0 self._lastoper1['text'] = 'Finished' self._lastoper2['text'] = '' return 0 def about(self, *e): ABOUT = ("NLTK Recursive Descent Parser Application\n"+ "Written by Edward Loper") TITLE = 'About: Recursive Descent Parser Application' try: from tkMessageBox import Message Message(message=ABOUT, title=TITLE).show() except: ShowText(self._top, TITLE, ABOUT) def help(self, *e): self._autostep = 0 # The default font's not very legible; try using 'fixed' instead. try: ShowText(self._top, 'Help: Recursive Descent Parser Application', (__doc__ or '').strip(), width=75, font='fixed') except: ShowText(self._top, 'Help: Recursive Descent Parser Application', (__doc__ or '').strip(), width=75) def postscript(self, *e): self._autostep = 0 self._cframe.print_to_file() def mainloop(self, *args, **kwargs): """ Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes. """ if in_idle(): return self._top.mainloop(*args, **kwargs) def resize(self, size=None): if size is not None: self._size.set(size) size = self._size.get() self._font.configure(size=-(abs(size))) self._boldfont.configure(size=-(abs(size))) self._sysfont.configure(size=-(abs(size))) self._bigfont.configure(size=-(abs(size+2))) self._redraw() ######################################### ## Expand Production Selection ######################################### def _toggle_grammar(self, *e): if self._show_grammar.get(): self._prodframe.pack(fill='both', side='left', padx=2, after=self._feedbackframe) self._lastoper1['text'] = 'Show Grammar' else: self._prodframe.pack_forget() self._lastoper1['text'] = 'Hide Grammar' self._lastoper2['text'] = '' # def toggle_grammar(self, *e): # self._show_grammar = not self._show_grammar # if self._show_grammar: # self._prodframe.pack(fill='both', expand='y', side='left', # after=self._feedbackframe) # self._lastoper1['text'] = 'Show Grammar' # else: # self._prodframe.pack_forget() # self._lastoper1['text'] = 'Hide Grammar' # self._lastoper2['text'] = '' def _prodlist_select(self, event): selection = self._prodlist.curselection() if len(selection) != 1: return index = int(selection[0]) old_frontier = self._parser.frontier() production = self._parser.expand(self._productions[index]) if production: self._lastoper1['text'] = 'Expand:' self._lastoper2['text'] = production self._prodlist.selection_clear(0, 'end') self._prodlist.selection_set(index) self._animate_expand(old_frontier[0]) else: # Reset the production selections. self._prodlist.selection_clear(0, 'end') for prod in self._parser.expandable_productions(): index = self._productions.index(prod) self._prodlist.selection_set(index) ######################################### ## Animation ######################################### def _animate_expand(self, treeloc): oldwidget = self._get(self._tree, treeloc) oldtree = oldwidget.parent() top = not isinstance(oldtree.parent(), TreeSegmentWidget) tree = self._parser.tree() for i in treeloc: tree = tree[i] widget = tree_to_treesegment(self._canvas, tree, node_font=self._boldfont, leaf_color='white', tree_width=2, tree_color='white', node_color='white', leaf_font=self._font) widget.node()['color'] = '#20a050' (oldx, oldy) = oldtree.node().bbox()[:2] (newx, newy) = widget.node().bbox()[:2] widget.move(oldx-newx, oldy-newy) if top: self._cframe.add_widget(widget, 0, 5) widget.move(30-widget.node().bbox()[0], 0) self._tree = widget else: oldtree.parent().replace_child(oldtree, widget) # Move the children over so they don't overlap. # Line the children up in a strange way. if widget.subtrees(): dx = (oldx + widget.node().width()/2 - widget.subtrees()[0].bbox()[0]/2 - widget.subtrees()[0].bbox()[2]/2) for subtree in widget.subtrees(): subtree.move(dx, 0) self._makeroom(widget) if top: self._cframe.destroy_widget(oldtree) else: oldtree.destroy() colors = ['gray%d' % (10*int(10*x/self._animation_frames.get())) for x in range(self._animation_frames.get(),0,-1)] # Move the text string down, if necessary. dy = widget.bbox()[3] + 30 - self._canvas.coords(self._textline)[1] if dy > 0: for twidget in self._textwidgets: twidget.move(0, dy) self._canvas.move(self._textline, 0, dy) self._animate_expand_frame(widget, colors) def _makeroom(self, treeseg): """ Make sure that no sibling tree bbox's overlap. """ parent = treeseg.parent() if not isinstance(parent, TreeSegmentWidget): return index = parent.subtrees().index(treeseg) # Handle siblings to the right rsiblings = parent.subtrees()[index+1:] if rsiblings: dx = treeseg.bbox()[2] - rsiblings[0].bbox()[0] + 10 for sibling in rsiblings: sibling.move(dx, 0) # Handle siblings to the left if index > 0: lsibling = parent.subtrees()[index-1] dx = max(0, lsibling.bbox()[2] - treeseg.bbox()[0] + 10) treeseg.move(dx, 0) # Keep working up the tree. self._makeroom(parent) def _animate_expand_frame(self, widget, colors): if len(colors) > 0: self._animating_lock = 1 widget['color'] = colors[0] for subtree in widget.subtrees(): if isinstance(subtree, TreeSegmentWidget): subtree.node()['color'] = colors[0] else: subtree['color'] = colors[0] self._top.after(50, self._animate_expand_frame, widget, colors[1:]) else: widget['color'] = 'black' for subtree in widget.subtrees(): if isinstance(subtree, TreeSegmentWidget): subtree.node()['color'] = 'black' else: subtree['color'] = 'black' self._redraw_quick() widget.node()['color'] = 'black' self._animating_lock = 0 if self._autostep: self._step() def _animate_backtrack(self, treeloc): # Flash red first, if we're animating. if self._animation_frames.get() == 0: colors = [] else: colors = ['#a00000', '#000000', '#a00000'] colors += ['gray%d' % (10*int(10*x/(self._animation_frames.get()))) for x in range(1, self._animation_frames.get()+1)] widgets = [self._get(self._tree, treeloc).parent()] for subtree in widgets[0].subtrees(): if isinstance(subtree, TreeSegmentWidget): widgets.append(subtree.node()) else: widgets.append(subtree) self._animate_backtrack_frame(widgets, colors) def _animate_backtrack_frame(self, widgets, colors): if len(colors) > 0: self._animating_lock = 1 for widget in widgets: widget['color'] = colors[0] self._top.after(50, self._animate_backtrack_frame, widgets, colors[1:]) else: for widget in widgets[0].subtrees(): widgets[0].remove_child(widget) widget.destroy() self._redraw_quick() self._animating_lock = 0 if self._autostep: self._step() def _animate_match_backtrack(self, treeloc): widget = self._get(self._tree, treeloc) node = widget.parent().node() dy = (1.0 * (node.bbox()[3] - widget.bbox()[1] + 14) / max(1, self._animation_frames.get())) self._animate_match_backtrack_frame(self._animation_frames.get(), widget, dy) def _animate_match(self, treeloc): widget = self._get(self._tree, treeloc) dy = ((self._textwidgets[0].bbox()[1] - widget.bbox()[3] - 10.0) / max(1, self._animation_frames.get())) self._animate_match_frame(self._animation_frames.get(), widget, dy) def _animate_match_frame(self, frame, widget, dy): if frame > 0: self._animating_lock = 1 widget.move(0, dy) self._top.after(10, self._animate_match_frame, frame-1, widget, dy) else: widget['color'] = '#006040' self._redraw_quick() self._animating_lock = 0 if self._autostep: self._step() def _animate_match_backtrack_frame(self, frame, widget, dy): if frame > 0: self._animating_lock = 1 widget.move(0, dy) self._top.after(10, self._animate_match_backtrack_frame, frame-1, widget, dy) else: widget.parent().remove_child(widget) widget.destroy() self._animating_lock = 0 if self._autostep: self._step() def edit_grammar(self, *e): CFGEditor(self._top, self._parser.grammar(), self.set_grammar) def set_grammar(self, grammar): self._parser.set_grammar(grammar) self._productions = list(grammar.productions()) self._prodlist.delete(0, 'end') for production in self._productions: self._prodlist.insert('end', (' %s' % production)) def edit_sentence(self, *e): sentence = " ".join(self._sent) title = 'Edit Text' instr = 'Enter a new sentence to parse.' EntryDialog(self._top, sentence, instr, self.set_sentence, title) def set_sentence(self, sentence): self._sent = sentence.split() #[XX] use tagged? self.reset()
class CenterFrame(BasePAFrame): """ фрейм со списком файлов """ def __init__(self, *args, **kwargs): self.w_frame_child = kwargs.pop('child_frame') BasePAFrame.__init__(self, *args, **kwargs) self.w_listbox_files = Listbox(self) self.w_scrollbar_files = Scrollbar(self) self.catalog = None self.catalog_files = [] def _pa_configure(self): BasePAFrame._pa_configure(self) self.w_listbox_files.config(yscrollcommand=self.w_scrollbar_files.set) self.w_scrollbar_files.config(command=self.w_listbox_files.yview) self.w_listbox_files.bind( '<<ListboxSelect>>', self.select_listbox_file) def _pa_layout(self): BasePAFrame._pa_layout(self) w_listbox_files_width = 0.95 self.w_listbox_files.place( relx=0, rely=0, relwidth=w_listbox_files_width, relheight=1) self.w_scrollbar_files.place( relx=w_listbox_files_width, rely=0, relwidth=1-w_listbox_files_width, relheight=1) def set_catalog(self, catalog=None): """ задаем новый каталог для отображения :param catalog: словарь { 'path': путь к каталогу } :return: """ try: current_index = self.w_listbox_files.curselection()[0] except IndexError: current_index = 0 if 0 < current_index < len(self.catalog_files): set_index = current_index + 1 else: set_index = current_index self.catalog = catalog self.catalog_files = [] self.w_listbox_files.delete(0, END) self.w_frame_child.set_file(None) if self.catalog is not None: catalog_path = self.catalog for file_name in os.listdir(catalog_path): file_path = os.path.join(catalog_path, file_name) if os.path.isfile(file_path): self.catalog_files.append({ 'name': file_name, 'path': file_path}) self.catalog_files.sort(key=lambda x: x['name']) catalog_files = [catalog['name'] for catalog in self.catalog_files] self.w_listbox_files.insert(END, *catalog_files) self.w_listbox_files.selection_set(set_index) self.w_listbox_files.see(set_index) self.w_listbox_files.event_generate("<<ListboxSelect>>") def update_catalog(self): self.set_catalog(self.catalog) def select_listbox_file(self, event): """ обработчик выбора файла в списке файлов :param event: :return: """ try: index = self.w_listbox_files.curselection()[0] file_ = self.catalog_files[index] except IndexError: return else: self.w_frame_child.set_file(file_)
class OSCRemote(object): def __init__(self): self.editor_issue = "1.3" # get command options self.command_options = remote_options() # get directory holding the code self.pp_dir = sys.path[0] if not os.path.exists(self.pp_dir + os.sep + "pp_oscremote.py"): tkMessageBox.showwarning("Pi Presents", "Bad Application Directory") exit() # Initialise logging Monitor.log_path = self.pp_dir self.mon = Monitor() self.mon.init() Monitor.classes = ['OSCRemote', 'OSCConfig', 'OSCEditor'] Monitor.log_level = int(self.command_options['debug']) self.mon.log(self, "Pi Presents Remote is starting") self.mon.log(self, " OS and separator " + os.name + ' ' + os.sep) self.mon.log(self, "sys.path[0] - location of code: code " + sys.path[0]) self.setup_gui() # OSC config class self.osc_config = OSCConfig() self.init() #and start the system self.root.after(1000, self.run_app) self.root.mainloop() def init(self): self.osc_config_file = self.pp_dir + os.sep + 'pp_config' + os.sep + 'pp_oscremote.cfg' self.read_create_osc() self.pp_home_dir = self.osc_config.pp_home_dir self.pp_profiles_offset = self.osc_config.pp_profiles_offset self.mon.log(self, "Data Home from options is " + self.pp_home_dir) self.mon.log( self, "Current Profiles Offset from options is " + self.pp_profiles_offset) self.pp_profile_dir = '' self.current_showlist = None self.current_show = None self.current_show_ref = '' self.shows_display.delete(0, END) self.results.set('') def add_status(self, text): self.status_display.insert(END, text + '\n') self.status_display.see(END) def run_app(self): self.client = None self.server = None self.st = None # initialise OSC variables self.prefix = '/pipresents' self.this_unit = '/' + self.osc_config.this_unit_name self.add_status('this unit is: ' + self.this_unit) self.controlled_unit = '/' + self.osc_config.controlled_unit_1_name self.add_status('controlled unit is: ' + self.controlled_unit) #connect client then start server to listen for replies self.init_client() self.add_status('connecting to controlled unit: ' + self.osc_config.controlled_unit_1_ip + ':' + self.osc_config.controlled_unit_1_port + ' ' + self.osc_config.controlled_unit_1_name) self.connect_client(self.osc_config.controlled_unit_1_ip, self.osc_config.controlled_unit_1_port) self.add_status('listening for replies on:' + self.osc_config.this_unit_ip + ':' + self.osc_config.this_unit_port) self.init_server(self.osc_config.this_unit_ip, self.osc_config.this_unit_port, self.client) self.add_initial_handlers() self.start_server() # *************************************** # RESPOND TO BUTTONS # *************************************** def open_show(self): self.msg_path = '/core/open ' self.msg_arg_text = self.current_show_ref self.display_msg_text() def close_show(self): self.msg_path = '/core/close ' self.msg_arg_text = self.current_show_ref self.display_msg_text() def exit_pipresents(self): self.msg_path = '/core/exitpipresents' self.msg_arg_text = '' self.display_msg_text() def play_event(self): self.msg_path = '/core/event' self.msg_arg_text = 'pp-play' self.display_msg_text() def pause_event(self): self.msg_path = '/core/event' self.msg_arg_text = 'pp-pause' self.display_msg_text() pass def stop_event(self): self.msg_path = '/core/event' self.msg_arg_text = 'pp-stop' self.display_msg_text() pass def up_event(self): self.msg_path = '/core/event' self.msg_arg_text = 'pp-up' self.display_msg_text() def down_event(self): self.msg_path = '/core/event' self.msg_arg_text = 'pp-down' self.display_msg_text() def output(self): self.msg_path = '/core/output' self.msg_arg_text = '' self.display_msg_text() def loopback(self): self.msg_path = '/system/loopback' self.msg_arg_text = '' self.display_msg_text() def server_info(self): self.msg_path = '/system/server-info' self.msg_arg_text = '' self.display_msg_text() # and put the created text in the results box in the gui def display_msg_text(self): self.results.set(self.prefix + self.controlled_unit + self.msg_path + ' ' + self.msg_arg_text) #calback from the Send button # parses the message string into fields and sends - NO error checking def send_message(self): msg_text = self.results.get() self.add_status('Send message:' + msg_text) self.mon.log(self, 'send message: ' + msg_text) fields = msg_text.split() address = fields[0] arg_list = fields[1:] self.send(address, arg_list) # *************************************** # OSC CLIENT TO SEND MESSAGES # *************************************** def init_client(self): self.client = OSC.OSCClient() def connect_client(self, ip, port): self.mon.log(self, 'connect to: ' + ip + ':' + str(port)) self.client.connect((ip, int(port))) def send(self, address, arg_list): msg = OSC.OSCMessage() msg.setAddress(address) for arg in arg_list: msg.append(arg) self.client.send(msg) def disconnect_client(self): self.client.close() return # *************************************** # OSC SERVER TO LISTEN TO REPLIES # *************************************** def init_server(self, ip, port_text, client): self.mon.log(self, 'Start Server: ' + ip + ':' + port_text) self.server = OSC.OSCServer((ip, int(port_text)), client) def start_server(self): self.st = threading.Thread(target=self.server.serve_forever) self.st.start() def close_server(self): if self.server != None: self.server.close() self.mon.log(self, 'Waiting for Server-thread to finish') if self.st != None: self.st.join() ##!!! self.mon.log(self, 'server thread closed') def add_initial_handlers(self): self.server.addMsgHandler('default', self.no_match_handler) self.server.addMsgHandler( self.prefix + self.this_unit + "/system/loopback-reply", self.loopback_reply_handler) self.server.addMsgHandler( self.prefix + self.this_unit + "/system/server-info-reply", self.server_info_reply_handler) def no_match_handler(self, addr, tags, stuff, source): text = '' text += "no match for new osc msg from %s" % OSC.getUrlStr( source) + '\n' text += "with addr : %s" % addr + '\n' text += "typetags %s" % tags + '\n' text += "data %s" % stuff + '\n' self.add_status(text + '\n') def loopback_reply_handler(self, addr, tags, stuff, source): self.add_status('Loopback reply received from: ' + self.pretty_list(source)) def server_info_reply_handler(self, addr, tags, stuff, source): self.add_status('Server Information from: ' + self.pretty_list(source) + '\n ' + self.pretty_list(stuff)) def pretty_list(self, fields): text = ' ' for field in fields: text += str(field) + ' ' return text # *************************************** # INIT EXIT MISC # *************************************** def e_edit_osc(self): self.disconnect_client() self.close_server() self.edit_osc() self.init() self.add_status('\n\n\nRESTART') self.run_app() def app_exit(self): self.disconnect_client() self.close_server() if self.root is not None: self.root.destroy() self.mon.finish() sys.exit() def show_help(self): tkMessageBox.showinfo("Help", "Read 'manual.pdf'") def about(self): tkMessageBox.showinfo( "About", "Simple Remote Control for Pi Presents\n" + "Author: Ken Thompson" + "\nWebsite: http://pipresents.wordpress.com/") def setup_gui(self): # set up the gui # root is the Tkinter root widget self.root = Tk() self.root.title("Remote Control for Pi Presents") # self.root.configure(background='grey') self.root.resizable(False, False) # define response to main window closing self.root.protocol("WM_DELETE_WINDOW", self.app_exit) # bind some display fields self.filename = StringVar() self.display_show = StringVar() self.results = StringVar() self.status = StringVar() # define menu menubar = Menu(self.root) profilemenu = Menu(menubar, tearoff=0, bg="grey", fg="black") profilemenu.add_command(label='Select', command=self.open_existing_profile) menubar.add_cascade(label='Profile', menu=profilemenu) toolsmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") menubar.add_cascade(label='Tools', menu=toolsmenu) osc_configmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") menubar.add_cascade(label='OSC', menu=osc_configmenu) osc_configmenu.add_command(label='Edit', command=self.e_edit_osc) helpmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") menubar.add_cascade(label='Help', menu=helpmenu) helpmenu.add_command(label='Help', command=self.show_help) helpmenu.add_command(label='About', command=self.about) self.root.config(menu=menubar) #top frame top_frame = Frame(self.root, padx=5, pady=5) top_frame.pack(side=TOP) results_label = Label(top_frame, text="Message to Send", font="arial 12 bold") results_label.pack(side=LEFT) results_display = Entry(top_frame, textvariable=self.results, width=70) results_display.pack(side=LEFT, fill=BOTH, expand=1) send_button = Button(top_frame, width=5, height=1, text='Send', fg='black', command=self.send_message, bg="light grey") send_button.pack(side=RIGHT) #bottom frame bottom_frame = Frame(self.root, padx=5, pady=5) bottom_frame.pack(side=TOP, fill=BOTH, expand=1) left_frame = Frame(bottom_frame, padx=5) left_frame.pack(side=LEFT) right_frame = Frame(bottom_frame, padx=5, pady=5) right_frame.pack(side=LEFT) suplabel_frame = Frame(right_frame, pady=5) suplabel_frame.pack(side=TOP) commands_label = Label(suplabel_frame, text="Show Control", font="arial 12 bold") commands_label.pack() supervisor_frame = Frame(right_frame, pady=5) supervisor_frame.pack(side=TOP) # supervisor buttons add_button = Button(supervisor_frame, width=5, height=1, text='Open\nShow', fg='black', command=self.open_show, bg="light grey") add_button.pack(side=LEFT) add_button = Button(supervisor_frame, width=5, height=1, text='Close\nShow', fg='black', command=self.close_show, bg="light grey") add_button.pack(side=LEFT) add_button = Button(supervisor_frame, width=10, height=1, text='Exit\nPi Presents', fg='black', command=self.exit_pipresents, bg="light grey") add_button.pack(side=LEFT) # events buttons oplabel_frame = Frame(right_frame, pady=5) oplabel_frame.pack(side=TOP) operations_label = Label(oplabel_frame, text="Input Events", font="arial 12 bold") operations_label.pack() operations_frame = Frame(right_frame, pady=5) operations_frame.pack(side=TOP) add_button = Button(operations_frame, width=5, height=1, text='Play', fg='black', command=self.play_event, bg="light grey") add_button.pack(side=LEFT) add_button = Button(operations_frame, width=5, height=1, text='Pause', fg='black', command=self.pause_event, bg="light grey") add_button.pack(side=LEFT) add_button = Button(operations_frame, width=5, height=1, text='Stop', fg='black', command=self.stop_event, bg="light grey") add_button.pack(side=LEFT) add_button = Button(operations_frame, width=5, height=1, text='Up', fg='black', command=self.up_event, bg="light grey") add_button.pack(side=LEFT) add_button = Button(operations_frame, width=5, height=1, text='Down', fg='black', command=self.down_event, bg="light grey") add_button.pack(side=LEFT) # animate buttons animate_frame = Frame(right_frame, pady=5) animate_frame.pack(side=TOP) animate_label = Label(animate_frame, text="Control Outputs", font="arial 12 bold") animate_label.pack() animate_frame = Frame(right_frame, pady=5) animate_frame.pack(side=TOP) add_button = Button(animate_frame, width=5, height=1, text='Output', fg='black', command=self.output, bg="light grey") add_button.pack(side=LEFT) # system buttons systemlabel_frame = Frame(right_frame, pady=5) systemlabel_frame.pack(side=TOP) system_label = Label(systemlabel_frame, text="System", font="arial 12 bold") system_label.pack() system_frame = Frame(right_frame, pady=5) system_frame.pack(side=TOP) add_button = Button(system_frame, width=5, height=1, text='Loopback', fg='black', command=self.loopback, bg="light grey") add_button.pack(side=LEFT) add_button = Button(system_frame, width=10, height=1, text='Server Info', fg='black', command=self.server_info, bg="light grey") add_button.pack(side=LEFT) # define display of showlist shows_title_frame = Frame(left_frame) shows_title_frame.pack(side=TOP) shows_label = Label(shows_title_frame, text="Shows") shows_label.pack() shows_frame = Frame(left_frame) shows_frame.pack(side=TOP) scrollbar = Scrollbar(shows_frame, orient=VERTICAL) self.shows_display = Listbox(shows_frame, selectmode=SINGLE, height=12, width=40, bg="white", activestyle=NONE, fg="black", yscrollcommand=scrollbar.set) scrollbar.config(command=self.shows_display.yview) scrollbar.pack(side=RIGHT, fill=Y) self.shows_display.pack(side=LEFT, fill=BOTH, expand=1) self.shows_display.bind("<ButtonRelease-1>", self.e_select_show) # status_frame status_frame = Frame(self.root, padx=5, pady=5) status_frame.pack(side=TOP, fill=BOTH, expand=1) status_label = Label(status_frame, text="Status", font="arial 12 bold") status_label.pack(side=LEFT) scrollbar = Scrollbar(status_frame, orient=VERTICAL) self.status_display = Text(status_frame, height=10, yscrollcommand=scrollbar.set) scrollbar.config(command=self.status_display.yview) scrollbar.pack(side=RIGHT, fill=Y) self.status_display.pack(side=LEFT, fill=BOTH, expand=1) # *************************************** # SHOWLIST # *************************************** def open_existing_profile(self): initial_dir = self.pp_home_dir + os.sep + "pp_profiles" + self.pp_profiles_offset if os.path.exists(initial_dir) is False: self.mon.err( self, "Profiles directory not found: " + initial_dir + "\n\nHint: Data Home option must end in pp_home") return dir_path = tkFileDialog.askdirectory(initialdir=initial_dir) # dir_path="C:\Users\Ken\pp_home\pp_profiles\\ttt" if len(dir_path) > 0: self.open_profile(dir_path) def open_profile(self, dir_path): showlist_file = dir_path + os.sep + "pp_showlist.json" if os.path.exists(showlist_file) is False: self.mon.err( self, "Not a Profile: " + dir_path + "\n\nHint: Have you opened the profile directory?") return self.pp_profile_dir = dir_path self.root.title("Remote for Pi Presents - " + self.pp_profile_dir) self.open_showlist(self.pp_profile_dir) def open_showlist(self, profile_dir): showlist_file = profile_dir + os.sep + "pp_showlist.json" if os.path.exists(showlist_file) is False: self.mon.err( self, "showlist file not found at " + profile_dir + "\n\nHint: Have you opened the profile directory?") self.app_exit() self.current_showlist = ShowList() self.current_showlist.open_json(showlist_file) if float(self.current_showlist.sissue()) != float(self.editor_issue): self.mon.err( self, "Version of profile does not match Remote: " + self.editor_issue) self.app_exit() self.refresh_shows_display() def refresh_shows_display(self): self.shows_display.delete(0, self.shows_display.size()) for index in range(self.current_showlist.length()): self.shows_display.insert( END, self.current_showlist.show(index)['title'] + " [" + self.current_showlist.show(index)['show-ref'] + "]") if self.current_showlist.show_is_selected(): self.shows_display.itemconfig( self.current_showlist.selected_show_index(), fg='red') self.shows_display.see(self.current_showlist.selected_show_index()) def e_select_show(self, event): print 'select show', self.current_showlist.length() if self.current_showlist is not None and self.current_showlist.length( ) > 0: mouse_item_index = int(event.widget.curselection()[0]) self.current_showlist.select(mouse_item_index) self.current_show_ref = self.current_showlist.selected_show( )['show-ref'] self.refresh_shows_display() else: self.current_show_ref = '' # *************************************** # OSC CONFIGURATION # *************************************** def read_create_osc(self): if self.osc_config.read(self.osc_config_file) is False: self.osc_config.create(self.osc_config_file) eosc = OSCEditor(self.root, self.osc_config_file, 'remote', 'Create OSC Remote Configuration') self.osc_config.read(self.osc_config_file) def edit_osc(self): if self.osc_config.read(self.osc_config_file) is False: self.osc_config.create(self.osc_config_file) eosc = OSCEditor(self.root, self.osc_config_file, 'remote', 'Edit OSC Reomote Configuration')
class TkApp: def __init__(self, ncffile, options): master = self.root = Tk() self.ncffile = ncffile self.options = options self.plotted_variables = set() frame = Frame(master) frame.grid(row = 0) codeframe = Frame(master) codeframe.grid(row = 1) metaframe = Frame(master) metaframe.grid(row = 2) goframe = Frame(frame) goframe.grid(column = 3, row = 1) var_label = Label(frame, text = 'Select Variable') var_label.grid(column = 0, row = 0) var_scrollbar = Scrollbar(frame, orient = VERTICAL) var_scrollbar.grid(column = 1, row = 1, sticky = N + S) self.var = Listbox(frame, selectmode = EXTENDED, exportselection = 0, yscrollcommand = var_scrollbar.set) self.var.grid(column = 0, row = 1) var_scrollbar.config(command = self.var.yview) what_to_do = Label(frame, text = 'Execute') what_to_do.grid(column = 2, row = 0) self.method_list = Listbox(frame, selectmode = SINGLE, exportselection = 0) self.method_list.grid(column = 2, row = 1) self.pre_txt = StringVar() pre_label = Label(codeframe, text = 'Before any figures, execute code') self.pre_txt.set(_pre_code) pre_label.grid(row = 2, sticky = 'W') self.pre = Entry(codeframe, width = 120, textvariable = self.pre_txt) self.pre.grid(row =3, sticky = 'E') self.before_txt = StringVar() self.before_txt.set(_before_code) before_label = Label(codeframe, text = 'Before each figure, execute code') before_label.grid(row = 4, sticky = 'W') self.before = Entry(codeframe, width = 120, textvariable = self.before_txt) self.before.grid(row =5, sticky = 'E') self.after_txt = StringVar() self.after_txt.set(_after_code) after_label = Label(codeframe, text = 'After each figure, execute code') after_label.grid(row = 6, sticky = 'W') self.after = Entry(codeframe, width = 120, textvariable = self.after_txt) self.after.grid(row =7, sticky = 'E') self.post_txt = StringVar() self.post_txt.set(_post_code) post_label = Label(codeframe, text = 'After all figures, execute code') post_label.grid(row = 8, sticky = 'W') self.post = Entry(codeframe, width = 120, textvariable = self.post_txt) self.post.grid(row = 9, sticky = 'E') options_label = Label(goframe, text = 'Options:') options_label.grid(column = 0, row = 1, sticky = 'W') self.logscale = IntVar() self.logscale.set(0) c = Checkbutton(goframe, text = "log-scale?", variable = self.logscale) c.grid(column = 0, row = 2, sticky = 'W') self.coastlines = IntVar() self.coastlines.set(_coastlines_opt) coastlines = Checkbutton(goframe, text = "coastlines?", variable = self.coastlines, justify = LEFT) coastlines.grid(column = 0, row = 3, sticky = 'W') self.countries = IntVar() self.countries.set(_countries_opt) countries = Checkbutton(goframe, text = "countries?", variable = self.countries, justify = LEFT) countries.grid(column = 0, row = 4, sticky = 'W') self.states = IntVar() self.states.set(_states_opt) states = Checkbutton(goframe, text = "states?", variable = self.states, justify = LEFT) states.grid(column = 0, row = 5, sticky = 'W') self.counties = IntVar() self.counties.set(_counties_opt) counties = Checkbutton(goframe, text = "counties?", variable = self.counties, justify = LEFT) counties.grid(column = 0, row = 6, sticky = 'W') self.execute_button = Button(goframe, text = "Make Figure", command = self.execute) self.execute_button.grid(row = 0, column = 0, sticky = 'W') self.methods = ['mapplot', 'presslat', 'presslon', 'time-lat', 'profile', 'timeseries', 'pressx', 'tileplot', 'plot'] method_labels= ['lat-lon', 'press-lat', 'press-lon', 'time-lat', 'Vertical Profile', 'Time Series', 'press-? (2-D)', 'Tile Plot (2-D)', 'Plot (1-D)'] for method in method_labels: self.method_list.insert(END, method) var_keys = [k for k, v in self.ncffile.variables.items() if k not in ('time', 'latitude', 'longitude', 'latitude_bounds', 'longitude_bounds', 'time_bounds', 'tau0', 'tau1', 'TFLAG')] var_keys.sort() self.vars = [] for spc in var_keys: self.var.insert(END, spc) self.vars.append(spc) meta_label = Label(metaframe, text = 'Common Data Language Header:') meta_label.grid(column = 0, row = 0, sticky = 'W') meta_scrollbar = Scrollbar(metaframe, orient = VERTICAL) meta_scrollbar.grid(column = 1, row = 1, sticky = N + S) self.meta = Text(metaframe, height=10, width=118, bg='white', relief='flat', yscrollcommand = meta_scrollbar.set) self.meta.grid(column = 0, row = 1, sticky = 'W') from PseudoNetCDF.pncdump import pncdump try: from StringIO import StringIO except ImportError: from io import StringIO pdump = StringIO("") try: name = ', '.join(options.ifile) except: name = 'ifile' pncdump(self.ncffile, header = True, outfile = pdump, ) pdump.seek(0, 0) self.meta.insert(END, pdump.read()) self.meta.config(state=DISABLED) help = Button(goframe, text = 'Help', command = self.help) help.grid(column = 0, row = 7) quit = Button(goframe, text = 'Quit', command = self.quit) quit.grid(column = 0, row = 8) master.mainloop() def help(self): print("pl is pylab: details at matplotlib;") def quit(self): self.root.destroy() def _get_var(self, list): items = list.curselection() try: items = map(int, items) except: pass items = [self.vars[i] for i in items] return items def get_var(self): return self._get_var(self.var) def get_methods(self): items = self.method_list.curselection() try: items = map(int, items) except: pass items = [self.methods[i] for i in items] return items def execute(self): os.system('clear') vars = self.get_var() self.plotted_variables = self.plotted_variables.union(vars) methods, = self.get_methods() self.options.logscale = bool(self.logscale.get()) self.options.coastlines = bool(self.coastlines.get()) self.options.countries = bool(self.countries.get()) self.options.states = bool(self.states.get()) self.options.counties = bool(self.counties.get()) self.options.pre_txt = self.pre_txt.get() self.options.before_txt = self.before_txt.get() self.options.after_txt = self.after_txt.get() self.options.post_txt = self.post_txt.get() plotwithopts(self.ncffile, methods, vars, self.options)
class ResultList(Frame): """ Result List widget """ def __init__(self, master=None): Frame.__init__(self, master, padx=3, pady=3) self.columnconfigure(0, weight=1, minsize=50) self.columnconfigure(1, weight=1000) self.columnconfigure(2, weight=1, minsize=10) self.__createWidgets() self.show() def __createWidgets(self): self.lbl = Label(text="") self.lbl.grid(row=1, column=0, columnspan=2, in_=self) self.__hide_button = Button(text="Hide", command=self.hide) self.__hide_button.grid(row=0, column=0, columnspan=2, in_=self) self.__yScroll = Scrollbar(orient=VERTICAL) self.list = Listbox(yscrollcommand=self.__yScroll.set, selectmode=SINGLE) self.__yScroll.config(command=self.list.yview) def show(self): self.__hide_button.config(text="Hide", command=self.hide) self.list.grid(row=2, column=0, columnspan=2, sticky=N + S + E + W, in_=self) self.__yScroll.grid(row=2, column=2, sticky=W + N + S, in_=self) def hide(self): self.__hide_button.config(text="Show", command=self.show) self.list.grid_forget() self.__yScroll.grid_forget() def clear(self): self.list.delete(0, END) def fill(self, valList): self.clear() for v in valList: self.list.insert(END, v) self.list.see(0) self.select(0) def append(self, val): self.list.insert(END, val) self.list.see(END) def select(self, index=0): self.list.selection_set(index) def selected(self): return int(self.list.curselection()[0]) def width(self, width): self.list.config(width=width)