class OptionWindow(Toplevel): def __call__(self, options=[], display=True): self.options = options self.listbox.delete(0, END) for key, value in options: self.listbox.insert(END, key) if display: self.display() def __init__(self): Toplevel.__init__(self, master=root) self.options = None self.title('Matches') self.listbox = Listbox(master=self) self.listbox.pack(expand=True, fill=BOTH, side=TOP) self.listbox.focus_set() self.listbox.activate(0) self.listbox.selection_set(0) self.listbox.config(width=50) self.listbox.bind('<Key-h>', lambda event: self.listbox.event_generate('<Left>')) self.listbox.bind('<Key-l>', lambda event: self.listbox.event_generate('<Right>')) self.listbox.bind('<Key-k>', lambda event: self.listbox.event_generate('<Up>')) self.listbox.bind('<Key-j>', lambda event: self.listbox.event_generate('<Down>')) self.listbox.bind('<Escape>', lambda event: self.close()) self.protocol("WM_DELETE_WINDOW", self.close) self.transient(root) self.withdraw() def display(self): self.grab_set() self.deiconify() self.listbox.focus_set() # self.wait_window(self) def close(self): # When calling destroy or withdraw without # self.deoiconify it doesnt give back # the focus to the parent window. self.deiconify() self.grab_release() self.withdraw()
def __display_old_puzzles(self): self.__clear_answers() def onselect(evt): # Note here that Tkinter passes an event object to onselect() w = evt.widget index = int(w.curselection()[0]) value = w.get(index) self.puzzle = saveAndRead.readFromFile(value) self.game.puzzle = [[" ", " ", " ", " ", " "] for y in range(5)] self.parent.title(value) top.destroy() self.canvas.destroy() self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.canvas.pack(fill=BOTH, side=TOP) self.__draw_grid() self.__draw_puzzle() self.__write_clues() self.canvas.bind("<Button-1>", self.__cell_clicked) self.canvas.bind("<Key>", self.__key_pressed) top = Tk() top.title('Old Puzzles') l1 = Listbox(top) # Old puzzles and their solutions are displayed in pop-up for i,puzzle in enumerate(saveAndRead.getAllPuzzleLabels()): l1.insert(i,puzzle) l1.pack() l1.bind('<<ListboxSelect>>', onselect)
class liste_mots: """Définit un cadre contenant une liste de mot avec un ascenseur""" def __init__(self,parent,titre,compare): police_mots=font.Font(parent, size=12, family='Courier') self.cadre = LabelFrame(parent, borderwidth=2, relief=GROOVE,text=titre) self.ascenseur=Scrollbar(self.cadre,orient=VERTICAL) self.mots=Listbox(self.cadre, font=police_mots, width=LARGEUR_LISTE_MOTS,yscrollcommand = self.ascenseur.set ) self.mots.bind('<<ListboxSelect>>', self.selection) self.mots.grid(column=0,row=0) self.ascenseur.grid(column=1,row=0,sticky=S+N) self.ascenseur.config( command = self.mots.yview ) self.liste_mots=[] self.compare=compare def ajoute_mot_couleur(self,mot,couleur): fin=self.mots.size() self.mots.insert(fin,mot) self.mots.itemconfig(fin,fg=couleur) self.liste_mots.append(mot) def selection(self,e): mot=self.liste_mots[self.mots.curselection()[0]] self.compare.modifie_mot1(mot) self.parent.infos.delete("0.0",END) valeur=self.parent.dict_moyennes[mot] texte="Selon ce modèle, le mot '"+mot+"' a été lu en moyenne "+str(round(valeur,NB_DECIMALES))+ "fois par un élève de ce profil au cours de l'année écoulée." self.parent.infos.insert(END,texte)
def __init__(self, master, lists): Frame.__init__(self, master) self.lists = [] for list_, widget in lists: frame = Frame(self) frame.pack(side=LEFT, expand=YES, fill=BOTH) Label(frame, text=list_, borderwidth=1, relief=RAISED).pack(fill=X) list_box = Listbox( frame, width=widget, borderwidth=0, selectborderwidth=0, relief=FLAT, exportselection=FALSE, ) list_box.pack(expand=YES, fill=BOTH) self.lists.append(list_box) list_box.bind("<B1-Motion>", lambda e, s=self: s._select(e.y)) list_box.bind("<Button-1>", lambda e, s=self: s._select(e.y)) list_box.bind("<Leave>", lambda e: "break") list_box.bind("<B2-Motion>", lambda e, s=self: s._b2motion(e.x, e.y)) list_box.bind("<Button-2>", lambda e, s=self: s._button2(e.x, e.y)) frame = Frame(self) frame.pack(side=LEFT, fill=Y) Label(frame, borderwidth=1, relief=RAISED).pack(fill=X) scroll = Scrollbar(frame, orient=VERTICAL, command=self._scroll) scroll.pack(expand=YES, fill=Y) self.lists[0]["yscrollcommand"] = scroll.set
def __init__(self, master, lists, **kw): Frame.__init__(self, master) self.lists = [] # 多列ListBox并置 h = kw['height'] for l,w in lists: frame = Frame(self) frame.pack(side=tkinter.LEFT, expand=tkinter.YES, fill=tkinter.BOTH) Label(frame, text=l, width=w, borderwidth=0, background='#fff', relief=tkinter.FLAT).pack(expand=tkinter.YES, padx=1, ipady=4, fill=tkinter.BOTH) lb = Listbox(frame, width=w, height=h, borderwidth=0, selectborderwidth=0, relief=tkinter.FLAT, exportselection=tkinter.FALSE) lb.pack(expand=tkinter.YES, ipadx=5, fill=tkinter.BOTH) self.lists.append(lb) lb.bind('<B1-Motion>', lambda e, s=self: s._select(e.y)) lb.bind('<Button-1>', lambda e, s=self: s._select(e.y)) lb.bind('<Leave>', lambda e: 'break') lb.bind('<B2-Motion>', lambda e, s=self: s._b2motion(e.x, e.y)) lb.bind('<Button-2>', lambda e, s=self: s._button2(e.x, e.y)) # self.bind('<up>', lambda e, s=self: s._move (-1, MOVE_LINES)) # self.bind('<down>', lambda e, s=self: s._move (+1, MOVE_LINES)) # self.bind('<prior>', lambda e, s=self: s._move (-1, MOVE_PAGES)) # self.bind('<next>', lambda e, s=self: s._move (+1, MOVE_PAGES)) # self.bind('<home>', lambda e, s=self: s._move (-1, MOVE_TOEND)) # self.bind('<end>', lambda e, s=self: s._move (+1, MOVE_TOEND)) frame = Frame(self) frame.pack(side=tkinter.LEFT, fill=tkinter.Y) # Label(frame, borderwidth=0, relief=tkinter.FLAT).pack(padx=1, fill=tkinter.X) sb = Scrollbar(frame, orient=tkinter.VERTICAL, command=self._scroll) sb.pack(expand=tkinter.YES, fill=tkinter.Y) self.lists[0]['yscrollcommand']=sb.set
class HelpIndex(Frame): """ This is a navigation for the tutorial. It can be launched from the help menu in the top bar. """ def __init__(self): super().__init__(Toplevel()) self.pack(padx=20, pady=20) # the labels with the corresponding page numbers self.options = { 'Pattern Tab': 1, 'Color Schemes': 8, 'Loading & Saving': 5, 'Editing Colors': 16 } self.index = Listbox(self) for i, label in enumerate(self.options): self.index.insert(i, label) self.index.bind('<<ListboxSelect>>', self.launch_help) self.index.grid(row=10, column=0) def launch_help(self, event): w = event.widget ind = int(w.curselection()[0]) value = w.get(ind) tut = Tutorial() tut.goto(self.options[value])
def body(self, master) -> NoReturn: self.karel_tasks = [] for difficulty, path in self.karel_paths.items(): self.karel_tasks.append({ "value": f"-- {difficulty} --", "path": None, "difficulty": difficulty }) for p in sorted((path / 'solutions').glob("*.py")): self.karel_tasks.append({ "value": p.stem, "path": p, "difficulty": difficulty }) options = StringVar(value=[]) listbox = Listbox(master=master, height=max(len(self.karel_tasks), 20), listvariable=options) listbox.pack() task_names = [] for item in self.karel_tasks: task_names.append(item['value']) options.set(task_names) listbox.bind("<<ListboxSelect>>", self.save_selection_and_close)
def show_user_own_playlist(): global list_, times_called, t1 t1 = Toplevel() t1.config(bg='#3C3C3C') t1.title("Your Created Playlists Are Here!") t2 = Label(t1, text='Here Is The List Of Playlist You Created:', font=('Arial Rounded MT bold', 25, 'bold')) t2.pack() list_ = Listbox(t1, width=32, bg="#3C3C3C", fg='cyan', font=('Arial', 17, 'bold')) list_.pack() x124 = 0 lisst = [] for i1 in names: list_.insert(x124, i1) lisst.append(list_.get(0, END)) print(lisst) x124 += 1 list_.bind('<Double-Button>', question1)
class SubWindow(): def __init__(self, main_window, acc_list, main): self.master = Toplevel(main_window) self.master.resizable(False, False) self.master.title("Select Your Account") self.main = main self.len_max = 50 for m in acc_list: if len(m[0]) > self.len_max: self.len_max = len(m[0]) self.listbox = Listbox(self.master, width=self.len_max, selectmode=SINGLE) self.listbox.grid(row=0, column=1) self.listbox.bind('<Double-Button>', self.selected_event) self.listbox_list = [] for item in acc_list: self.listbox.insert(END, item[0]) self.listbox_list.append(item[1]) def selected_event(self, e=None): self.main.set_membershipID( self.listbox_list[self.listbox.curselection()[0]]) self.master.destroy()
def _generate_listbox(self, parent, meal=True): """Generoi listauskentän. Listauskenttä generoidaan parametrista riippuen joko ruokalajille tai raaka-aineelle. Kenttään syötetään jommat kummat arvoksi ja ruokalajin tapauksessa kenttään sidotaan triggeri tuplaklikkaukselle, jolla päästään poistamaan ruokalajeja kirjastosta. Args: parent: isäntäkehys, johon kenttä sidotaan. meal: vipu, jolla metodille kerrotaan, käsitelläänkö ruokalajien vai raaka-aineiden kenttää. Oletuksena käsitellään ruokalajien kenttää. Returns: Palauttaa listbox-objektin, joka sisältää ruokalajit tai raaka-aineet. """ if not meal: items = self._ctrl.fetch_ingredients() items.sort(key = lambda x: x.name) else: items = self._ctrl.fetch_meals() items.sort(key = lambda x: x.name) items_box = Listbox(parent, bg = "#FFFFFF") if meal: items_box.bind("<Double-Button-1>", lambda x: self._process_remove(items_box.get(constants.ACTIVE))) for i, item in enumerate(items): items_box.insert(i, item) return items_box
class SettingsOBDView(Frame): settings_list = ["SAE J1850 PWM","SAE J1850 VPW","AUTO, ISO 9141-2","ISO 14230-4 (KWP 5BAUD)","ISO 14230-4 (KWP FAST)","ISO 15765-4 (CAN 11/500)","ISO 15765-4 (CAN 29/500)","ISO 15765-4 (CAN 11/250)","ISO 15765-4 (CAN 29/250)","SAE J1939 (CAN 29/250)"] def __init__(self, ui_cont, *args, **kwargs): Frame.__init__(self, *args, **kwargs) self.initializeGauges() self.placeGauges() self.ui_cont = ui_cont def initializeGauges(self): self.title_font = font.Font(family="FreeMono", size=15, weight="bold") self.list_font = font.Font(family="FreeMono", size=13) self.settings_text = Label(self, text="OBD Connection", background="white", font=self.title_font) self.listbox = Listbox(self, font=self.list_font, selectmode="single", borderwidth=0, relief="flat", highlightthickness=0) self.listbox.bind('<ButtonRelease-1>', self.item_deselected) for item in self.settings_list: self.listbox.insert(10, item) def placeGauges(self): self.settings_text.pack(fill="x") self.listbox.pack(fill="both", expand=1) def item_deselected(self, event): curr_selct = self.listbox.curselection() if len(curr_selct) > 0: item_id = self.listbox.curselection()[0] item_name = self.settings_list[item_id] self.listbox.selection_clear(item_id)
def ShowResult(m,eid): m.destroy() root=Tk() root.title("Result") root.geometry("500x400") lframe=Frame(root) lframe.pack(side=LEFT) load=Image.open("index.png") render=ImageTk.PhotoImage(load) img=Label(lframe,image=render) img.image=render img.pack(side=LEFT) cFrame=Frame(root) cFrame.pack(side=LEFT) Label(cFrame,text="Panno:",font = "Times 17 bold").pack() Label(cFrame,text="").pack() listFrame=Frame(cFrame) listFrame.pack() scrollbarE=Scrollbar(listFrame) listBoxPanno=Listbox(listFrame,width=30,selectmode=BROWSE) listBoxPanno.config(yscrollcommand=scrollbarE.set) scrollbarE.config(command=listBoxPanno.yview) listBoxPanno.pack(expand = True, fill = BOTH,side=LEFT) scrollbarE.pack(fill = BOTH,side=RIGHT) db.getAllPanno(listBoxPanno) listBoxPanno.bind('<Double-Button-1>', lambda x:Panno_c(root,eid,listBoxPanno)) Label(cFrame,text="").pack() Button(cFrame,text="Back",font = "Times 10 bold",command=lambda :see_After(root) ).pack(expand = True, fill = BOTH) root.mainloop()
def get_recent_updates(): import requests from bs4 import BeautifulSoup import time url = "https://www.wuxiaworld.com" response = requests.get(url) recents = [] t = response.text.split( "<h3>Most Recently Updated</h3>\n</div>\n<div class=\"section-content\">\n<table class=\"table table-novels\">\n<thead class=\"hidden-xs\">\n<tr>\n<th>Title</th>\n<th>Release</th>\n<th>Translator</th>\n<th>Time</th>\n</tr>\n</thead>\n<tbody>" ) t = t[1].split("<tr>") for i in range(1, len(t)): item = [] x = t[i].split("<td>\n<span class=\"title\">\n<a href=\"")[1].split( "\">")[1].split("</a>")[0] soup = BeautifulSoup(x, "html.parser") item.append(soup.text) x = t[i].split("<div class=\"visible-xs-inline\">\n<a class=\"" )[1].split("\" href=\"")[1].split("\">") item.append(url + x[0]) x = x[1].split("</a>") soup = BeautifulSoup(x[0], "html.parser") item.append(soup.text[1:-1]) x = t[i].split("data-timestamp=\"")[1].split("\">")[0] item.append(x) recents.append(item) ts = time.time() top = Tk() top.geometry("800x600") sb = Scrollbar(top) sb.pack(side=RIGHT, fill=Y) mylist = Listbox(top, yscrollcommand=sb.set) for recent in recents: mylist.insert(END, recent[0]) mylist.insert(END, recent[1]) char_list = recent[2] re_pattern = re.compile(u'[^\u0000-\uD7FF\uE000-\uFFFF]', re.UNICODE) filtered_string = re_pattern.sub(u'\uFFFD', char_list) mylist.insert(END, filtered_string) diff = (int(ts) - int(recent[3])) if diff > 3600: hour = str(int(diff / 3600)) mylist.insert(END, "%s hour ago.\n" % hour) elif diff > (24 * 3600): day = str(int(diff / (24 * 3600))) mylist.insert(END, "%s day ago.\n" % day) else: minute = str(int(diff / 60)) mylist.insert(END, "%s minute ago.\n" % minute) mylist.bind('<<ListboxSelect>>', callback) mylist.pack(fill=BOTH, expand=True) sb.config(command=mylist.yview) mainloop()
class App: WIDTH = 600 HEIGHT = 800 def __init__(self, root, funcs): self.root = root self.root.title("Plotki Migotki") self.root.geometry("%dx%d%+d%+d" % (App.WIDTH, App.HEIGHT, 0, 0)) self.main_frame = Frame(root, width=App.WIDTH, height=App.HEIGHT) self.main_frame.pack_propagate(0) self.main_frame.pack() self.list_map = funcs self.listbox = Listbox(self.main_frame, height=4, width=15, selectbackground="orange") for ix, (entry, _f) in enumerate(self.list_map): plot_type, title = entry self.listbox.insert(ix, title) if plot_type == BARCHART: self.listbox.itemconfig(ix, bg='green') elif plot_type == BOXPLOT: self.listbox.itemconfig(ix, bg='yellow') elif plot_type == SCATTERPLOT: self.listbox.itemconfig(ix, bg='grey') elif plot_type == HISTOGRAM: self.listbox.itemconfig(ix, bg='magenta') self.listbox.bind("<Double-Button-1>", self.call_back) self.listbox.bind("<Return>", self.call_back) self.listbox.pack(expand=1, fill=tk.BOTH) def call_back(self, event): zones = self.listbox.curselection() assert len(zones) == 1 ix = zones[0] ix, cb = self.list_map[ix] cb()
def __init__(self, master, lists): """initialize visual frame""" Frame.__init__(self, master) self.lists = [] for l, w in lists: frame = Frame(self) frame.pack(side=LEFT, expand=YES, fill=BOTH) Label(frame, text=l, borderwidth=1, relief=RAISED).pack(fill=X) lb = Listbox(frame, width=w, borderwidth=0, selectborderwidth=0, relief=FLAT, exportselection=FALSE) lb.pack(expand=YES, fill=BOTH) self.lists.append(lb) lb.bind('<B1-Motion>', lambda e, s=self: s._select(e.y)) lb.bind('<Button-1>', lambda e, s=self: s._select(e.y)) lb.bind('<Leave>', lambda e: 'break') lb.bind('<B2-Motion>', lambda e, s=self: s._b2motion(e.x, e.y)) lb.bind('<Button-2>', lambda e, s=self: s._button2(e.x, e.y)) frame = Frame(self) frame.pack(side=LEFT, fill=Y) Label(frame, borderwidth=1, relief=RAISED).pack(fill=X) sb = Scrollbar(frame, orient=VERTICAL, command=self._scroll) sb.pack(expand=YES, fill=Y) self.lists[0]['yscrollcommand'] = sb.set
class model_select(Frame): def __init__(self,controller,model_list,current_model,master,*args,**kwargs): self.controller = controller self.model_list = model_list self.current_model = current_model # Dibujar widget super().__init__(master, *args, **kwargs) self.listbox = Listbox(self, exportselection=False) self.listbox.bind('<<ListboxSelect>>', self.selection) self.listbox.pack() for item in self.model_list: self.listbox.insert(END, item) self.listbox.select_set(0) self.listbox.event_generate("<<ListboxSelect>>") def selection(self,x): w = x.widget index = int(w.curselection()[0]) value = w.get(index) print(value) # Send message to interface to load another model f_path = os.path.join(config_folder, value) self.current_model.change_model(f_path) self.controller.event_change_model(self.current_model) pass
class AlexListBox(Frame): def __init__(self, parent, items=[], width=20, height=10, selectioncommand=None): super().__init__(parent) self.selectioncommand = selectioncommand self.listbox = Listbox(self, width=width, height=height) self.listbox.grid(row=0, column=0) scrollbar_y = AlexScrollbar(self, command=self.listbox.yview) scrollbar_y.grid(row=0, column=1, sticky=N + S) self.listbox.configure(yscrollcommand=scrollbar_y.set) scrollbar_x = AlexScrollbar(self, command=self.listbox.xview, orient=HORIZONTAL) scrollbar_x.grid(row=1, column=0, sticky=E + W) self.listbox.configure(xscrollcommand=scrollbar_x.set) if self.selectioncommand is not None: self.listbox.bind('<<ListboxSelect>>', self._select_callback) self.set_items(items) def _select_callback(self, event): selection = self.get() # ignore unselect if selection != None: self.selectioncommand(selection) def set_items(self, items): self.listbox.delete(0, END) self.items = [] for item in items: self.items.append(item) self.listbox.insert(END, "%s" % item) def get_items(self): return self.items def get(self): selections = self.listbox.curselection() if len(selections) > 0: return self.items[selections[0]] else: return None def set(self, selection): self.listbox.selection_clear(0, len(self.items)) for i in range(0, len(self.items)): if self.items[i] == selection: self.listbox.selection_set(i)
def imprimePontos(): def exibeValor(): print(combo.get()) print(ponto) Graph = bpg.Equation(Field, ponto[1], ponto[2], ponto[0]) Graph.fill_x_and_y_lists() if combo.get() == "Ponto de interceptação": Graph.plot_graph_one() elif combo.get() == "Posição x Tempo": Graph.plot_graph_two_Y() Graph.plot_graph_two_X() elif combo.get() == "Velocidade x Tempo": Graph.plot_graph_threeY() Graph.plot_graph_threeX() elif combo.get() == "Acelereração x Tempo": Graph.plot_graph_fourY() Graph.plot_graph_fourX() elif combo.get() == "Distancia x Tempo": Graph.plot_graph_five() if len(Field.Interception_Index_Points) != 0: nova_janela = tk.Tk() nova_janela.title("Bomba Patch 2020 ATUALIZADO") nova_janela.geometry("1100x600") mostraPontos = Listbox(nova_janela, width=80, height=30, font=("Helvetica", 10), highlightthickness=2, selectbackground="red") mostraPontos.place(relx=0.7, rely=0.5, anchor=CENTER) mostraPontos.delete(1, END) mostraPontos.bind('<<ListboxSelect>>', imprime) scrollbar = tk.Scrollbar(nova_janela, orient="vertical") scrollbar.config(command=mostraPontos.yview) scrollbar.pack(side="right", fill="y") mostraPontos.config(yscrollcommand=scrollbar.set) if bpf.get_interception_points(Field, mostraPontos): combo = Combobox(nova_janela, width=40) combo['values'] = ( "Ponto de interceptação", "Posição x Tempo", "Velocidade x Tempo", "Acelereração x Tempo", "Distancia x Tempo") combo.current(0) # definimos o valor padrão! combo.pack() combo.place(x=280, y=300, anchor=CENTER) botao = tk.Button(nova_janela, text = "Mostrar Gráfico", width=12, height=2,command = exibeValor) botao.pack() botao.place(x=280, y=350, anchor=CENTER) nova_janela.mainloop() else: messagebox.showinfo("Aviso", "O robô NÃO intercepta a bola")
def __init__(self, *, multiple_runner_class, input_spec, left_name, right_name): """Sets up windows and the instance of RunMultipleTimes that will do the actual work.""" #: The input_spec is an iterable of #: :py:class:`farg.core.read_input_spec.SpecificationForOneRun`. self.input_spec = input_spec #: Class responsible for the actual running multiple times. self.multiple_runner_class = multiple_runner_class #: Main window self.mw = mw = Tk() #: Statistics thus far, grouped by input. self.stats = AllStats(left_name=left_name, right_name=right_name) #: Are we in the process of quitting? self.quitting = False self.status_label = Label(mw, text='Not Started', font=('Times', 20), foreground='#000000') self.status_label_text = self.status_label.cget('text') self.status_label.pack(side=TOP, expand=True, fill=X) #: Has a run started? Used to ensure single run. self.run_started = False details_frame = Frame(mw) details_frame.pack(side=TOP) #: listbox on left listing inputs. frame = Frame(details_frame) scrollbar = Scrollbar(frame, orient=VERTICAL) listbox = Listbox(frame, yscrollcommand=scrollbar.set, height=25, width=70, selectmode=SINGLE) scrollbar.config(command=listbox.yview) scrollbar.pack(side=RIGHT, fill=Y) listbox.pack(side=LEFT, fill=BOTH, expand=1) listbox.bind('<ButtonRelease-1>', self.SelectForDisplay, '+') frame.pack(side=LEFT) self.listbox = listbox #: Canvas on right for details self.canvas = Canvas(details_frame, width=kCanvasWidth, height=kCanvasHeight, background='#FFFFFF') self.canvas.pack(side=LEFT) #: which input are we displaying the details of? self.display_details_for = None #: Thread used for running self.thread = None self.mw.bind('<KeyPress-q>', lambda e: self.Quit()) self.mw.bind('<KeyPress-r>', lambda e: self.KickOffRun()) self.Refresher() self.mw.after(1000, self.KickOffRun)
def __init__(self, *, multiple_runner_class, input_spec, left_name, right_name): """Sets up windows and the instance of RunMultipleTimes that will do the actual work.""" #: The input_spec is an iterable of #: :py:class:`farg.core.read_input_spec.SpecificationForOneRun`. self.input_spec = input_spec #: Class responsible for the actual running multiple times. self.multiple_runner_class = multiple_runner_class #: Main window self.mw = mw = Tk() #: Statistics thus far, grouped by input. self.stats = AllStats(left_name=left_name, right_name=right_name) #: Are we in the process of quitting? self.quitting = False self.status_label = Label( mw, text='Not Started', font=('Times', 20), foreground='#000000') self.status_label_text = self.status_label.cget('text') self.status_label.pack(side=TOP, expand=True, fill=X) #: Has a run started? Used to ensure single run. self.run_started = False details_frame = Frame(mw) details_frame.pack(side=TOP) #: listbox on left listing inputs. frame = Frame(details_frame) scrollbar = Scrollbar(frame, orient=VERTICAL) listbox = Listbox( frame, yscrollcommand=scrollbar.set, height=25, width=70, selectmode=SINGLE) scrollbar.config(command=listbox.yview) scrollbar.pack(side=RIGHT, fill=Y) listbox.pack(side=LEFT, fill=BOTH, expand=1) listbox.bind('<ButtonRelease-1>', self.SelectForDisplay, '+') frame.pack(side=LEFT) self.listbox = listbox #: Canvas on right for details self.canvas = Canvas( details_frame, width=kCanvasWidth, height=kCanvasHeight, background='#FFFFFF') self.canvas.pack(side=LEFT) #: which input are we displaying the details of? self.display_details_for = None #: Thread used for running self.thread = None self.mw.bind('<KeyPress-q>', lambda e: self.Quit()) self.mw.bind('<KeyPress-r>', lambda e: self.KickOffRun()) self.Refresher() self.mw.after(1000, self.KickOffRun)
def Listatag(self): # Lista de tags * em fase de teste title = ['189.186.63.44.20','123.145.584.55.5', '','',''] titleList = Listbox(self, height=5) for t in title: titleList.insert(END, t) titleList.grid(row=7, column=2, columnspan=2, pady=5, sticky=W+E) titleList.bind("<<ListboxSelect>>", self.newTitle)
def setupGui(): global window global labelShows, labelEpisodes, labelDownloads global listShows, listEps, listDownloads global btnAbout, btnDownload, btnChooseFolder global folderFrame global folderName window = Tk() window.title('iView') window.minsize(300, 200) labelShows = Label(window, text='Shows') labelShows.grid(column=0, row=0, sticky=[N,S,E,W]) listShows = Listbox(window) listShows.grid(column=0, row=1, sticky=[N,S,E,W]) listShows.bind('<<ListboxSelect>>', indexEpsEv) indexShows() labelEpisodes = Label(window, text='Episodes') labelEpisodes.grid(column=1, row=0, sticky=[N,S,E,W]) listEps = Listbox(window) listEps.grid(column=1, row=1, sticky=[N,S,E,W]) listEps.bind('<<ListboxSelect>>', setEpNumEv) indexEps(0) labelDownloads = Label(window, text='Downloads') labelDownloads.grid(column=2, row=0, sticky=[N,S,E,W]) listDownloads = Listbox(window) listDownloads.grid(column=2, row=1, sticky=[N,S,E,W]) btnAbout = Button(window, text='About', command=about) btnAbout.grid(column=0, row=2, sticky=[N,S,E,W]) btnDownload = Button(window, text='Download', command=download) btnDownload.grid(column=1, row=2, sticky=[N,S,E,W]) btnChooseFolder = Button(window, text='Choose Download Folder', command=chooseDir) btnChooseFolder.grid(column=2, row=2, sticky=[N,S,E,W]) folderName = Text(window, height=1) folderName.grid(column=0, row=3, columnspan=3) folderName.insert(END, expanduser("~")+(':Videos:iView:'.replace(':', os.sep))) window.columnconfigure(0, weight=1) window.columnconfigure(1, weight=1) window.columnconfigure(2, weight=1) window.rowconfigure(1, weight=1) def updateDownloadList(): refreshDownloadList() window.after(1000, updateDownloadList) dlListThrd = threading.Thread(target=updateDownloadList) dlListThrd.setName('Update Download List') dlListThrd.start()
def create_gui(): """ Method that creates and initializes the GUI :return: """ global window window = Tk() window.title("Train Data Marker 0.1") window.geometry('1060x520') window.resizable(0, 0) global in_listbox, labeling_listbox, training_listbox, image_label # Setup the input - list of avi video files in_listbox = Listbox(window, height=30) in_listbox.grid(row=0, column=0, rowspan=2, sticky=NSEW) in_listbox.bind('<<ListboxSelect>>', video_select_action) in_scroll = Scrollbar() in_scroll.grid(row=0, column=1, rowspan=2, sticky=NSEW) in_scroll.config(command=in_listbox.yview) in_listbox.config(yscrollcommand=in_scroll.set) # Setup the listbox of images for labeling (intermediate step) labeling_listbox = Listbox(window, height=30) labeling_listbox.grid(row=0, column=2, rowspan=2, sticky=NSEW) labeling_scroll = Scrollbar() labeling_scroll.grid(row=0, column=3, rowspan=2, sticky=NSEW) labeling_scroll.config(command=labeling_listbox.yview) labeling_listbox.config(yscrollcommand=labeling_scroll.set) # Setup the listbox of images for output training data training_listbox = Listbox(window, height=30) training_listbox.grid(row=0, column=4, rowspan=2, sticky=NSEW) training_scroll = Scrollbar() training_scroll.grid(row=0, column=5, rowspan=2, sticky=NSEW) training_scroll.config(command=training_listbox.yview) training_listbox.config(yscrollcommand=training_scroll.set) right_pane = LabelFrame(window, text='Image', height=480, width=640) right_pane.grid(row=0, column=6, rowspan=2, sticky=NSEW) image_label = Label(right_pane, text='Im here too', width=640, height=480) image_label.grid(sticky=NSEW) menubar = create_menu() window.config(menu=menubar) window.columnconfigure(3, weight=1) window.rowconfigure(3, weight=1) update_status() window.mainloop()
class RSVisCanvasFrame(Frame): # method -------------------------------------------------------------- # ----------------------------------------------------------------------- def __init__( self, parent, images, data, **kwargs ): super(RSVisCanvasFrame, self).__init__(parent) self.columnconfigure(2, weight=1) self.rowconfigure(0, weight=1) self.scrollbar = Scrollbar(self, orient="vertical", width=16) self.listbox = Listbox(self, yscrollcommand=self.scrollbar.set, width=37, activestyle=UNDERLINE) self.scrollbar.config(command=self.listbox.yview) self.scrollbar.grid(row=0, column=0, sticky=N+S) self.listbox.grid(row=0, column=1, sticky=N+S) for count, item in enumerate(images): self.listbox.insert(END, pathlib.Path(item[0].path).stem) self.listbox.bind("<<ListboxSelect>>", self.listbox_event) self._canvas = rsviscv.RSVisCanvas(self, images, data, **kwargs) self._canvas.set_container() self._canvas.grid(row=0, column=2, sticky=N+S+E+W) # parent.bind("<a>", self.key_a) # parent.bind("<d>", self.key_d) # method -------------------------------------------------------------- # ----------------------------------------------------------------------- def listbox_event(self,event): try: self._canvas._idx_list(index=self.listbox.curselection()[0]) self._canvas.set_container() except IndexError: pass # method -------------------------------------------------------------- # ----------------------------------------------------------------------- def update_listbox(self, event): self.listbox.activate(self._canvas.get_idx_list()) # method -------------------------------------------------------------- # ----------------------------------------------------------------------- def key_a(self, event, **kwargs): """Show the previous image in given image list (see listbox).""" self.update_listbox(event) # method -------------------------------------------------------------- # ----------------------------------------------------------------------- def key_d(self, event, **kwargs): """Show the next image in given image list (see listbox).""" self.update_listbox(event)
class ScenarioCenter(Toplevel): def __init__(self, parent, scEvents, scName): super().__init__(parent, height=100) self.parent = parent self.attributes('-topmost', 'true') self.resizable(width=False, height=False) self.title('Scenario Center') self.scEvents = scEvents self.scName = scName editListFrame = Frame(self) editListFrame.pack() self.currentSelection = [] self.lb = Listbox(editListFrame, selectmode=MULTIPLE) for i in self.scEvents: self.lb.insert(END, i) self.lb.bind("<<ListboxSelect>>", self.onSelect) self.lb.grid(row=0, column=0, columnspan=2) self.DeleteBtn = Button(editListFrame, text='Delete', width=12, height=1) self.DeleteBtn.grid(row=0, column=2, padx=5) self.DeleteBtn.bind('<ButtonRelease-1>', self.onDeleteClick) self.cancelBtn = Button(editListFrame, text='Cancel', width=12, height=1) self.cancelBtn.grid(row=1, column=1, pady=2) self.cancelBtn.bind('<ButtonRelease-1>', self.onCancelClick) self.okBtn = Button(editListFrame, text='OK', width=12, height=1) self.okBtn.grid(row=1, column=2, padx=1, pady=2) self.okBtn.bind('<ButtonRelease-1>', self.onOkClick) def onCancelClick(self, event): log.deleteScenarioFile(self.scName) self.parent.updateList() self.destroy() def onDeleteClick(self, event): print(self.scEvents) self.lb.delete(0, END) for idx in self.currentSelection[::-1]: del self.scEvents[idx] for i in self.scEvents: self.lb.insert(END, i) def onOkClick(self, event): log.saveSelectedScenario(self.scName, self.scEvents) self.destroy() def onSelect(self, event): self.currentSelection = list(self.lb.curselection())
class SettingsView(Frame): settings_list = [ "General", "Wi-Fi", "Appearance", "GPS Chip", "OBD Connection" ] def __init__(self, ui_cont, *args, **kwargs): Frame.__init__(self, *args, **kwargs) self.initializeGauges() self.placeGauges() self.ui_cont = ui_cont self.gps_chip_view = SettingsGPSView(ui_cont, self.ui_cont.root) self.general_view = SettingsGeneralView(ui_cont, self.ui_cont.root) self.wifi_view = SettingsWifiView(ui_cont, self.ui_cont.root) self.appearance_view = SettingsAppearanceView(ui_cont, self.ui_cont.root) self.obd_view = SettingsOBDView(ui_cont, self.ui_cont.root) def initializeGauges(self): self.title_font = font.Font(family="FreeMono", size=15, weight="bold") self.list_font = font.Font(family="FreeMono", size=28) self.settings_text = Label(self, text="Settings", background="white", font=self.title_font) self.listbox = Listbox(self, font=self.list_font, selectmode="single", borderwidth=0, relief="flat", highlightthickness=0) self.listbox.bind('<ButtonRelease-1>', self.item_deselected) for item in self.settings_list: self.listbox.insert(10, item) def placeGauges(self): self.settings_text.pack(fill="x") self.listbox.pack(fill="both", expand=1) def item_deselected(self, event): curr_selct = self.listbox.curselection() if len(curr_selct) > 0: item_id = self.listbox.curselection()[0] item_name = self.settings_list[item_id] if item_name == "General": self.ui_cont.display_view(self.general_view) if item_name == "Wi-Fi": self.ui_cont.display_view(self.wifi_view) if item_name == "Appearance": self.ui_cont.display_view(self.appearance_view) if item_name == "GPS Chip": self.ui_cont.display_view(self.gps_chip_view) if item_name == "OBD Connection": self.ui_cont.display_view(self.obd_view) self.listbox.selection_clear(item_id)
class HelpWindow(Toplevel): def __init__(self, master=None): super().__init__(master) self.root = master self.title = 'Help' self.list = Listbox(self) self.list.pack(side="left", fill="y") self.text = scrolledtext.ScrolledText(self, wrap=WORD) self.text.pack(side="right", fill="both", expand=True) self.images = [] self.load_list() self.list.bind('<<ListboxSelect>>', self.list_click) self.list.select_set(0) self.list_click(None) def load_list(self): self.files = {} path = os.path.dirname(os.path.realpath(__file__)) file_path = os.path.join(path, 'index.json') f = open(file_path, 'rt') self.files = json.loads(f.read()) for counter, entry in enumerate(self.files['files']): self.list.insert(counter, entry['name']) f.close() def list_click(self, event): index = self.list.curselection()[0] item = self.files['files'][index] path = os.path.dirname(os.path.realpath(__file__)) fileName = os.path.normpath(os.path.join(path, item['fileName'])) self.render_file(fileName) def render_file(self, fileName): path = os.path.dirname(os.path.realpath(__file__)) f = open(os.path.join(fileName), 'rt') buffer = f.read() f.close() parser = MarkdownParser() tokens = parser.parse(buffer) renderer = MarkdownRenderTk(self.text) renderer.render(tokens, os.path.normpath(os.path.join(path, '../res')), self.images, self.link_click) def link_click(self, url, title): if (url.startswith('http:') or url.startswith('https:')): # Open a web browser with that link. webbrowser.open(url) else: # Open a markdown file. path = os.path.dirname(os.path.realpath(__file__)) fileName = os.path.normpath(os.path.join(path, url)) self.render_file(fileName)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) sbar = Scrollbar(self) list = Listbox(self) sbar.config(command=list.yview) list.config(yscrollcommand=sbar.set) sbar.pack(side='right', fill='y') list.pack(side='left', expand='yes', fill='both') list.bind('<<ListboxSelect>>', self._on_listbox_click) self.__list_click_callback = None self.__list = list self.__sbar = sbar
def create_tasks_list(self, person: Person): tasks_listbox = Listbox(self.top, height=20) scroll = tkinter.Scrollbar(command=tasks_listbox.yview) tasks_listbox.bind( '<Double-Button>', lambda event: self.on_task_select(tasks_listbox, person)) tasks_listbox.config(yscrollcommand=scroll.set) self.fill_listbox(person.tasks_schedule, tasks_listbox) person.tasks_schedule.listeners.append( lambda: self.fill_listbox(person.tasks_schedule, tasks_listbox)) tasks_listbox.pack(side="left") scroll.pack(side="left", fill=tkinter.Y) self.list_boxes.append(tasks_listbox) self.list_boxes.append(scroll)
class LabeledListBox(Frame): def __init__(self, parent, list_model, label_text): Frame.__init__(self, parent) self._list_model = list_model self._list_objects = [] self._selected_items = [] scrollbar = Scrollbar(self, orient=VERTICAL) Label(self, text=label_text).pack() self.listbox = Listbox(self, selectmode=EXTENDED, exportselection=0, yscrollcommand=scrollbar.set, borderwidth=0, highlightthickness=0) scrollbar.config(command=self.listbox.yview) scrollbar.pack(side=RIGHT, fill=Y) self.listbox.pack(side=LEFT, fill=BOTH, expand=1) self.listbox.bind('<<ListboxSelect>>', self._on_select) self._list_model.list_items_model.add_listener(self._list_items_changed) self._list_model.selected_items_model.add_listener(self._selected_items_changed) self._update_list_items() def _list_items_changed(self, values): self._update_list_items() def _selected_items_changed(self, values): self._update_selected_items() def _update_list_items(self): values, labels = self._list_model.list_items_model.get_list_values() if not values == self._list_objects: self._list_objects = [] self._selected_items = [] self.listbox.delete(0, END) for value, label in zip(values, labels): self._list_objects.append(value) self.listbox.insert(END, label) self._update_selected_items() def _update_selected_items(self): selected_items = self._list_model.selected_items_model.selected_items if not selected_items == self._selected_items: self._selected_items = selected_items for index, list_item in enumerate(self._list_objects): if list_item in selected_items: self.listbox.selection_set(index) def _on_select(self, evt): visible_selected_indices = self.listbox.curselection() for index, list_item in enumerate(self._list_objects): if index in visible_selected_indices: self._list_model.selected_items_model.select(list_item) else: self._list_model.selected_items_model.deselect(list_item)
class TkHref(Tk): def __init__(self): Tk.__init__(self) self.state = ('zoomed') self.t2l = dict() self.urls = { 'Top News': 'http://www.moneycontrol.com/rss/MCtopnews.xml', 'Latest News': 'http://www.moneycontrol.com/rss/latestnews.xml', 'Most Popular': 'http://www.moneycontrol.com/rss/MCtopnews.xml', 'Business News': 'http://www.moneycontrol.com/rss/MCtopnews.xml', 'Brokerage Recommendations': 'http://www.moneycontrol.com/rss/brokeragerecos.xml', 'Buzzing Stocks': 'http://www.moneycontrol.com/rss/buzzingstocks.xml', 'Market Reports': 'http://www.moneycontrol.com/rss/marketreports.xml', 'Global News': 'http://www.moneycontrol.com/rss/internationalmarkets.xml', 'Market Edge': 'http://www.moneycontrol.com/rss/marketedge.xml', 'Technicals': 'http://www.moneycontrol.com/rss/technicals.xml', 'Results': 'http://www.moneycontrol.com/rss/results.xml' } self.l01 = ttk.Label(self, text='Hyperlinks in Tkinter') self.h01 = ttk.Separator(self, orient='horizontal') self.c01 = ttk.Combobox(self, values=[*self.urls.keys()]) self.b01 = ttk.Button(self, text='Get News', command=self.fetch) self.lb0 = Listbox(self, foreground='blue', width=80, height=15) self.lb0.bind('<<ListboxSelect>>', self.selected) self.l01.grid(row=0, column=0, columnspan=2) self.h01.grid(row=1, column=0, columnspan=2, sticky='ew') self.c01.grid(row=2, column=0) self.b01.grid(row=2, column=1) self.lb0.grid(row=3, column=0, columnspan=2, sticky='ew') # ['Select News Catagory', 'Top News', 'Latest', 'Most Popular', 'Business', 'Brokerage Recommendations', 'Buzzing Stocks', 'Market Report', 'Global News', 'Market Edge', 'Technicals', 'Results'] def fetch(self): try: f = feedparser.parse(self.urls[self.c01.get()]) # ['title', 'title_detail', 'links', 'link', 'summary', 'summary_detail', 'published', 'published_parsed', 'id', 'guidislink'] for i in f.entries: self.t2l[i.title] = i.link self.lb0.insert('end', i.title) except Exception as e: print(e) def selected(self, something): print(something) webbrowser.open_new(self.t2l[self.lb0.get(self.lb0.curselection())])
def initUI(self): self.parent.title("TVstream manager") self.stytle = ttk.Style() self.pack(fill=BOTH, expand=1) self.columnconfigure(0, weight=1, pad=2) self.columnconfigure(2, weight=1, pad=2) self.columnconfigure(4, pad=7) #self.rowconfigure(3, weight=1) #self.rowconfigure(4, weight=1, pad=7) lbll = Label(self, text="Lingua") lbll.grid(row=0,column=0,sticky=W, pady=4, padx=5) lble = Label(self, text="Emittenti") lble.grid(row=0,column=2,sticky=W, pady=1, padx=5) global langlst scrollang = Scrollbar(self) langlst = Listbox(self,font='Arial 9',yscrollcommand=scrollang.set) scrollang.config(command = langlst.yview) for i in lingue: langlst.insert(END, i) langlst.focus_set() langlst.bind("<<ListboxSelect>>", self.onSelectLang) langlst.grid(row=1,column=0, columnspan=2, padx=6,sticky=E+W+S+N) scrollang.grid(row=1,column=1, sticky=E+S+N) global emitlst scrollemit = Scrollbar(self) emitlst = Listbox(self,font='Arial 9',yscrollcommand=scrollemit.set) scrollemit.config(command = emitlst.yview ) emitlst.bind("<<ListboxSelect>>", self.onSelectEmittente) emitlst.grid(row=1,column=2, columnspan=2, padx=5,sticky=E+W+S+N) scrollemit.grid(row=1,column=3,sticky=E+S+N) lbltxt = Label(self, text="Output log") lbltxt.grid(row=2,column=0, columnspan=3, sticky=W, pady=4, padx=5) global area area = Text(self,height=10,font='Arial 9') area.grid(row=3, column=0, columnspan=5, rowspan=1, padx=5, sticky=E+W+S+N) scrolltxt = Scrollbar(self) scrolltxt.config(command = area.yview) scrolltxt.grid(row=3,column=4, columnspan=1, rowspan=1, sticky=E+N+S) play = Button(self, text='Play', command=self.playUrl, bg='gray', fg='black') play.grid(row=1,column=4,padx=4,sticky=E+W)
def makeWidgets(self, options_): labList = Listbox(self, relief=SUNKEN) sbar = Scrollbar(self) sbar.config(command=labList.yview) # xlink sbar and list labList.config(yscrollcommand=sbar.set) # move one moves other sbar.pack(side=RIGHT, fill=Y) # pack first=clip last labList.pack(side=LEFT, expand=YES, fill=BOTH) # list clipped first pos = 0 for label in options_: # add to listbox labList.insert(pos, label) # or insert(END,label) pos += 1 # or enumerate(options) #list.config(selectmode=SINGLE, setgrid=1) # select,resize modes labList.bind('<Double-1>', self.handleList) # set event handler self.listbox = labList
def data_editor(): def init_data(): with open(filename + '.rd.json', 'r') as f: imported = json.load(f) data_dict['version'] = imported['version'] for key in data['nodes']: if key in imported['nodes']: data_dict['nodes'][key] = imported['nodes'][key] else: data_dict['nodes'][key] = 'Unnamed' def select(event): print(mylist.selection_get()) key = str(mylist.selection_get()).split(':')[0] string = simpledialog.askstring('Edit name', 'Enter name for node : ' + key) if string and string != '': data_dict['nodes'][key] = string with open(filename + '.rd.json', 'w') as f: json.dump(data_dict, f) print('Dumped to : ' + f.name) insert_data() def insert_data(): mylist.delete(0, tk.END) for key in data_dict['nodes']: mylist.insert(tk.END, key + ':' + data_dict['nodes'][key]) data_dict = {} data_nodes_dict = {} data_dict['nodes'] = data_nodes_dict data_editing = False init_data() data_f = tk.Tk() scrollbar = Scrollbar(data_f) scrollbar.pack( side = tk.RIGHT, fill = tk.Y ) mylist = Listbox(data_f, yscrollcommand = scrollbar.set ) insert_data() mylist.pack( side = tk.LEFT, fill = tk.BOTH ) scrollbar.config( command = mylist.yview ) mylist.bind('<Double-1>', select) data_f.mainloop()
def showVariant(root): varform = Toplevel(root) varform.geometry('400x180') varform.focus_force() listbox = Listbox(varform, width=10, height=2, font=('13')) listbox.bind('<<ListboxSelect>>', lambda event, arg=listbox:select_item(event, arg)) listbox.place(x=150, y=20) for item in listbox_items: listbox.insert(END, item) btn1 = Button(varform, text="Continue", width=15, height=3, command=lambda:gotoMain(root, varform)) btn1.place(x=50, y=80) btn2 = Button(varform, text="Exit", width=15, height=3, command=lambda:exitAll(root)) btn2.place(x=200, y=80)
def _about_creatures(self): lb = Listbox(self.frame, height=15, width=50, selectmode=SINGLE) lb.bind('<<ListboxSelect>>', self._onselect) lb.grid(row=1, column=2) items = self.model.creatures.items() items = sorted(items, key=lambda k: k[0][0] * self.model.width + k[0][1]) for (x, y), creature in items: lb.insert(END, [x, y, creature.life]) self.canvas = NeuroCanvas(self.frame, (2, 2), 400, 300)
def initUI(self): self.parent.title("Listbox") self.pack(fill=BOTH, expand=1) IP_list = ['IP Address 1', 'IP Address 2', 'IP Address 3', 'IP Address 4', 'IP Address 5', 'IP Address 6', 'IP Address 7', 'IP Address 8', 'IP Address 9', 'IP Address 10', 'IP Address 11', 'IP Address 12', 'IP Address 13', 'IP Address 14', 'IP Address 15', 'IP Address 16'] IP_numbers = ['150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1'] lb = Listbox(self) for i in IP_list: 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=270) # 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") lb.grid(sticky=W, pady=40, padx=50) #lb = Text(self) lb.grid(row=1, column=0, columnspan=2, rowspan=4, padx=50, sticky=E+W+S+N) 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 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)
def initUI(self): self.parent.title("Listbox") self.pack(fill=BOTH, expand=1) acts = ["Scarlett Johansson", "Rachel Weiss", "Natalie Portman", "Jessica Alba", "Angelina jolie", "Emma Stone", "Sandra Bullock", "Julia Roberts", "Jennifer Lawrence", "Mila Kunis", "Jennifer Aniston", "Charlize Theron", "Cameron Diaz", "Nicole Kidman", "Meryl Streep", "Reese Witherspoon"] lb = Listbox(self, selectmode="multiple") 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()
class MiniWindow: def __init__(self,root,list): self.list = list self.mini = Toplevel(root) self.mini.wm_title("Matches") print (root.winfo_screenwidth()) self.mini.geometry("%dx%d+%d+%d" %(500,200,root.winfo_x()+root.winfo_width(),root.winfo_y())) self.filelist = Listbox(self.mini) for item in self.list: self.filelist.insert('end',str(item)) self.filelist.bind("<<ListboxSelect>>",self.onClick) self.filelist.pack(fill="both") def onClick(self,event): print(self.filelist.curselection()) index = int(self.filelist.curselection()[0]) link = self.list[index] filedir = os.path.dirname(link) if os.name == 'nt': os.startfile(filedir) elif os.name == 'posix': subprocess.Popen(["xdg-open",filedir])
class GUI(Frame): # pylint: disable=too-many-ancestors """class for GUI""" static_logger = logging.getLogger(__name__) static_queue = queue.Queue() def __init__(self, parent, db, pab, alg): """init""" Frame.__init__(self, parent) self.right_list = Listbox(parent) self.left_list = Listbox(parent) self.parent = parent self.db_creator = db self.path_and_bag = pab self.alg_do = alg self.menu_bar = Menu(self.parent) self.init_ui() def init_ui(self): """getting all things started""" self.parent.title("PyMeno") self.left_list.bind("<Double-Button-1>", self.on_double_click) self.parent.config(menu=self.menu_bar) file_menu = Menu(self.menu_bar, tearoff=False) menu2_parse = Menu(self.menu_bar, tearoff=False) # menu3_parse = Menu(menu_bar, tearoff=False) # sub_menu = Menu(file_menu, tearoff=False) self.left_list.pack(side=LEFT, fill=BOTH, expand=2) self.right_list.pack(side=RIGHT, fill=BOTH, expand=2) # add something to menu file_menu.add_command(label="Choose folder with music ALG 1", underline=0, command=self.new_thread_2) file_menu.add_command(label="Choose folder with music ALG 2", underline=0, command=self.new_thread_1) file_menu.add_command(label="Choose folder with music ALG 3", underline=0, command=self.new_thread_2) file_menu.add_command(label="Exit", underline=0, command=self.on_exit) menu2_parse.add_command(label="Download artists list", underline=0, command=self.db_creator.download_list_of_artists) menu2_parse.\ add_command(label="Parse artists information to database", underline=0, command=self.go_to_lilis_parsing) self.menu_bar.add_cascade(label="File", underline=0, menu=file_menu) self.menu_bar.add_cascade(label="Data", underline=0, menu=menu2_parse) def on_exit(self): """quit""" GUI.static_queue.put("endino-tarantino") self.quit() def disable_menu(self): """disable menu while program is working""" self.menu_bar.entryconfig("File", state="disabled") self.menu_bar.entryconfig("Data", state="disabled") def enable_menu(self): """enable menu after work""" self.menu_bar.entryconfig("File", state="normal") self.menu_bar.entryconfig("Data", state="normal") def new_thread_1(self): """thread for the first algorythm""" dir_name = filedialog.askdirectory(parent=self, initialdir="/", title='Please select a directory') if dir_name != "": self.disable_menu() self.path_and_bag.check_if_refresh(dir_name) self.config(cursor="wait") self.update() self.clean_queue() GUI.static_queue.put("Finding files in chosen folder:\n\n") num_files = len([val for sub_list in [[os.path.join(i[0], j)for j in i[2]] for i in os.walk(dir_name)] for val in sub_list]) rott = tk.Tk() app = App(rott, GUI.static_queue, num_files) rott.protocol("WM_DELETE_WINDOW", app.on_closing) thread = threading.Thread(target=self.open_menu, args=(dir_name,)) thread.setDaemon(True) thread.start() app.mainloop() else: print("Action aborted") def open_menu(self, dir_name): """select directory with music, alg 1""" list_of_songs = [] self.path_and_bag.clear_bag_of_words() for data in os.walk(dir_name): for filename in data[2]: list_of_songs = self.path_and_bag.change_title(os.path.join(data[0], filename)) GUI.static_queue.put(filename) if not list_of_songs: print("action aborted") else: GUI.static_queue.put("\nAnd what we have here?:\n") self.config(cursor="") shared_items_add = self.alg_do.search_for_simmilar_ver_2(False, GUI.static_queue) if not shared_items_add: shared_items_add = self.alg_do.search_for_simmilar_ver_2(True, GUI.static_queue) if shared_items_add: self.left_list.delete(0, END) self.right_list.delete(0, END) for song in list_of_songs: temp = song.split(',', 1) self.insert_to_right_list_box(temp[0], temp[1]) for key, value in shared_items_add.items(): temp = key.split(',', 1) GUI.static_queue.put(temp[0] + " : " + value) self.insert_to_left_list_box(temp[0] + " : " + value) GUI.static_queue.put("endino-tarantino") self.enable_menu() def new_thread_2(self): """thread for the second algorythm""" dir_name = filedialog.askdirectory(parent=self, initialdir="/", title='Please select a directory') if dir_name != "": self.disable_menu() self.path_and_bag.check_if_refresh(dir_name) self.config(cursor="wait") self.update() self.clean_queue() GUI.static_queue.put("Finding files in chosen folder:\n\n") num_files = len([val for sub_list in [[os.path.join(i[0], j)for j in i[2]] for i in os.walk(dir_name)] for val in sub_list]) rott = tk.Tk() app = App(rott, GUI.static_queue, num_files) rott.protocol("WM_DELETE_WINDOW", app.on_closing) thread = threading.Thread(target=self.open_menu_ver_2, args=(dir_name,)) thread.setDaemon(True) thread.start() app.mainloop() else: print("Action aborted") @staticmethod def clean_queue(): """cleaning queue if user exit manualy""" if not GUI.static_queue.empty(): while not GUI.static_queue.empty(): GUI.static_queue.get() def open_menu_ver_2(self, dir_name): """select directory with music, alg 2""" list_of_songs = [] self.path_and_bag.clear_bag_of_words() for data in os.walk(dir_name): for filename in data[2]: list_of_songs = self.path_and_bag.change_title(os.path.join(data[0], filename)) GUI.static_queue.put(filename) if not list_of_songs: print("action aborted") else: GUI.static_queue.put("\nAnd what we have here?:\n") self.config(cursor="") shared_items_add = self.alg_do.search_for_simmilar_ver_1(False, GUI.static_queue) if not shared_items_add: shared_items_add = self.alg_do.search_for_simmilar_ver_1(True, GUI.static_queue) if shared_items_add: self.left_list.delete(0, END) self.right_list.delete(0, END) for song in list_of_songs: temp = song.split(',', 1) self.insert_to_right_list_box(temp[0], temp[1]) for key, value in shared_items_add.items(): temp = key.split(',', 1) self.insert_to_left_list_box(temp[0] + " : " + value) GUI.static_queue.put("endino-tarantino") self.enable_menu() def new_thread_3(self): """thread for the third algorythm""" dir_name = filedialog.askdirectory(parent=self, initialdir="/", title='Please select a directory') if dir_name != "": self.disable_menu() self.path_and_bag.check_if_refresh(dir_name) self.config(cursor="wait") self.update() self.clean_queue() GUI.static_queue.put("Finding files in chosen folder:\n\n") num_files = len([val for sub_list in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk(dir_name)] for val in sub_list]) rott = tk.Tk() app = App(rott, GUI.static_queue, num_files) rott.protocol("WM_DELETE_WINDOW", app.on_closing) thread = threading.Thread(target=self.open_menu_ver_3, args=(dir_name,)) thread.setDaemon(True) thread.start() app.mainloop() else: print("Action aborted") def open_menu_ver_3(self, dir_name): """select directory with music, alg 3""" list_of_songs = [] self.path_and_bag.clear_bag_of_words() for data in os.walk(dir_name): for filename in data[2]: list_of_songs = self.path_and_bag.change_title(os.path.join(data[0], filename)) GUI.static_queue.put(filename) print(list_of_songs) if not list_of_songs: print("action aborted") else: GUI.static_queue.put("\nAnd what we have here?:\n") self.config(cursor="") shared_items_add = self.alg_do.search_for_simmilar_ver_3(False, GUI.static_queue) if not shared_items_add: shared_items_add = self.alg_do.search_for_simmilar_ver_3(True, GUI.static_queue) if shared_items_add: self.left_list.delete(0, END) self.right_list.delete(0, END) for song in list_of_songs: temp = song.split(',', 1) self.insert_to_right_list_box(temp[0], temp[1]) for key, value in shared_items_add.items(): temp = key.split(',', 1) self.insert_to_left_list_box(temp[0] + " : " + value) GUI.static_queue.put("endino-tarantino") self.enable_menu() def insert_to_right_list_box(self, artist, song): """insert to right listbox for other methods""" self.right_list.insert(END, artist + " - " + song) def insert_to_left_list_box(self, artist): """insert to left listbox for other methods""" self.left_list.insert(END, artist) def go_to_lilis_parsing(self): """how many artist do you want to parse""" number_from = simpledialog.askstring('Number', 'How many artists?/FROM') if number_from is not None: number_from = int(number_from) print(number_from) number_to = int(simpledialog.askstring('Number', 'How many artists?/TO')) if number_to is not None: number_to = int(number_to) print(number_to) self.db_creator.parse_file(number_to, number_from) def on_double_click(self, event): """open youtube on double click""" new = 2 # open in a new tab, if possible widget = event.widget selection = widget.curselection() value = widget.get(selection[0]) url = self.youtube_search(value) webbrowser.open(url, new=new) @staticmethod def youtube_search(to_search): """ This function finds url to our songs throw Youtube API """ developer_key = "AIzaSyCn9Pk4vWC8LjjIKqol5gkku20DI0IRurU" youtube_api_service_name = "youtube" youtube_api_version = "v3" parse = argparse.ArgumentParser() parse.add_argument("--q", help="Search term", default=to_search) parse.add_argument("--max-results", help="Max results", default=25) args = parse.parse_args() youtube = build(youtube_api_service_name, youtube_api_version, developerKey=developer_key) # Call the search.list method to retrieve results matching the specified # query term. search_response = youtube.search().list(q=args.q, # pylint: disable=no-member part="id,snippet", maxResults=args.max_results, order="viewCount").execute() videos = [] channels = [] play_lists = [] # Add each result to the appropriate list, and then display the lists of # matching videos, channels, and play lists. for search_result in search_response.get("items", []): if search_result["id"]["kind"] == "youtube#video": videos.append(search_result["id"]["videoId"]) elif search_result["id"]["kind"] == "youtube#channel": channels.append("%s (%s)" % (search_result["snippet"]["title"], search_result["id"]["channelId"])) elif search_result["id"]["kind"] == "youtube#playlist": play_lists.append("%s (%s)" % (search_result["snippet"]["title"], search_result["id"]["playlistId"])) try: return "https://www.youtube.com/watch?v=" + videos[0] except (UnicodeEncodeError, IndexError): GUI.static_logger.error('ERROR', exc_info=True) return "https://www.youtube.com/watch?v=" + "_NXrTujMP50"
class LogUI(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.filemodels = [] filemodel1 = FileModel("C:/Users/chen_xi/test1.csv", searchconds=[], relation="and", joincondtuples=[]) filemodel2 = FileModel("C:/Users/chen_xi/test2.csv", searchconds=[], relation="and", joincondtuples=[]) self.filemodels = [filemodel1, filemodel2] self._initUI() self.selectedfileindex = -1 def _initUI(self): self.parent.title("Log Processor") self.pack() self._initfilepanel() self._initsearchcondpanel() self._initjoincondpanel() self._initconsole() self._inflatefilelist() def _initfilepanel(self): frame = Frame(self) frame.grid(row=0, column=0, sticky=E + W + S + N) label = Label(frame, text="File List: ") label.grid(sticky=N + W) self.filelist = Listbox(frame, width=40) self.filelist.grid(row=1, column=0, rowspan=2, columnspan=3) vsl = Scrollbar(frame, orient=VERTICAL) vsl.grid(row=1, column=3, rowspan=2, sticky=N + S + W) hsl = Scrollbar(frame, orient=HORIZONTAL) hsl.grid(row=3, column=0, columnspan=3, sticky=W + E + N) self.filelist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set) self.filelist.bind('<<ListboxSelect>>', self._onfilelistselection) hsl.config(command=self.filelist.xview) vsl.config(command=self.filelist.yview) upbtn = Button(frame, text="Up", width=7, command=self._upfile) upbtn.grid(row=1, column=4, padx=5, pady=5) downbtn = Button(frame, text="Down", width=7, command=self._downfile) downbtn.grid(row=2, column=4, padx=5, pady=5) newbtn = Button(frame, text="New", width=7, command=self._addfile) newbtn.grid(row=4, column=1, pady=5, sticky=E + S) delbtn = Button(frame, text="Delete", width=7, command=self._deletefile) delbtn.grid(row=4, column=2, padx=5, pady=5, sticky=W + S) def _inflatefilelist(self): self.filelist.delete(0, END) for filemodel in self.filemodels: self.filelist.insert(END, filemodel.filename) def _initsearchcondpanel(self): frame = Frame(self) frame.grid(row=0, column=1, sticky=E + W + S + N, padx=5) label = Label(frame, text="Search Condition: ") label.grid(row=0, column=0, columnspan=1, sticky=W) relationlable = Label(frame, text="Relation") relationlable.grid(row=0, column=1, columnspan=1, sticky=E) self.condrelationvar = StringVar(frame) relationinput = Combobox(frame, textvariable=self.condrelationvar, values=["and", "or"]) relationinput.grid(row=0, column=2, padx=5, sticky=E) relationinput.bind('<<ComboboxSelected>>', self._onrelationchange) self.searchcondlist = Listbox(frame) self.searchcondlist.grid(row=1, rowspan=1, columnspan=3, sticky=E + W + S + N) vsl = Scrollbar(frame, orient=VERTICAL) vsl.grid(row=1, column=3, rowspan=1, sticky=N + S + W) hsl = Scrollbar(frame, orient=HORIZONTAL) hsl.grid(row=2, column=0, columnspan=3, sticky=W + E + N) self.searchcondlist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set) hsl.config(command=self.searchcondlist.xview) vsl.config(command=self.searchcondlist.yview) newbtn = Button(frame, text="New", width=7, command=self._addsearchcondition) newbtn.grid(row=3, column=0, padx=5, pady=5, sticky=E) delbtn = Button(frame, text="Delete", width=7, command=self._deletesearchcondition) delbtn.grid(row=3, column=1, sticky=E) modbtn = Button(frame, text="Update", width=7, command=self._modifysearchcondition) modbtn.grid(row=3, column=2, padx=5, pady=5, sticky=W) def _onrelationchange(self, evt): selectedmodel = self._getselectedfile() selectedmodel.relation = self.condrelationvar.get() def _inflatesearchcondlist(self, filemodel): self.condrelationvar.set(filemodel.relation) conds = filemodel.searchconds self.searchcondlist.delete(0, END) for cond in conds: self.searchcondlist.insert(END, cond.tostring()) def _initjoincondpanel(self): frame = Frame(self) frame.grid(row=0, column=2, sticky=E + W + S + N, padx=5) label = Label(frame, text="Join Condition: ") label.grid(sticky=N + W) self.joincondlist = Listbox(frame) self.joincondlist.grid(row=1, rowspan=1, columnspan=3, sticky=E + W + S + N) vsl = Scrollbar(frame, orient=VERTICAL) vsl.grid(row=1, column=3, rowspan=1, sticky=N + S + W) hsl = Scrollbar(frame, orient=HORIZONTAL) hsl.grid(row=2, column=0, columnspan=3, sticky=W + E + N) self.joincondlist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set) hsl.config(command=self.joincondlist.xview) vsl.config(command=self.joincondlist.yview) newbtn = Button(frame, text="New", width=7, command=self._addjoincondition) newbtn.grid(row=3, column=0, padx=5, pady=5, sticky=E) delbtn = Button(frame, text="Delete", width=7, command=self._deletejoincondition) delbtn.grid(row=3, column=1, sticky=E) modbtn = Button(frame, text="Update", width=7, command=self._modifyjoincondition) modbtn.grid(row=3, column=2, padx=5, pady=5, sticky=W) def _inflatejoincondlist(self, condtuples): self.joincondlist.delete(0, END) for condtuple in condtuples: cond = condtuple[0] tofilename = condtuple[1] self.joincondlist.insert(END, cond.tostring() + " in " + tofilename) def _initconsole(self): separator = Separator(self, orient=HORIZONTAL) separator.grid(row=1, columnspan=3, sticky=W + E, padx=5, pady=5) self.console = Text(self) self.console.grid(row=2, columnspan=3, sticky=W + E, padx=5, pady=5) vsl = Scrollbar(self, orient=VERTICAL) vsl.grid(row=2, column=3, sticky=N + S + W) hsl = Scrollbar(self, orient=HORIZONTAL) hsl.grid(row=3, column=0, columnspan=3, sticky=W + E + N) hsl.config(command=self.console.xview) vsl.config(command=self.console.yview) resbtn = Button(self, text="Search", width=7, comman=self._showsearchresult) resbtn.grid(row=4, column=2, padx=5, pady=5, sticky=E) def _showsearchresult(self): try: res = self._searchresult() formatres = self._formatsearchresult(res) except Exception: formatres = "Error!\r\n" + traceback.format_exc() self.console.delete("0.0", END) self.console.insert("0.0", formatres) def _searchresult(self): filesearchs = [] joinsearchs = [] for filemodel in self.filemodels: filename = filemodel.filename singlesearch = SingleFileSearch(filename, DictReader(open(filename)), filemodel.searchconds, filemodel.relation) filesearchs.append(singlesearch) joindict = {} for joincondtuple in filemodel.joincondtuples: tofilename = joincondtuple[1] joincond = joincondtuple[0] if tofilename not in joindict: joindict[tofilename] = [] joindict[tofilename].append(joincond) for tofilename in joindict: joinsearch = JoinFileSearch(filename, DictReader(open(filename)), tofilename, DictReader(open(tofilename)), joindict[tofilename]) joinsearchs.append(joinsearch) search = Search(filesearchs, joinsearchs) return search.process() def _formatsearchresult(self, searchresult): formatres = self._formatsummary(searchresult) + "\r\n" fileresults = searchresult.results for filemodel in self.filemodels: filename = filemodel.filename fileresult = fileresults[filename] formatres += self._formatfileresult(fileresult) formatres += "\r\n" return formatres def _formatsummary(self, searchresult): res = "Summary\r\n" res += "Time Cost: " + str(searchresult.timecost) + " Seconds\r\n" fileresults = searchresult.results for filemodel in self.filemodels: filename = filemodel.filename fileresult = fileresults[filename] res += filename + " Size: " + str(len(fileresult.result)) + "\r\n" return res def _formatfileresult(self, fileresult): res = "" filename = fileresult.filename res += filename + " Size: " + str(len(fileresult.result)) + "\r\n" fields = csvhandler.getfields(filename) for (i, field) in enumerate(fields): res += field if i < (len(fields) - 1): res += "," else: res += "\r\n" for rowdict in fileresult.result: for (i, field) in enumerate(fields): res += rowdict[field] if i < (len(fields) - 1): res += "," else: res += "\r\n" return res def _addfile(self): filetypes = [('csv files', '*.csv'), ('All files', '*')] selectedfile = askopenfilename(filetypes=filetypes) if selectedfile is not None: newmodel = FileModel(selectedfile, searchconds=[], relation="and", joincondtuples=[]) self.filemodels.append(newmodel) self.filelist.insert(END, newmodel.filename) self._setselectedfileindex(len(self.filemodels) - 1) def _deletefile(self): index = self._getselectedfileindex() if index >= 0: self.filelist.delete(index) del self.filemodels[index] self._setselectedfileindex(-1) def _upfile(self): if self._getselectedfileindex() <= 0: return index = self._getselectedfileindex() selectedfilename = self._getselectedfile().filename if index > 0: self.filelist.insert((index - 1), selectedfilename) self.filelist.delete(index + 1) self.filemodels[index - 1], self.filemodels[index] = self.filemodels[index], self.filemodels[index - 1] self._setselectedfileindex(index - 1) def _downfile(self): if self._getselectedfileindex() < 0: return index = self._getselectedfileindex() selectedfilename = self._getselectedfile().filename if index < (len(self.filemodels) - 1): self.filelist.insert((index + 2), selectedfilename) self.filelist.delete(index) self.filemodels[index], self.filemodels[index + 1] = self.filemodels[index + 1], self.filemodels[index] self._setselectedfileindex(index + 1) def _onfilelistselection(self, evt): if len(self.filelist.curselection()) == 0: return self._setselectedfileindex(self.filelist.curselection()[0]) selectedfile = self._getselectedfile() self._inflatesearchcondlist(selectedfile) joincondtuples = selectedfile.joincondtuples self._inflatejoincondlist(joincondtuples) def _addsearchcondition(self): if self._getselectedfileindex() < 0: return self._popupsearchcondwindow() def _deletesearchcondition(self): index = self._getselectedsearchcondindex() if index < 0: return selectedfile = self._getselectedfile() del selectedfile.searchconds[index] self.searchcondlist.delete(index) def _modifysearchcondition(self): if self._getselectedsearchcondindex() < 0: return self._popupsearchcondwindow(self._getselectedsearchcondindex()) def _addjoincondition(self): if self._getselectedfileindex() < 0: return self._popupjoincondwindow() def _deletejoincondition(self): index = self._getselectedjoincondindex() if index < 0: return selectedfile = self._getselectedfile() del selectedfile.joincondtuples[index] self.joincondlist.delete(index) def _modifyjoincondition(self): if self._getselectedjoincondindex() < 0: return self._popupjoincondwindow(self._getselectedjoincondindex()) def _popupsearchcondwindow(self, index=-1): if index < 0: cond = ValueSearchCondition("", "") else: cond = self._getselectedfile().searchconds[index] window = Toplevel(self) title = Label(window, text="New Search Condition") title.grid(row=0, column=0, padx=5, pady=5, sticky=W + N) fieldlabel = Label(window, text="Field Name: ") fieldlabel.grid(row=1, column=0, padx=5, pady=5, sticky=W) fields = csvhandler.getfields(self._getselectedfile().filename) fieldvar = StringVar(window) fieldinput = Combobox(window, textvariable=fieldvar, values=fields, width=20) fieldinput.grid(row=1, column=1, columnspan=2, padx=5, pady=5, sticky=W) valuelabel = Label(window, text="Value: ") valuelabel.grid(row=3, column=0, padx=5, pady=5, sticky=W) valueinput = Entry(window) valueinput.grid(row=3, column=1, columnspan=2, padx=5, pady=5, sticky=W) minlabel = Label(window, text="Min Value: ") minlabel.grid(row=4, column=0, padx=5, pady=5, sticky=W) mininput = Entry(window) mininput.grid(row=4, column=1, columnspan=2, padx=5, pady=5, sticky=W) maxlabel = Label(window, text="Max Value: ") maxlabel.grid(row=5, column=0, padx=5, pady=5, sticky=W) maxinput = Entry(window) maxinput.grid(row=5, column=1, columnspan=2, padx=5, pady=5, sticky=W) sarchkind = IntVar() def _enablesingle(): valueinput.config(state=NORMAL) mininput.config(state=DISABLED) maxinput.config(state=DISABLED) singlebutton.select() def _enablejoin(): valueinput.config(state=DISABLED) mininput.config(state=NORMAL) maxinput.config(state=NORMAL) joinbutton.select() typelabel = Label(window, text="Search Type: ") typelabel.grid(row=2, column=0, padx=5, pady=5, sticky=W) singlebutton = Radiobutton(window, text="Single", variable=sarchkind, value=1, command=_enablesingle) singlebutton.grid(row=2, column=1, columnspan=1, padx=5, pady=5, sticky=W) joinbutton = Radiobutton(window, text="Range", variable=sarchkind, value=2, command=_enablejoin) joinbutton.grid(row=2, column=2, columnspan=1, padx=5, pady=5, sticky=W) # init value fieldvar.set(cond.field) if isinstance(cond, ValueSearchCondition): valueinput.insert(0, cond.val) _enablesingle() elif isinstance(cond, RangeSearchCondition): mininput.insert(0, cond.valmin) maxinput.insert(0, cond.valmax) _enablejoin() def _newcond(): '''create new condition ''' if sarchkind.get() == 1: cond = ValueSearchCondition(fieldvar.get(), valueinput.get()) else: cond = RangeSearchCondition(fieldvar.get(), mininput.get(), maxinput.get()) selectedfile = self._getselectedfile() if index < 0: selectedfile.searchconds.append(cond) else: del selectedfile.searchconds[index] selectedfile.searchconds[index:index] = [cond] self._inflatesearchcondlist(selectedfile) window.destroy() okbtn = Button(window, text="Confirm", width=7, command=_newcond) okbtn.grid(row=6, column=1, rowspan=1, columnspan=1, sticky=E, padx=5, pady=5) clsbtn = Button(window, text="Close", width=7, command=lambda: window.destroy()) clsbtn.grid(row=6, column=2, rowspan=1, columnspan=1, sticky=E, padx=5, pady=5) def _popupjoincondwindow(self, index=-1): if index < 0: cond = JoinSearchCondition(("", "")) tofilename = "" else: condtuple = self._getselectedfile().joincondtuples[index] cond = condtuple[0] tofilename = condtuple[1] window = Toplevel(self) title = Label(window, text="New Search Condition") title.grid(row=0, column=0, padx=5, pady=5, sticky=W + N) filenamelabel = Label(window, text="Target Field Name: ") filenamelabel.grid(row=1, column=0, padx=5, pady=5, sticky=W) filevar = StringVar(window) filenameinput = Combobox(window, textvariable=filevar, values=self.filelist.get(0, END), width=30) filenameinput.grid(row=1, column=1, columnspan=2, padx=5, pady=5, sticky=W) fromfieldlabel = Label(window, text="Field in From File: ") fromfieldlabel.grid(row=3, column=0, padx=5, pady=5, sticky=W) fromfields = csvhandler.getfields(self._getselectedfile().filename) fromfieldvar = StringVar(window) fieldinput = Combobox(window, textvariable=fromfieldvar, values=fromfields, width=20) fieldinput.grid(row=3, column=1, columnspan=2, padx=5, pady=5, sticky=W) tofieldlabel = Label(window, text="Field in Target File: ") tofieldlabel.grid(row=4, column=0, padx=5, pady=5, sticky=W) tofields = [] tofieldvar = StringVar(window) tofieldinput = Combobox(window, textvariable=tofieldvar, values=tofields, width=20) tofieldinput.grid(row=4, column=1, columnspan=2, padx=5, pady=5, sticky=W) def updatetofieldinput(evt): if filevar.get() is not None and len(filevar.get()) > 0: tofields = csvhandler.getfields(filevar.get()) window.grid_slaves(4, 1)[0].grid_forget() tofieldinput = Combobox(window, textvariable=tofieldvar, values=tofields, width=20) tofieldinput.grid(row=4, column=1, columnspan=2, padx=5, pady=5, sticky=W) filenameinput.bind('<<ComboboxSelected>>', updatetofieldinput) # init value filevar.set(tofilename) fromfieldvar.set(cond.fieldtuple[0]) updatetofieldinput(None) tofieldvar.set(cond.fieldtuple[1]) def _newcond(): '''create new condition ''' cond = JoinSearchCondition((fromfieldvar.get(), tofieldvar.get())) tofilename = filevar.get() selectedfile = self._getselectedfile() if index < 0: selectedfile.joincondtuples.append((cond, tofilename)) else: del selectedfile.joincondtuples[index] selectedfile.joincondtuples[index:index] = [(cond, tofilename)] self._inflatejoincondlist(selectedfile.joincondtuples) window.destroy() okbtn = Button(window, text="Confirm", width=7, command=_newcond) okbtn.grid(row=6, column=1, rowspan=1, columnspan=1, sticky=E, padx=5, pady=5) clsbtn = Button(window, text="Close", width=7, command=lambda: window.destroy()) clsbtn.grid(row=6, column=2, rowspan=1, columnspan=1, sticky=W, padx=5, pady=5) def _getselectedfile(self): if self._getselectedfileindex() < 0: return None return self.filemodels[self._getselectedfileindex()] def _getselectedfileindex(self): return self.selectedfileindex def _setselectedfileindex(self, index): self.selectedfileindex = index if index >= 0: self.filelist.selection_set(index) def _getselectedsearchcondindex(self): if len(self.searchcondlist.curselection()) > 0: return self.searchcondlist.curselection()[0] return -1 def _getselectedjoincondindex(self): if len(self.joincondlist.curselection()) > 0: return self.joincondlist.curselection()[0] return -1
class GetKeysDialog(Toplevel): # Dialog title for invalid key sequence keyerror_title = 'Key Sequence Error' def __init__(self, parent, title, action, current_key_sequences, *, _htest=False, _utest=False): """ parent - parent of this dialog title - string which is the title of the popup dialog action - string, the name of the virtual event these keys will be mapped to current_key_sequences - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest _utest - bool, do not wait when running unittest """ Toplevel.__init__(self, parent) self.withdraw() # Hide while setting geometry. self.configure(borderwidth=5) self.resizable(height=False, width=False) self.title(title) self.transient(parent) self.grab_set() self.protocol("WM_DELETE_WINDOW", self.cancel) self.parent = parent self.action = action self.current_key_sequences = current_key_sequences self.result = '' self.key_string = StringVar(self) self.key_string.set('') # Set self.modifiers, self.modifier_label. self.set_modifiers_for_platform() self.modifier_vars = [] for modifier in self.modifiers: variable = StringVar(self) variable.set('') self.modifier_vars.append(variable) self.advanced = False self.create_widgets() self.update_idletasks() self.geometry( "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width()/2 - self.winfo_reqwidth()/2), parent.winfo_rooty() + ((parent.winfo_height()/2 - self.winfo_reqheight()/2) if not _htest else 150) ) ) # Center dialog over parent (or below htest box). if not _utest: self.deiconify() # Geometry set, unhide. self.wait_window() def showerror(self, *args, **kwargs): # Make testing easier. Replace in #30751. messagebox.showerror(*args, **kwargs) def create_widgets(self): self.frame = frame = Frame(self, borderwidth=2, relief='sunken') frame.pack(side='top', expand=True, fill='both') frame_buttons = Frame(self) frame_buttons.pack(side='bottom', fill='x') self.button_ok = Button(frame_buttons, text='OK', width=8, command=self.ok) self.button_ok.grid(row=0, column=0, padx=5, pady=5) self.button_cancel = Button(frame_buttons, text='Cancel', width=8, command=self.cancel) self.button_cancel.grid(row=0, column=1, padx=5, pady=5) # Basic entry key sequence. self.frame_keyseq_basic = Frame(frame, name='keyseq_basic') self.frame_keyseq_basic.grid(row=0, column=0, sticky='nsew', padx=5, pady=5) basic_title = Label(self.frame_keyseq_basic, text=f"New keys for '{self.action}' :") basic_title.pack(anchor='w') basic_keys = Label(self.frame_keyseq_basic, justify='left', textvariable=self.key_string, relief='groove', borderwidth=2) basic_keys.pack(ipadx=5, ipady=5, fill='x') # Basic entry controls. self.frame_controls_basic = Frame(frame) self.frame_controls_basic.grid(row=1, column=0, sticky='nsew', padx=5) # Basic entry modifiers. self.modifier_checkbuttons = {} column = 0 for modifier, variable in zip(self.modifiers, self.modifier_vars): label = self.modifier_label.get(modifier, modifier) check = Checkbutton(self.frame_controls_basic, command=self.build_key_string, text=label, variable=variable, onvalue=modifier, offvalue='') check.grid(row=0, column=column, padx=2, sticky='w') self.modifier_checkbuttons[modifier] = check column += 1 # Basic entry help text. help_basic = Label(self.frame_controls_basic, justify='left', text="Select the desired modifier keys\n"+ "above, and the final key from the\n"+ "list on the right.\n\n" + "Use upper case Symbols when using\n" + "the Shift modifier. (Letters will be\n" + "converted automatically.)") help_basic.grid(row=1, column=0, columnspan=4, padx=2, sticky='w') # Basic entry key list. self.list_keys_final = Listbox(self.frame_controls_basic, width=15, height=10, selectmode='single') self.list_keys_final.insert('end', *AVAILABLE_KEYS) self.list_keys_final.bind('<ButtonRelease-1>', self.final_key_selected) self.list_keys_final.grid(row=0, column=4, rowspan=4, sticky='ns') scroll_keys_final = Scrollbar(self.frame_controls_basic, orient='vertical', command=self.list_keys_final.yview) self.list_keys_final.config(yscrollcommand=scroll_keys_final.set) scroll_keys_final.grid(row=0, column=5, rowspan=4, sticky='ns') self.button_clear = Button(self.frame_controls_basic, text='Clear Keys', command=self.clear_key_seq) self.button_clear.grid(row=2, column=0, columnspan=4) # Advanced entry key sequence. self.frame_keyseq_advanced = Frame(frame, name='keyseq_advanced') self.frame_keyseq_advanced.grid(row=0, column=0, sticky='nsew', padx=5, pady=5) advanced_title = Label(self.frame_keyseq_advanced, justify='left', text=f"Enter new binding(s) for '{self.action}' :\n" + "(These bindings will not be checked for validity!)") advanced_title.pack(anchor='w') self.advanced_keys = Entry(self.frame_keyseq_advanced, textvariable=self.key_string) self.advanced_keys.pack(fill='x') # Advanced entry help text. self.frame_help_advanced = Frame(frame) self.frame_help_advanced.grid(row=1, column=0, sticky='nsew', padx=5) help_advanced = Label(self.frame_help_advanced, justify='left', text="Key bindings are specified using Tkinter keysyms as\n"+ "in these samples: <Control-f>, <Shift-F2>, <F12>,\n" "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n" "Upper case is used when the Shift modifier is present!\n\n" + "'Emacs style' multi-keystroke bindings are specified as\n" + "follows: <Control-x><Control-y>, where the first key\n" + "is the 'do-nothing' keybinding.\n\n" + "Multiple separate bindings for one action should be\n"+ "separated by a space, eg., <Alt-v> <Meta-v>." ) help_advanced.grid(row=0, column=0, sticky='nsew') # Switch between basic and advanced. self.button_level = Button(frame, command=self.toggle_level, text='<< Basic Key Binding Entry') self.button_level.grid(row=2, column=0, stick='ew', padx=5, pady=5) self.toggle_level() def set_modifiers_for_platform(self): """Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn't matter if the keyboard has these keys; it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering. """ if sys.platform == "darwin": self.modifiers = ['Shift', 'Control', 'Option', 'Command'] else: self.modifiers = ['Control', 'Alt', 'Shift'] self.modifier_label = {'Control': 'Ctrl'} # Short name. def toggle_level(self): "Toggle between basic and advanced keys." if self.button_level.cget('text').startswith('Advanced'): self.clear_key_seq() self.button_level.config(text='<< Basic Key Binding Entry') self.frame_keyseq_advanced.lift() self.frame_help_advanced.lift() self.advanced_keys.focus_set() self.advanced = True else: self.clear_key_seq() self.button_level.config(text='Advanced Key Binding Entry >>') self.frame_keyseq_basic.lift() self.frame_controls_basic.lift() self.advanced = False def final_key_selected(self, event=None): "Handler for clicking on key in basic settings list." self.build_key_string() def build_key_string(self): "Create formatted string of modifiers plus the key." keylist = modifiers = self.get_modifiers() final_key = self.list_keys_final.get('anchor') if final_key: final_key = translate_key(final_key, modifiers) keylist.append(final_key) self.key_string.set(f"<{'-'.join(keylist)}>") def get_modifiers(self): "Return ordered list of modifiers that have been selected." mod_list = [variable.get() for variable in self.modifier_vars] return [mod for mod in mod_list if mod] def clear_key_seq(self): "Clear modifiers and keys selection." self.list_keys_final.select_clear(0, 'end') self.list_keys_final.yview('moveto', '0.0') for variable in self.modifier_vars: variable.set('') self.key_string.set('') def ok(self, event=None): keys = self.key_string.get().strip() if not keys: self.showerror(title=self.keyerror_title, parent=self, message="No key specified.") return if (self.advanced or self.keys_ok(keys)) and self.bind_ok(keys): self.result = keys self.grab_release() self.destroy() def cancel(self, event=None): self.result = '' self.grab_release() self.destroy() def keys_ok(self, keys): """Validity check on user's 'basic' keybinding selection. Doesn't check the string produced by the advanced dialog because 'modifiers' isn't set. """ final_key = self.list_keys_final.get('anchor') modifiers = self.get_modifiers() title = self.keyerror_title key_sequences = [key for keylist in self.current_key_sequences for key in keylist] if not keys.endswith('>'): self.showerror(title, parent=self, message='Missing the final Key') elif (not modifiers and final_key not in FUNCTION_KEYS + MOVE_KEYS): self.showerror(title=title, parent=self, message='No modifier key(s) specified.') elif (modifiers == ['Shift']) \ and (final_key not in FUNCTION_KEYS + MOVE_KEYS + ('Tab', 'Space')): msg = 'The shift modifier by itself may not be used with'\ ' this key symbol.' self.showerror(title=title, parent=self, message=msg) elif keys in key_sequences: msg = 'This key combination is already in use.' self.showerror(title=title, parent=self, message=msg) else: return True return False def bind_ok(self, keys): "Return True if Tcl accepts the new keys else show message." try: binding = self.bind(keys, lambda: None) except TclError as err: self.showerror( title=self.keyerror_title, parent=self, message=(f'The entered key sequence is not accepted.\n\n' f'Error: {err}')) return False else: self.unbind(keys, binding) return True
class LucteriosMainForm(Tk): def __init__(self): Tk.__init__(self) try: img = Image("photo", file=join( dirname(import_module('lucterios.install').__file__), "lucterios.png")) self.tk.call('wm', 'iconphoto', self._w, img) except: pass self.has_checked = False self.title(ugettext("Lucterios installer")) self.minsize(475, 260) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.running_instance = {} self.resizable(True, True) self.protocol("WM_DELETE_WINDOW", self.on_closing) self.ntbk = ttk.Notebook(self) self.ntbk.grid(row=0, column=0, columnspan=1, sticky=(N, S, E, W)) self.create_instance_panel() self.create_module_panel() stl = ttk.Style() stl.theme_use("default") stl.configure("TProgressbar", thickness=5) self.progress = ttk.Progressbar( self, style="TProgressbar", orient='horizontal', mode='indeterminate') self.progress.grid(row=1, column=0, sticky=(E, W)) self.btnframe = Frame(self, bd=1) self.btnframe.grid(row=2, column=0, columnspan=1) Button(self.btnframe, text=ugettext("Refresh"), width=20, command=self.refresh).grid( row=0, column=0, padx=3, pady=3, sticky=(N, S)) self.btnupgrade = Button( self.btnframe, text=ugettext("Search upgrade"), width=20, command=self.upgrade) self.btnupgrade.config(state=DISABLED) self.btnupgrade.grid(row=0, column=1, padx=3, pady=3, sticky=(N, S)) Button(self.btnframe, text=ugettext("Close"), width=20, command=self.on_closing).grid( row=0, column=2, padx=3, pady=3, sticky=(N, S)) def on_closing(self): all_stop = True instance_names = list(self.running_instance.keys()) for old_item in instance_names: if (self.running_instance[old_item] is not None) and self.running_instance[old_item].is_running(): all_stop = False if all_stop or askokcancel(None, ugettext("An instance is always running.\nDo you want to close?")): self.destroy() else: self.refresh() def destroy(self): instance_names = list(self.running_instance.keys()) for old_item in instance_names: if self.running_instance[old_item] is not None: self.running_instance[old_item].stop() del self.running_instance[old_item] Tk.destroy(self) def create_instance_panel(self): frm_inst = Frame(self.ntbk) frm_inst.grid_columnconfigure(0, weight=1) frm_inst.grid_rowconfigure(0, weight=1) frm_inst.grid_columnconfigure(1, weight=3) frm_inst.grid_rowconfigure(1, weight=0) self.instance_list = Listbox(frm_inst, width=20) self.instance_list.bind('<<ListboxSelect>>', self.select_instance) self.instance_list.pack() self.instance_list.grid(row=0, column=0, sticky=(N, S, W, E)) self.instance_txt = Text(frm_inst, width=75) self.instance_txt.grid(row=0, column=1, rowspan=2, sticky=(N, S, W, E)) self.instance_txt.config(state=DISABLED) self.btninstframe = Frame(frm_inst, bd=1) self.btninstframe.grid(row=1, column=0, columnspan=1) self.btninstframe.grid_columnconfigure(0, weight=1) Button(self.btninstframe, text=ugettext("Launch"), width=25, command=self.open_inst).grid( row=0, column=0, columnspan=2, sticky=(N, S)) Button(self.btninstframe, text=ugettext("Modify"), width=10, command=self.modify_inst).grid(row=1, column=0, sticky=(N, S)) Button(self.btninstframe, text=ugettext("Delete"), width=10, command=self.delete_inst).grid(row=1, column=1, sticky=(N, S)) Button(self.btninstframe, text=ugettext("Save"), width=10, command=self.save_inst).grid(row=2, column=0, sticky=(N, S)) Button(self.btninstframe, text=ugettext("Restore"), width=10, command=self.restore_inst).grid(row=2, column=1, sticky=(N, S)) Button(self.btninstframe, text=ugettext("Add"), width=25, command=self.add_inst).grid( row=3, column=0, columnspan=2, sticky=(N, S)) self.ntbk.add(frm_inst, text=ugettext('Instances')) def create_module_panel(self): frm_mod = Frame(self.ntbk) frm_mod.grid_columnconfigure(0, weight=1) frm_mod.grid_rowconfigure(0, weight=1) self.module_txt = Text(frm_mod) self.module_txt.grid(row=0, column=0, sticky=(N, S, W, E)) self.module_txt.config(state=DISABLED) self.ntbk.add(frm_mod, text=ugettext('Modules')) def do_progress(self, progressing): if not progressing: self.progress.stop() self.progress.grid_remove() else: self.progress.start(25) self.progress.grid(row=1, column=0, sticky=(E, W)) def enabled(self, is_enabled, widget=None): if widget is None: widget = self self.do_progress(not is_enabled) if is_enabled: widget.config(cursor="") else: widget.config(cursor="watch") if isinstance(widget, Button) and (widget != self.btnupgrade): if is_enabled and (not hasattr(widget, 'disabled') or not widget.disabled): widget.config(state=NORMAL) else: widget.config(state=DISABLED) else: for child_cmp in widget.winfo_children(): self.enabled(is_enabled, child_cmp) @ThreadRun def refresh(self, instance_name=None): if instance_name is None: instance_name = self.get_selected_instance_name() self.instance_txt.delete("1.0", END) self._refresh_instance_list() self.set_select_instance_name(instance_name) if not self.has_checked: self._refresh_modules() if self.instance_list.size() == 0: sleep(.3) self._refresh_modules() sleep(.3) self.after_idle(self.add_inst) def _refresh_modules(self): self.btnupgrade.config(state=DISABLED) self.module_txt.config(state=NORMAL) self.module_txt.delete("1.0", END) lct_glob = LucteriosGlobal() mod_lucterios, mod_applis, mod_modules = lct_glob.installed() self.module_txt.insert( END, ugettext("Lucterios core\t\t%s\n") % mod_lucterios[1]) self.module_txt.insert(END, '\n') self.module_txt.insert(END, ugettext("Application\n")) for appli_item in mod_applis: self.module_txt.insert( END, "\t%s\t%s\n" % (appli_item[0].ljust(30), appli_item[1])) self.module_txt.insert(END, ugettext("Modules\n")) for module_item in mod_modules: self.module_txt.insert( END, "\t%s\t%s\n" % (module_item[0].ljust(30), module_item[1])) extra_urls = lct_glob.get_extra_urls() if len(extra_urls) > 0: self.module_txt.insert(END, "\n") self.module_txt.insert(END, ugettext("Pypi servers\n")) for extra_url in extra_urls: self.module_txt.insert(END, "\t%s\n" % extra_url) self.module_txt.config(state=DISABLED) self.has_checked = True self.after(1000, lambda: Thread(target=self.check).start()) def _refresh_instance_list(self): self.instance_list.delete(0, END) luct_glo = LucteriosGlobal() instance_list = luct_glo.listing() for item in instance_list: self.instance_list.insert(END, item) if item not in self.running_instance.keys(): self.running_instance[item] = None instance_names = list(self.running_instance.keys()) for old_item in instance_names: if old_item not in instance_list: if self.running_instance[old_item] is not None: self.running_instance[old_item].stop() del self.running_instance[old_item] def set_select_instance_name(self, instance_name): cur_sel = 0 for sel_iter in range(self.instance_list.size()): if self.instance_list.get(sel_iter) == instance_name: cur_sel = sel_iter break self.instance_list.selection_set(cur_sel) self.select_instance(None) def get_selected_instance_name(self): if len(self.instance_list.curselection()) > 0: return self.instance_list.get(int(self.instance_list.curselection()[0])) else: return "" def set_ugrade_state(self, must_upgrade): if must_upgrade: self.btnupgrade.config(state=NORMAL) self.btnupgrade["text"] = ugettext("Upgrade needs") else: self.btnupgrade["text"] = ugettext("No upgrade") self.btnupgrade.config(state=DISABLED) def check(self): must_upgrade = False try: lct_glob = LucteriosGlobal() _, must_upgrade = lct_glob.check() finally: self.after(300, self.set_ugrade_state, must_upgrade) @ThreadRun def upgrade(self): self.btnupgrade.config(state=DISABLED) self.instance_list.config(state=DISABLED) try: from logging import getLogger admin_path = import_module( "lucterios.install.lucterios_admin").__file__ proc = Popen( [sys.executable, admin_path, "update"], stderr=STDOUT, stdout=PIPE) value = proc.communicate()[0] try: value = value.decode('ascii') except: pass six.print_(value) if proc.returncode != 0: getLogger("lucterios.admin").error(value) else: getLogger("lucterios.admin").info(value) showinfo(ugettext("Lucterios installer"), ugettext( "The application must restart")) python = sys.executable os.execl(python, python, *sys.argv) finally: self._refresh_modules() self.btnupgrade.config(state=NORMAL) self.instance_list.config(state=NORMAL) @ThreadRun def select_instance(self, evt): if self.instance_list['state'] == NORMAL: self.instance_list.config(state=DISABLED) try: instance_name = self.get_selected_instance_name() self.instance_txt.configure(state=NORMAL) self.instance_txt.delete("1.0", END) if instance_name != '': if instance_name not in self.running_instance.keys(): self.running_instance[instance_name] = None inst = LucteriosInstance(instance_name) inst.read() self.instance_txt.insert(END, "\t\t\t%s\n\n" % inst.name) self.instance_txt.insert( END, ugettext("Database\t\t%s\n") % inst.get_database_txt()) self.instance_txt.insert( END, ugettext("Appli\t\t%s\n") % inst.get_appli_txt()) self.instance_txt.insert( END, ugettext("Modules\t\t%s\n") % inst.get_module_txt()) self.instance_txt.insert( END, ugettext("Extra\t\t%s\n") % inst.get_extra_txt()) self.instance_txt.insert(END, '\n') if self.running_instance[instance_name] is not None and self.running_instance[instance_name].is_running(): self.instance_txt.insert(END, ugettext( "=> Running in http://%(ip)s:%(port)d\n") % {'ip': self.running_instance[instance_name].lan_ip, 'port': self.running_instance[instance_name].port}) self.btninstframe.winfo_children()[0]["text"] = ugettext( "Stop") else: self.running_instance[instance_name] = None self.instance_txt.insert(END, ugettext("=> Stopped\n")) self.btninstframe.winfo_children()[0]["text"] = ugettext( "Launch") else: self.btninstframe.winfo_children()[0]["text"] = ugettext( "Launch") self.btninstframe.winfo_children()[0].disabled = ( instance_name == '') self.btninstframe.winfo_children()[1].disabled = ( instance_name == '') self.btninstframe.winfo_children()[2].disabled = ( instance_name == '') self.btninstframe.winfo_children()[3].disabled = ( instance_name == '') self.btninstframe.winfo_children()[4].disabled = ( instance_name == '') self.instance_txt.configure(state=DISABLED) finally: setup_from_none() self.instance_list.config(state=NORMAL) @ThreadRun def add_modif_inst_result(self, result, to_create): inst = LucteriosInstance(result[0]) inst.set_extra("LANGUAGE_CODE='%s'" % result[5]) inst.set_appli(result[1]) inst.set_module(result[2]) inst.set_database(result[4]) if to_create: inst.add() else: inst.modif() inst = LucteriosInstance(result[0]) inst.set_extra(result[3]) inst.security() self.refresh(result[0]) def add_inst(self): self.enabled(False) try: self.do_progress(False) ist_edt = InstanceEditor() ist_edt.execute() ist_edt.transient(self) self.wait_window(ist_edt) finally: self.enabled(True) if ist_edt.result is not None: self.add_modif_inst_result(ist_edt.result, True) def modify_inst(self): self.enabled(False) try: self.do_progress(False) ist_edt = InstanceEditor() ist_edt.execute(self.get_selected_instance_name()) ist_edt.transient(self) self.wait_window(ist_edt) finally: self.enabled(True) if ist_edt.result is not None: self.add_modif_inst_result(ist_edt.result, False) @ThreadRun def delete_inst_name(self, instance_name): inst = LucteriosInstance(instance_name) inst.delete() self.refresh() def delete_inst(self): setup_from_none() instance_name = self.get_selected_instance_name() if askokcancel(None, ugettext("Do you want to delete '%s'?") % instance_name): self.delete_inst_name(instance_name) else: self.refresh() @ThreadRun def open_inst(self): instance_name = self.get_selected_instance_name() if instance_name != '': try: if instance_name not in self.running_instance.keys(): self.running_instance[instance_name] = None if self.running_instance[instance_name] is None: port = FIRST_HTTP_PORT for inst_obj in self.running_instance.values(): if (inst_obj is not None) and (inst_obj.port >= port): port = inst_obj.port + 1 self.running_instance[instance_name] = RunServer( instance_name, port) self.running_instance[instance_name].start() else: self.running_instance[instance_name].stop() self.running_instance[instance_name] = None finally: self.set_select_instance_name(instance_name) @ThreadRun def save_instance(self, instance_name, file_name): inst = LucteriosInstance(instance_name) inst.filename = file_name if inst.archive(): showinfo(ugettext("Lucterios installer"), ugettext( "Instance saved to %s") % file_name) else: showerror( ugettext("Lucterios installer"), ugettext("Instance not saved!")) self.refresh(instance_name) def save_inst(self): instance_name = self.get_selected_instance_name() if instance_name != '': file_name = asksaveasfilename( parent=self, filetypes=[('lbk', '.lbk'), ('*', '.*')]) if file_name != '': self.save_instance(instance_name, file_name) @ThreadRun def restore_instance(self, instance_name, file_name): if file_name[-4:] == '.bkf': rest_inst = MigrateFromV1(instance_name, withlog=True) else: rest_inst = LucteriosInstance(instance_name) rest_inst.filename = file_name if rest_inst.restore(): showinfo(ugettext("Lucterios installer"), ugettext( "Instance restore from %s") % file_name) else: showerror( ugettext("Lucterios installer"), ugettext("Instance not restored!")) self.refresh(instance_name) def restore_inst(self): instance_name = self.get_selected_instance_name() if instance_name != '': file_name = askopenfilename( parent=self, filetypes=[('lbk', '.lbk'), ('bkf', '.bkf'), ('*', '.*')]) if file_name != '': self.restore_instance(instance_name, file_name) def execute(self): self.refresh() center(self, (700, 300)) self.mainloop()
class Player(object): """Player class""" def __init__(self): """Initialisation of the Player object""" self.cfg = None self.db = None self.root = Tk() self.URL1L = StringVar(master=self.root) self.URL2L = StringVar(master=self.root) self.URL3L = StringVar(master=self.root) self.URL4L = StringVar(master=self.root) self.URL5L = StringVar(master=self.root) self.files = {} self.start() #---------------------------------------------------------------------# def start(self): """Start the Player""" print("*** Starting the Player ***") # Configuration self.cfg = Config() while not self.cfg.readConf() or not self.cfg.checkConf(): self.displayConfig() if self.cfg.readConf() and self.cfg.checkConf(): # Database self.db = Db(self.cfg) if self.db.openDb(): self.display() return(True) else: error("Database not open") return(False) else: error("Cannot read configuration file") return(False) #---------------------------------------------------------------------# def stop(self): """Stop the Player""" msg = "Do you want to quit Raspyplayer ?" if messagebox.askokcancel("Raspyplayer MC", msg): print("*** Stopping the Player ***") self.db.closeDb() self.root.destroy() #---------------------------------------------------------------------# def scanDB(self): """Add movies in DB""" print("*** Adding movies in database") self.db.initDb() scanFiles(self.db, self.cfg, self.cfg.PATH) self.db.commitDb() return(True) #---------------------------------------------------------------------# def loadAllMovies(self): """Load movies from DB""" self.files = self.db.getAllMovies() return(True) #---------------------------------------------------------------------# def loadSrcMovies(self, src): """Load movies matching search pattern""" self.files = self.db.getSrcMovies(src) return(True) #---------------------------------------------------------------------# def play(self, url, file): """Play a movie""" print("Playing {}".format(file)) if self.cfg.useOmx(): if not url: sub = file[0:-3] + "srt" if isfile(sub): cmd = self.cfg.OMXCMD2.format(self.cfg.OPT, self.cfg.OUT, sub, file) else: cmd = self.cfg.OMXCMD1.format(self.cfg.OPT, self.cfg.OUT, file) else: cmd = self.cfg.OMXCMD1.format(self.cfg.OPT, self.cfg.OUT, file) else: cmd = self.cfg.MPLRCMD.format(file) if DEBUG: print(cmd) system(cmd) return(True) #---------------------------------------------------------------------# def directPlay(self): """Direct play a file""" file = askopenfilename(title="Select a movie") if file: ps = playScreen() self.play(False, file) ps.destroy() return(True) #---------------------------------------------------------------------# def displayHelp(self): """Display help""" messagebox.showinfo("Help...", getHelp()) return(True) #---------------------------------------------------------------------# def displayConfig(self): """Display Config Window""" self.cfg.display(self) self.askToRefreshDataBase() return(True) #---------------------------------------------------------------------# def playSelection(self): """Play selected files""" sel = self.ui_files.curselection() ps = playScreen() for i in sel: f = self.ui_files.get(i) self.play(False, self.files[f]) ps.destroy() return(True) #---------------------------------------------------------------------# def playUrl(self, url): """Play selected url""" ps = playScreen() self.play(True, url) ps.destroy() return(True) #---------------------------------------------------------------------# def display(self): """Display the player""" self.createGui() self.cfg.toggleUrl(self) self.askToRefreshDataBase() self.root.mainloop() #---------------------------------------------------------------------# def askToRefreshDataBase(self): """Ask to refresh database""" msg = "Do you want to refresh the movies database ?" if messagebox.askokcancel("Raspyplayer MC", msg): self.refreshDataBase() else: self.refreshFilesList() return(True) #---------------------------------------------------------------------# def refreshDataBase(self): """Refresh the movies database""" if isdir(self.cfg.PATH): self.scanDB() self.refreshFilesList() return(True) #---------------------------------------------------------------------# def refreshFilesList(self): """Refresh the list of files""" src = self.ui_srcentry.get() # Empty variables : self.files = {} if self.ui_files.size() > 0: self.ui_files.delete(0, END) # Get files in DB : if src == "" or src == "*": if DEBUG: print("Get ALL") self.loadAllMovies() else: if DEBUG: print("Get '{}'".format(src)) self.loadSrcMovies(('%'+src+'%',)) # Sort results : liste = list() for f, p in self.files.items(): liste.append(f) liste.sort(key=str.lower) # Display result : for file in liste: self.ui_files.insert(END, file) return(True) #---------------------------------------------------------------------# def playUrl1(self): """Play URL 1""" self.playUrl(self.cfg.URL1) def playUrl2(self): """Play URL 2""" self.playUrl(self.cfg.URL2) def playUrl3(self): """Play URL 3""" self.playUrl(self.cfg.URL3) def playUrl4(self): """Play URL 4""" self.playUrl(self.cfg.URL4) def playUrl5(self): """Play URL 5""" self.playUrl(self.cfg.URL5) #---------------------------------------------------------------------# def evtPlay(self, evt): self.playSelection() def evtRefresh(self, evt): self.refreshFilesList() def evtScan(self, evt): self.askToRefreshDataBase() def evtCfg(self, cfg): self.displayConfig() def evtHelp(self, evt): self.displayHelp() def evtQuit(self, evt): self.stop() #---------------------------------------------------------------------# def createGui(self): """Create the GUI for Player""" print("*** Creating GUI ***") self.root.title("Raspyplayer Media Center v{}".format(VERSION)) font = Font(self.root, size=26, family='Sans') #self.root.attributes('-fullscreen', True) self.root.attributes('-zoomed', '1') # Top Frame (search group) self.ui_topframe = Frame(self.root, borderwidth=2) self.ui_topframe.pack({"side": "top"}) # Label search self.ui_srclabel = Label(self.ui_topframe, text="Search:", font=font) self.ui_srclabel.grid(row=1, column=0, padx=2, pady=2) # Entry search self.ui_srcentry = Entry(self.ui_topframe, font=font) self.ui_srcentry.grid(row=1, column=1, padx=2, pady=2) self.ui_srcentry.bind("<Return>", self.evtRefresh) # Button search self.ui_srcexec = Button(self.ui_topframe, text="Search", command=self.refreshFilesList, font=font) self.ui_srcexec.grid(row=1, column=2, padx=2, pady=2) # Frame (contain Middle and Url frames) self.ui_frame = Frame(self.root, borderwidth=2) self.ui_frame.pack(fill=BOTH, expand=1) # Middle Frame (files group) self.ui_midframe = Frame(self.ui_frame, borderwidth=2) self.ui_midframe.pack({"side": "left"}, fill=BOTH, expand=1) # Files liste and scrollbar self.ui_files = Listbox(self.ui_midframe, selectmode=EXTENDED, font=font) self.ui_files.pack(side=LEFT, fill=BOTH, expand=1) self.ui_files.bind("<Return>", self.evtPlay) self.ui_filesscroll = Scrollbar(self.ui_midframe, command=self.ui_files.yview) self.ui_files.configure(yscrollcommand=self.ui_filesscroll.set) self.ui_filesscroll.pack(side=RIGHT, fill=Y) # Url Frame (url group) self.ui_urlframe = Frame(self.ui_frame, borderwidth=2) self.ui_urlframe.pack({"side": "right"}) # Button Url 1 self.ui_buturl1 = Button(self.ui_urlframe, textvariable=self.URL1L, command=self.playUrl1, font=font) self.ui_buturl1.grid(row=1, column=0, padx=2, pady=2) # Button Url 2 self.ui_buturl2 = Button(self.ui_urlframe, textvariable=self.URL2L, command=self.playUrl2, font=font) self.ui_buturl2.grid(row=2, column=0, padx=2, pady=2) # Button Url 3 self.ui_buturl3 = Button(self.ui_urlframe, textvariable=self.URL3L, command=self.playUrl3, font=font) self.ui_buturl3.grid(row=3, column=0, padx=2, pady=2) # Button Url 4 self.ui_buturl4 = Button(self.ui_urlframe, textvariable=self.URL4L, command=self.playUrl4, font=font) self.ui_buturl4.grid(row=4, column=0, padx=2, pady=2) # Button Url 5 self.ui_buturl5 = Button(self.ui_urlframe, textvariable=self.URL5L, command=self.playUrl5, font=font) self.ui_buturl5.grid(row=5, column=0, padx=2, pady=2) # Bottom Frame (buttons group) self.ui_botframe = Frame(self.root, borderwidth=2) self.ui_botframe.pack({"side": "left"}) # Button Play self.ui_butplay = Button(self.ui_botframe, text="Play", command=self.playSelection, font=font) self.ui_butplay.grid(row=1, column=0, padx=2, pady=2) # Button Refresh self.ui_butscan = Button(self.ui_botframe, text="Scan", command=self.askToRefreshDataBase, font=font) self.ui_butscan.grid(row=1, column=1, padx=2, pady=2) # Button Direct Play self.ui_butdplay = Button(self.ui_botframe, text="Direct Play", command=self.directPlay, font=font) self.ui_butdplay.grid(row=1, column=2, padx=2, pady=2) # Button Config self.ui_butconf = Button(self.ui_botframe, text="Config", command=lambda : self.cfg.display(self), font=font) self.ui_butconf.grid(row=1, column=3, padx=2, pady=2) # Button Help self.ui_buthelp = Button(self.ui_botframe, text="Help", command=self.displayHelp, font=font) self.ui_buthelp.grid(row=1, column=4, padx=2, pady=2) # Button Quit self.ui_butquit = Button(self.ui_botframe, text="Quit", command=self.stop, font=font) self.ui_butquit.grid(row=1, column=5, padx=2, pady=2) # General bindings self.root.bind("<F1>", self.evtHelp) self.root.bind("<F2>", self.evtCfg) self.root.bind("<F3>", self.evtRefresh) self.root.bind("<F5>", self.evtScan) self.root.bind("<F12>", self.evtQuit) return(True)
class DrtGlueDemo(object): def __init__(self, examples): # Set up the main window. self._top = Tk() self._top.title("DRT Glue Demo") # Set up key bindings. self._init_bindings() # Initialize the fonts.self._error = None self._init_fonts(self._top) self._examples = examples self._readingCache = [None for example in examples] # The user can hide the grammar. self._show_grammar = IntVar(self._top) self._show_grammar.set(1) # Set the data to None self._curExample = -1 self._readings = [] self._drs = None self._drsWidget = None self._error = None self._init_glue() # Create the basic frames. self._init_menubar(self._top) self._init_buttons(self._top) self._init_exampleListbox(self._top) self._init_readingListbox(self._top) self._init_canvas(self._top) # Resize callback self._canvas.bind("<Configure>", self._configure) ######################################### ## Initialization Helpers ######################################### def _init_glue(self): tagger = RegexpTagger( [ ("^(David|Mary|John)$", "NNP"), ("^(walks|sees|eats|chases|believes|gives|sleeps|chases|persuades|tries|seems|leaves)$", "VB"), ("^(go|order|vanish|find|approach)$", "VB"), ("^(a)$", "ex_quant"), ("^(every)$", "univ_quant"), ("^(sandwich|man|dog|pizza|unicorn|cat|senator)$", "NN"), ("^(big|gray|former)$", "JJ"), ("^(him|himself)$", "PRP"), ] ) depparser = MaltParser(tagger=tagger) self._glue = DrtGlue(depparser=depparser, remove_duplicates=False) def _init_fonts(self, root): # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html> self._sysfont = Font(font=Button()["font"]) root.option_add("*Font", self._sysfont) # TWhat's our font size (default=same as sysfont) self._size = IntVar(root) self._size.set(self._sysfont.cget("size")) self._boldfont = Font(family="helvetica", weight="bold", size=self._size.get()) self._font = Font(family="helvetica", size=self._size.get()) if self._size.get() < 0: big = self._size.get() - 2 else: big = self._size.get() + 2 self._bigfont = Font(family="helvetica", weight="bold", size=big) def _init_exampleListbox(self, parent): self._exampleFrame = listframe = Frame(parent) self._exampleFrame.pack(fill="both", side="left", padx=2) self._exampleList_label = Label(self._exampleFrame, font=self._boldfont, text="Examples") self._exampleList_label.pack() self._exampleList = Listbox( self._exampleFrame, selectmode="single", relief="groove", background="white", foreground="#909090", font=self._font, selectforeground="#004040", selectbackground="#c0f0c0", ) self._exampleList.pack(side="right", fill="both", expand=1) for example in self._examples: self._exampleList.insert("end", (" %s" % example)) self._exampleList.config(height=min(len(self._examples), 25), width=40) # Add a scrollbar if there are more than 25 examples. if len(self._examples) > 25: listscroll = Scrollbar(self._exampleFrame, orient="vertical") self._exampleList.config(yscrollcommand=listscroll.set) listscroll.config(command=self._exampleList.yview) listscroll.pack(side="left", fill="y") # If they select a example, apply it. self._exampleList.bind("<<ListboxSelect>>", self._exampleList_select) def _init_readingListbox(self, parent): self._readingFrame = listframe = Frame(parent) self._readingFrame.pack(fill="both", side="left", padx=2) self._readingList_label = Label(self._readingFrame, font=self._boldfont, text="Readings") self._readingList_label.pack() self._readingList = Listbox( self._readingFrame, selectmode="single", relief="groove", background="white", foreground="#909090", font=self._font, selectforeground="#004040", selectbackground="#c0f0c0", ) self._readingList.pack(side="right", fill="both", expand=1) # Add a scrollbar if there are more than 25 examples. listscroll = Scrollbar(self._readingFrame, orient="vertical") self._readingList.config(yscrollcommand=listscroll.set) listscroll.config(command=self._readingList.yview) listscroll.pack(side="right", fill="y") self._populate_readingListbox() def _populate_readingListbox(self): # Populate the listbox with integers self._readingList.delete(0, "end") for i in range(len(self._readings)): self._readingList.insert("end", (" %s" % (i + 1))) self._readingList.config(height=min(len(self._readings), 25), width=5) # If they select a example, apply it. self._readingList.bind("<<ListboxSelect>>", self._readingList_select) def _init_bindings(self): # Key bindings are a good thing. self._top.bind("<Control-q>", self.destroy) self._top.bind("<Control-x>", self.destroy) self._top.bind("<Escape>", self.destroy) self._top.bind("n", self.next) self._top.bind("<space>", self.next) self._top.bind("p", self.prev) self._top.bind("<BackSpace>", self.prev) def _init_buttons(self, parent): # Set up the frames. self._buttonframe = buttonframe = Frame(parent) buttonframe.pack(fill="none", side="bottom", padx=3, pady=2) Button(buttonframe, text="Prev", background="#90c0d0", foreground="black", command=self.prev).pack(side="left") Button(buttonframe, text="Next", background="#90c0d0", foreground="black", command=self.next).pack(side="left") def _configure(self, event): self._autostep = 0 (x1, y1, x2, y2) = self._cframe.scrollregion() y2 = event.height - 6 self._canvas["scrollregion"] = "%d %d %d %d" % (x1, y1, x2, y2) self._redraw() def _init_canvas(self, parent): self._cframe = CanvasFrame( parent, background="white", # width=525, height=250, closeenough=10, border=2, relief="sunken", ) self._cframe.pack(expand=1, fill="both", side="top", pady=2) canvas = self._canvas = self._cframe.canvas() # Initially, there's no tree or text self._tree = None self._textwidgets = [] self._textline = None def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Exit", underline=1, command=self.destroy, accelerator="q") menubar.add_cascade(label="File", underline=0, menu=filemenu) actionmenu = Menu(menubar, tearoff=0) actionmenu.add_command(label="Next", underline=0, command=self.next, accelerator="n, Space") actionmenu.add_command(label="Previous", underline=0, command=self.prev, accelerator="p, Backspace") menubar.add_cascade(label="Action", underline=0, menu=actionmenu) optionmenu = Menu(menubar, tearoff=0) optionmenu.add_checkbutton( label="Remove Duplicates", underline=0, variable=self._glue.remove_duplicates, command=self._toggle_remove_duplicates, accelerator="r", ) menubar.add_cascade(label="Options", underline=0, menu=optionmenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_radiobutton(label="Tiny", variable=self._size, underline=0, value=10, command=self.resize) viewmenu.add_radiobutton(label="Small", variable=self._size, underline=0, value=12, command=self.resize) viewmenu.add_radiobutton(label="Medium", variable=self._size, underline=0, value=14, command=self.resize) viewmenu.add_radiobutton(label="Large", variable=self._size, underline=0, value=18, command=self.resize) viewmenu.add_radiobutton(label="Huge", variable=self._size, underline=0, value=24, command=self.resize) menubar.add_cascade(label="View", underline=0, menu=viewmenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="About", underline=0, command=self.about) menubar.add_cascade(label="Help", underline=0, menu=helpmenu) parent.config(menu=menubar) ######################################### ## Main draw procedure ######################################### def _redraw(self): canvas = self._canvas # Delete the old DRS, widgets, etc. if self._drsWidget is not None: self._drsWidget.clear() if self._drs: self._drsWidget = DrsWidget(self._canvas, self._drs) self._drsWidget.draw() if self._error: self._drsWidget = DrsWidget(self._canvas, self._error) self._drsWidget.draw() ######################################### ## Button Callbacks ######################################### def destroy(self, *e): self._autostep = 0 if self._top is None: return self._top.destroy() self._top = None def prev(self, *e): selection = self._readingList.curselection() readingListSize = self._readingList.size() # there are readings if readingListSize > 0: # if one reading is currently selected if len(selection) == 1: index = int(selection[0]) # if it's on (or before) the first item if index <= 0: self._select_previous_example() else: self._readingList_store_selection(index - 1) else: # select its first reading self._readingList_store_selection(readingListSize - 1) else: self._select_previous_example() def _select_previous_example(self): # if the current example is not the first example if self._curExample > 0: self._exampleList_store_selection(self._curExample - 1) else: # go to the last example self._exampleList_store_selection(len(self._examples) - 1) def next(self, *e): selection = self._readingList.curselection() readingListSize = self._readingList.size() # if there are readings if readingListSize > 0: # if one reading is currently selected if len(selection) == 1: index = int(selection[0]) # if it's on (or past) the last item if index >= (readingListSize - 1): self._select_next_example() else: self._readingList_store_selection(index + 1) else: # select its first reading self._readingList_store_selection(0) else: self._select_next_example() def _select_next_example(self): # if the current example is not the last example if self._curExample < len(self._examples) - 1: self._exampleList_store_selection(self._curExample + 1) else: # go to the first example self._exampleList_store_selection(0) def about(self, *e): ABOUT = "NLTK Discourse Representation Theory (DRT) Glue Semantics Demo\n" + "Written by Daniel H. Garrette" TITLE = "About: NLTK DRT Glue Demo" try: from tkMessageBox import Message Message(message=ABOUT, title=TITLE).show() except: ShowText(self._top, TITLE, ABOUT) def postscript(self, *e): self._autostep = 0 self._cframe.print_to_file() def mainloop(self, *args, **kwargs): """ Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes. """ if in_idle(): return self._top.mainloop(*args, **kwargs) def resize(self, size=None): if size is not None: self._size.set(size) size = self._size.get() self._font.configure(size=-(abs(size))) self._boldfont.configure(size=-(abs(size))) self._sysfont.configure(size=-(abs(size))) self._bigfont.configure(size=-(abs(size + 2))) self._redraw() def _toggle_remove_duplicates(self): self._glue.remove_duplicates = not self._glue.remove_duplicates self._exampleList.selection_clear(0, "end") self._readings = [] self._populate_readingListbox() self._readingCache = [None for ex in self._examples] self._curExample = -1 self._error = None self._drs = None self._redraw() def _exampleList_select(self, event): selection = self._exampleList.curselection() if len(selection) != 1: return self._exampleList_store_selection(int(selection[0])) def _exampleList_store_selection(self, index): self._curExample = index example = self._examples[index] self._exampleList.selection_clear(0, "end") if example: cache = self._readingCache[index] if cache: if isinstance(cache, list): self._readings = cache self._error = None else: self._readings = [] self._error = cache else: try: self._readings = self._glue.parse_to_meaning(example) self._error = None self._readingCache[index] = self._readings except Exception as e: self._readings = [] self._error = DrtVariableExpression(Variable("Error: " + str(e))) self._readingCache[index] = self._error # add a star to the end of the example self._exampleList.delete(index) self._exampleList.insert(index, (" %s *" % example)) self._exampleList.config(height=min(len(self._examples), 25), width=40) self._populate_readingListbox() self._exampleList.selection_set(index) self._drs = None self._redraw() def _readingList_select(self, event): selection = self._readingList.curselection() if len(selection) != 1: return self._readingList_store_selection(int(selection[0])) def _readingList_store_selection(self, index): reading = self._readings[index] self._readingList.selection_clear(0, "end") if reading: self._readingList.selection_set(index) self._drs = reading.simplify().normalize().resolve_anaphora() self._redraw()
class Main(Frame): def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller self.db_set = False self.configure(relief=GROOVE) self.configure(borderwidth="2") # Manual link adding self.manual_btn = Button(self) self.manual_btn.place(relx=0.07, rely=0.81, height=45, width=130) self.manual_btn.configure(activebackground="#d9d9d9") self.manual_btn.configure(highlightbackground="#d9d9d9") self.manual_btn.configure(pady="0") self.manual_btn.configure(text="Add manually") self.manual_btn.configure(width=130) self.file_btn = Button(self) self.file_btn.place(relx=0.67, rely=0.81, height=45, width=150) self.file_btn.configure(activebackground="#d9d9d9") self.file_btn.configure(highlightbackground="#d9d9d9") self.file_btn.configure(pady="0") self.file_btn.configure(text="Add from file") self.label = Label(self) self.label.place(relx=0.08, rely=0.0, height=61, width=484) self.label.configure(text="Create new playlists and add content to them") self.label.configure(width=485) self.listbox = Listbox(self) self.listbox.place(relx=0.38, rely=0.22, relheight=0.31, relwidth=0.17) self.listbox.configure(background="white") self.listbox.configure(disabledforeground="#a3a3a3") self.listbox.configure(foreground="#000000") self.listbox.configure(selectmode=SINGLE) self.listbox.configure(width=105) for name, value in config.configparser.items('Playlists'): if os.path.isdir(value): self.listbox.insert('end', name) else: config.remove_value('Playlists', name) self.listbox.bind('<<ListboxSelect>>', self.onselect) self.label_name = Label(self) self.label_name.place(relx=0.7, rely=0.22, height=31, width=84) self.label_name.configure(foreground="#000000") self.label_name.configure(text="Name") self.label_name.configure(width=85) self.entry = Entry(self) self.entry.place(relx=0.63, rely=0.31, relheight=0.08, relwidth=0.29) self.entry.configure(background="white") self.entry.configure(foreground="#000000") self.entry.configure(insertbackground="black") self.entry.configure(takefocus="0") self.entry.configure(width=175) self.change_name = Button(self) self.change_name.place(relx=0.7, rely=0.42, height=34, width=97) self.change_name.configure(activebackground="#d9d9d9") self.change_name.configure(highlightbackground="#d9d9d9") self.change_name.configure(highlightcolor="black") self.change_name.configure(pady="0") self.change_name.configure(text="Rename") self.change_name.configure(width=100) self.new_playlist = Button(self, command=self.new_database) self.new_playlist.place(relx=0.08, rely=0.28, height=54, width=107) self.new_playlist.configure(activebackground="#d9d9d9") self.new_playlist.configure(highlightbackground="#d9d9d9") self.new_playlist.configure(highlightcolor="black") self.new_playlist.configure(pady="0") self.new_playlist.configure(text="Create new playlist") self.new_playlist.configure(width=105) self.db_name = Entry(self) self.db_name.place(relx=0.07, rely=0.44, relheight=0.08, relwidth=0.22) self.db_name.configure(fg='grey') self.db_name.configure(width=135) self.db_name.insert(0, "Input database name here") self.db_name.bind('<Button-1>', lambda event: greytext(self.db_name)) def onselect(self, event): w = event.widget index = int(w.curselection()[0]) value = w.get(index) set_database(config.configparser.get('Playlists', value)) if not database.check_integrity(): messagebox.showwarning('Integrity check failed', 'You might be missing some entries in your list') if not self.db_set: self.manual_btn.configure(command=lambda: self.controller.show_frame('AddManually')) self.file_btn.configure(command=lambda: self.controller.show_frame('ReadFromFile')) self.db_set = True def new_database(self): name = self.db_name.get() names = config.configparser.options('Playlists') print(name, names) if name.strip() == '' or self.db_name.cget('fg') == 'grey': messagebox.showerror('Invalid name', "Please input a valid name for the database") return if name in names: messagebox.showerror('Name already in use', "Please select another name") return path = '../playlists/%s/' % name if set_database(path, create=True) is False: return config.set_value('Playlists', name, path) self.listbox.insert('end', name)
class AutocompleteEntry(Entry): def __init__(self, *args, **kwargs): Entry.__init__(self, width=100, *args, **kwargs) self.focus_set() self.pack() self.var = self["textvariable"] if self.var == '': self.var = self["textvariable"] = StringVar() self.var.trace('w', self.changed) self.bind("<Right>", self.selection) self.bind("<Up>", self.up) self.bind("<Down>", self.down) self.bind("<Return>", self.enter) self.lb_up = False self.lb = None def enter(self, event): print(event) def changed(self, name, index, mode): if self.var.get() == '': if self.lb: self.lb.destroy() self.lb_up = False else: words = self.comparison() if words: if not self.lb_up: self.lb = Listbox(master=root, width=100) self.lb.bind("<Double-Button-1>", self.selection) self.lb.bind("<Right>", self.selection) self.lb.place(x=self.winfo_x(), y=self.winfo_y()+self.winfo_height()) self.lb_up = True self.lb.delete(0, END) for w in words: self.lb.insert(END,w) else: if self.lb_up: self.lb.destroy() self.lb_up = False def selection(self, _): if self.lb_up: self.var.set(self.lb.get(ACTIVE)) self.lb.destroy() self.lb_up = False self.icursor(END) def up(self, _): if self.lb_up: if self.lb.curselection() == (): index = '0' else: index = self.lb.curselection()[0] if index != '0': self.lb.selection_clear(first=index) index = str(int(index)-1) self.lb.selection_set(first=index) self.lb.activate(index) def down(self, _): if self.lb_up: if self.lb.curselection() == (): index = '0' else: index = self.lb.curselection()[0] if index != END: self.lb.selection_clear(first=index) index = str(int(index)+1) self.lb.selection_set(first=index) self.lb.activate(index) def comparison(self): q = self.var.get() q = str(q.decode('utf8')) for hit in searcher.search(qp.parse(q), limit=50): if hit['author']: yield '%s. "%s"' % (hit['author'], hit['title']) else: yield hit['title']
class Add_Recipe_Modal(Modal): def __init__(self, parent=None, title="Add Recipe"): self.shorts = [] self.amounts = None self.ingredients = None Modal.__init__(self, parent, title, geometry="375x410" if system() == "Windows" else "375x350") def initialize(self): amount_label = Label(self, width=8, text="Amount") amount_label.grid(row=0, column=0) ingredients_label = Label(self, width=35, text="Item Name") ingredients_label.grid(row=0, column=1) self.amounts_list = Listbox(self, width=8, selectmode="single") self.amounts_list.bind("<Double-Button-1>", self.edit) self.amounts_list.grid(row=1, column=0, sticky="E") self.ingredients_list = Listbox(self, width=35, selectmode="single") self.ingredients_list.bind("<Double-Button-1>", self.edit) self.ingredients_list.grid(row=1, column=1) add_button = Button(self, width=7, text="Add", command=self.add) self.bind("<Control-+>", self.add) self.bind("<Insert>", self.add) add_button.grid(row=2, column=1, sticky="E") remove_button = Button(self, text="Remove", command=self.remove) self.bind("<Delete>", self.remove) remove_button.grid(row=2, column=0) produces_label = Label(self, text="Produces: ") produces_label.grid(row=3, column=0, sticky="W") self.produces_box = Entry(self, width=5) self.produces_box.insert(0, "1") self.produces_box.grid(row=3, column=1, sticky="W") machine_label = Label(self, text="Machine: ") machine_label.grid(row=4, column=0, sticky="W") self.machine_box = Entry(self) self.machine_box.grid(row=4, column=1, sticky="EW") info_label = Label(self, text="Extra Info: ") info_label.grid(row=5, column=0, sticky="W") self.info_box = Entry(self) self.info_box.grid(row=5, column=1, sticky="EW") cancel_button = Button(self, text="Cancel", width=7, command=self.cancel) self.bind("<Escape>", self.cancel) cancel_button.grid(row=6, column=0, pady=10) ok_button = Button(self, text="OK", width=7, command=self.ok) self.bind("<Return>", self.ok) ok_button.grid(row=6, column=1, pady=10, sticky="E") self.bind("<<ListboxSelect>>", self.sync) def sync(self, event): if event.widget is self.amounts_list and len(self.amounts_list.curselection()) != 0: self.ingredients_list.selection_set(self.amounts_list.curselection()[0]) def add(self, event=None): short, name, amount = Add_Ingredient_Modal().show() if short is not None and name is not None and amount is not None: if name not in self.ingredients_list.get(0, "end"): self.ingredients_list.insert("end", name) self.amounts_list.insert("end", amount) self.shorts.append(short) def edit(self, event=None): if len(self.ingredients_list.curselection()) != 0: index = self.ingredients_list.curselection()[0] current_short = self.shorts[index] current_name = self.ingredients_list.get(index) current_amount = self.amounts_list.get(index) new_short, new_name, new_amount = Edit_Ingredient_Modal().show(current_short, current_name, current_amount) if new_short is not None and new_name is not None and new_amount is not None: self.amounts_list.delete(index) self.ingredients_list.delete(index) self.amounts_list.insert(index, new_amount) self.ingredients_list.insert(index, new_name) self.shorts[index] = new_short def remove(self, event=None): if len(self.ingredients_list.curselection()) != 0: slct = int(self.ingredients_list.curselection()[0]) self.ingredients_list.delete(slct) self.amounts_list.delete(slct) del(self.shorts[slct]) def ok(self, event=None): if len(self.ingredients_list.get(0)) != 0 and self.produces_box is not None and self.produces_box.get().isdigit(): self.produces = int(self.produces_box.get()) self.amounts = self.amounts_list.get(0, last="end") self.ingredients = self.ingredients_list.get(0, last="end") self.machine = self.machine_box.get() self.info = self.info_box.get() self.destroy() def cancel(self, event=None): self.amounts = None self.ingredients = None self.shorts = None self.produces = None self.machine = None self.info = None self.destroy() def show(self): Modal.show(self) return self.shorts, self.ingredients, self.amounts, self.produces, self.machine, self.info
class ListboxVidget(Vidget, Eventor): """ ListboxVidget contains a Listbox widget. It adds the following abilities: - Store items of any type, unlike Listbox widget that only stores texts. - Remember selected item even if the listbox widget lost focus. - Notify pre-change and post-change events. """ # Error raised when trying to change the listbox while a change is going on class CircularCallError(ValueError): pass # Error raised when trying to change the listbox while it is disabled class DisabledError(ValueError): pass # Event notified when the listbox's items are to be changed ITEMS_CHANGE_SOON = 'ITEMS_CHANGE_SOON' # Event notified when the listbox's items are changed ITEMS_CHANGE_DONE = 'ITEMS_CHANGE_DONE' # Event notified when the listbox's active item is to be changed ITEMCUR_CHANGE_SOON = 'ITEMCUR_CHANGE_SOON' # Event notified when the listbox's active item is changed ITEMCUR_CHANGE_DONE = 'ITEMCUR_CHANGE_DONE' # Events list EVENTS = ( ITEMS_CHANGE_SOON, ITEMS_CHANGE_DONE, ITEMCUR_CHANGE_SOON, ITEMCUR_CHANGE_DONE, ) def __init__( self, items=None, item_to_text=None, normal_bg='', normal_fg='', active_bg='sky blue', active_fg='white', selected_bg='steel blue', selected_fg='white', master=None, ): """ Initialize object. @param items: Items list. @param item_to_text: Item-to-text function. Default is `str`. @param normal_bg: Unselected item background color. @param normal_fg: Unselected item foreground color. @param active_bg: Active item background color. `Active` means the item is selected (in general meaning) but the listbox has no focus. @param active_fg: Active item foreground color. `Active` means the item is selected (in general meaning) but the listbox has no focus. @param selected_bg: Selected item background color. `Selected` means the item is selected (in general meaning) and the listbox has focus. @param selected_fg: Selected item foreground color. `Selected` means the item is selected (in general meaning) and the listbox has focus. @param master: Master widget. @return: None. """ # Initialize Vidget. # Create main frame widget. Vidget.__init__( self, master=master, ) # Initialize Eventor Eventor.__init__(self) # If items list is given if items is not None: # If items list is not list if not isinstance(items, list): # Raise error raise TypeError(items) # If items list is list. # If items list is not given, or items list is given and is list # Items list self._items = items if items is not None else [] # Item-to-text function. Default is `str`. self._item_to_text = item_to_text if item_to_text is not None else str # Unselected item background color self._normal_fg = normal_fg # Unselected item foreground color self._normal_bg = normal_bg # Active item background color self._active_fg = active_fg # Active item foreground color self._active_bg = active_bg # Selected item background color self._selected_fg = selected_fg # Selected item foreground color self._selected_bg = selected_bg # Whether the listbox is changing self._is_changing = False # Active index. `-1` means void, i.e. no item is active. self._indexcur = -1 # Whether active index is being reset to same value self._is_resetting = False # Create listbox widget self._listbox = Listbox( master=self.widget(), relief='groove', activestyle='none', highlightthickness=0, # Active index cache only supports single-selection mode for now. # See 2N6OR. selectmode='single', ) # Set the listbox widget as config target self.config_target_set(self._listbox) # Create x-axis scrollbar self._scrollbar_xview = _HiddenScrollbar( self.widget(), orient=HORIZONTAL, ) # Create y-axis scrollbar self._scrollbar_yview = _HiddenScrollbar( self.widget(), orient=VERTICAL, ) # Mount scrollbars self._listbox.config(xscrollcommand=self._scrollbar_xview.set) self._listbox.config(yscrollcommand=self._scrollbar_yview.set) self._scrollbar_xview.config(command=self._listbox.xview) self._scrollbar_yview.config(command=self._listbox.yview) # Bind single-click event handler self._listbox.bind('<Button-1>', self._on_single_click) # Bind double-click event handler self._listbox.bind('<Double-Button-1>', self._on_double_click) # Update listbox widget self._listbox_widget_update(keep_active=False) # Update widget self._widget_update() def _widget_update(self): """ Update widget. @return: None. """ # Row 0 for listbox and y-axis scrollbar self.widget().rowconfigure(0, weight=1) # Row 1 for x-axis scrollbar self.widget().rowconfigure(1, weight=0) # Column 0 for listbox and x-axis scrollbar self.widget().columnconfigure(0, weight=1) # Column 1 for y-axis scrollbar self.widget().columnconfigure(1, weight=0) # Lay out listbox self._listbox.grid(row=0, column=0, sticky='NSEW') # Lay out x-axis scrollbar self._scrollbar_xview.grid(row=1, column=0, sticky='EW') # Lay out y-axis scrollbar self._scrollbar_yview.grid(row=0, column=1, sticky='NS') def is_enabled(self): """ Test whether the listbox is enabled. @return: Boolean. """ # Return whether the listbox is enabled return self._listbox.config('state')[4] != DISABLED def is_changing(self): """ Test whether the listbox is changing. @return: Boolean. """ # Return whether the listbox is changing return self._is_changing def is_resetting(self): """ Test whether the listbox is setting active index to the same value. @return: Boolean. """ # Return whether the listbox is setting active index to the same value return self._is_resetting def size(self): """ Get number of items. @return: Number of items. """ # Return number of items return len(self._items) def items(self): """ Get items list. Notice do not change the list outside. @return: Items list. """ # Return items list return self._items def items_set( self, items, notify=True, keep_active=False, ): """ Set items list. Notice do not change the list outside. @param items: Items list. @param notify: Whether notify pre-change and post-change events. @param keep_active: Whether keep or clear active index. @return: None. """ # If the items is not list if not isinstance(items, list): # Raise error raise TypeError(items) # If the items is list. # If the listbox is disabled if not self.is_enabled(): # Raise error raise ListboxVidget.DisabledError() # If the listbox is not disabled. # If the listbox is changing if self._is_changing: # Raise error raise ListboxVidget.CircularCallError() # If the listbox is not changing. # Set changing flag on self._is_changing = True # If notify events if notify: # Notify pre-change event self.handler_notify(self.ITEMS_CHANGE_SOON) # Store the new items self._items = items # Update listbox widget self._listbox_widget_update( keep_active=keep_active ) # If notify events if notify: # Notify post-change event self.handler_notify(self.ITEMS_CHANGE_DONE) # Set changing flag off self._is_changing = False def index_is_valid(self, index): """ Test whether given index is valid. Notice -1 is not valid. @param index: Index to test. @return: Boolean. """ # Test whether given index is valid return 0 <= index and index < self.size() def index_is_valid_or_void(self, index): """ Test whether given index is valid or is -1. @param index: Index to test. @return: Boolean. """ # Test whether given index is valid or is -1 return index == -1 or self.index_is_valid(index) def index_first(self): """ Get the first item's index. @return: First item's index, or -1 if the listbox is empty. """ # Return the first item's index return 0 if self.size() > 0 else -1 def index_last(self): """ Get the last item's index. @return: Last item's index, or -1 if the listbox is empty. """ # Return the last item's index return self.size() - 1 def indexcur(self, internal=False, raise_error=False): """ Get the active index. @param internal: See 2N6OR. @return: The active index. If no active active, either return -1, or raise IndexError if `raise_error` is True. """ # Get active indexes indexcurs = self._indexcurs(internal=internal) # If have active indexes if indexcurs: # Return the first active index return indexcurs[0] # If no active indexes else: # If raise error if raise_error: # Raise error raise IndexError(-1) # If not raise error else: # Return -1 return -1 def _indexcurs(self, internal=False): """ Get active indexes list. 2N6OR @param internal: Whether use listbox widget's selected indexes, instead of cached active index. Notice listbox widget has no selected indexes if it has no focus. Notice using cached active index only supports single-selection mode, which means the result list has at most one index. @return: Active indexes list. """ # If use listbox widget's selected indexes if internal: # Return listbox widget's selected indexes list return [int(x) for x in self._listbox.curselection()] # If not use listbox widget's selected indexes else: # If cached active index is valid if self.index_is_valid(self._indexcur): # Return a list with the cached active index return [self._indexcur] # If cached active index is not valid else: # Return empty list return [] def indexcur_set( self, index, focus=False, notify=True, notify_arg=None, ): """ Set active index. @param index: The index to set. @param focus: Whether set focus on the listbox widget. @param notify: Whether notify pre-change and post-change events. @param notify_arg: Event argument. @return: None. """ # If the index is not valid or -1 if not self.index_is_valid_or_void(index): # Raise error raise IndexError(index) # If the index is valid or is -1. # If the listbox is not enabled if not self.is_enabled(): # Raise error raise ListboxVidget.DisabledError() # If the listbox is enabled. # If the listbox is changing if self._is_changing: # Raise error raise ListboxVidget.CircularCallError() # If the listbox is not changing. # Set changing flag on self._is_changing = True # Get old active index old_indexcur = self._indexcur # Set resetting flag on if new and old indexes are equal self._is_resetting = (index == old_indexcur) # If notify events if notify: # Notify pre-change event self.handler_notify(self.ITEMCUR_CHANGE_SOON, notify_arg) # If old active index is valid if self.index_is_valid(old_indexcur): # Set old active item's background color to normal color self._listbox.itemconfig(old_indexcur, background=self._normal_bg) # Set old active item's foreground color to normal color self._listbox.itemconfig(old_indexcur, foreground=self._normal_fg) # Cache new active index self._indexcur = index # Clear listbox widget's selection self._listbox.selection_clear(0, END) # Set listbox widget's selection self._listbox.selection_set(index) # Set listbox widget's activated index self._listbox.activate(index) # If new active index is valid if index != -1: # Set new active item's background color to active color self._listbox.itemconfig(index, background=self._active_bg) # Set new active item's foreground color to active color self._listbox.itemconfig(index, foreground=self._active_fg) # If set focus if focus: # Set focus on the listbox widget self._listbox.focus_set() # If new active index is valid if index != -1: # Make the active item visible self._listbox.see(index) # If notify events if notify: # Notify post-change event self.handler_notify(self.ITEMCUR_CHANGE_DONE, notify_arg) # Set resetting flag off self._is_resetting = False # Set changing flag off self._is_changing = False def indexcur_set_by_event( self, event, focus=False, notify=True, notify_arg=None, ): """ Set active index using a Tkinter event object that contains coordinates of the active item. @param event: Tkinter event object. @param focus: Whether set focus on the listbox widget. @param notify: Whether notify pre-change and post-change events. @param notify_arg: Event argument. @return: None. """ # Get the event's y co-ordinate's nearest listbox item index index = self._listbox.nearest(event.y) # If the index is not valid if not self.index_is_valid_or_void(index): # Ignore the event return # If the index is valid else: # Set the index as active index self.indexcur_set( index=index, focus=focus, notify=notify, notify_arg=notify_arg, ) def item(self, index): """ Get item at given index. @return: Item at given index, or IndexError if the index is not valid. """ return self.items()[index] def itemcur(self, internal=False, raise_error=False): """ Get the active item. @param internal: See 2N6OR. @param raise_error: Whether raise error if no active item. @return: The active item. If no active item, if `raise_error` is True, raise IndexError, otherwise return None. """ # Get active index. # May raise IndexError if `raise_error` is True. indexcur = self.indexcur( internal=internal, raise_error=raise_error, ) # If no active index if indexcur == -1: # Return None return None # If have active index else: # Return the active item return self.items()[indexcur] def item_insert( self, item, index=None, notify=True, keep_active=True, ): """ Insert item at given index. @param item: Item to insert. @param index: Index to insert. `None` means active index, and if no active index, insert at the end. @param notify: Whether notify pre-change and post-change events. @param keep_active: Whether keep or clear active index. @return: None. """ # If notify events if notify: # Notify pre-change events self.handler_notify(self.ITEMCUR_CHANGE_SOON) self.handler_notify(self.ITEMS_CHANGE_SOON) # Get old active index active_index = self.indexcur() # If the index is None, # it means use active index. if index is None: # Use active index. # `-1` works and means appending. index = active_index # Insert the item to the items list self._items.insert(index, item) # If old active index is valid if active_index != -1: # If old active index is GE the inserted index if active_index >= index: # Shift active index by one active_index += 1 # If old active index is not GE the inserted index, use it as-is. # Set new active index self.indexcur_set(index=active_index, notify=False) # Update listbox widget self._listbox_widget_update( keep_active=keep_active ) # If notify events if notify: # Notify post-change events self.handler_notify(self.ITEMS_CHANGE_DONE) self.handler_notify(self.ITEMCUR_CHANGE_DONE) def item_remove( self, index, notify=True, keep_active=True, ): """ Remove item at given index. @param index: Index to remove. @param notify: Whether notify pre-change and post-change events. @param keep_active: Whether keep or clear active index. @return: None. """ # If the index is not valid if not self.index_is_valid(index): # Raise error raise ValueError(index) # If the index is valid. # If notify events if notify: # Notify pre-change events self.handler_notify(self.ITEMCUR_CHANGE_SOON) self.handler_notify(self.ITEMS_CHANGE_SOON) # Get old active index active_index = self.indexcur() # Remove item at the index del self._items[index] # If old active index is valid if active_index != -1: # Get the last index index_last = self.index_last() # If old active index is GT the last index if active_index > index_last: # Use the last index as new active index active_index = index_last # If old active index is not GT the last index, use it as-is. # Set new active index self.indexcur_set(index=active_index, notify=False) # Update listbox widget self._listbox_widget_update( keep_active=keep_active ) # If notify events if notify: # Notify post-change events self.handler_notify(self.ITEMS_CHANGE_DONE) self.handler_notify(self.ITEMCUR_CHANGE_DONE) def handler_add( self, event, handler, need_arg=False, ): """ Add event handler for an event. If the event is ListboxVidget event, add the event handler to Eventor. If the event is not ListboxVidget event, add the event handler to listbox widget. Notice this method overrides `Eventor.handler_add` in order to add non-ListboxVidget event handler to listbox widget. @param event: Event name. @param handler: Event handler. @param need_arg: Whether the event handler needs event argument. @return: None. """ # If the event is ListboxVidget event if event in self.EVENTS: # Add the event handler to Eventor return Eventor.handler_add( self, event=event, handler=handler, need_arg=need_arg, ) # If the event is not ListboxVidget event, # it is assumed to be Tkinter widget event. else: # Add the event handler to listbox widget return self.bind( event=event, handler=handler, ) def bind( self, event, handler, ): """ Add event handler to listbox widget. ListboxVidget internally uses `<Button-1>` and `<Double-Button-1>` to capture active index changes. So if the given event is `<Button-1>` or `<Double-Button-1>`, the given handler will be wrapped. @param event: Event name. @param handler: Event handler. @return: None. """ # If the event is not `<Button-1>` or `<Double-Button-1>` if event not in ['<Button-1>', '<Double-Button-1>']: # Add the event handler to listbox widget self._listbox.bind(event, handler) # If the event is `<Button-1>` or `<Double-Button-1>` else: # Create event handler wrapper def handler_wrapper(e): """ Event handler wrapper that sets new active index and then calls the wrapped event handler. Setting new active index is needed because when this handler is called by Tkinter, the active index of the listbox is still old. @param e: Tkinter event object. @return: None. """ # Set new active index self.indexcur_set_by_event(e, notify=True) # Call the wrapped event handler handler(e) # Add the event handler wrapper to the listbox widget self._listbox.bind(event, handler_wrapper) def _on_single_click(self, event): """ `<Button-1>` event handler that updates active index. @param event: Tkinter event object. @return: None. """ # Updates active index self.indexcur_set_by_event(event, notify=True) def _on_double_click(self, event): """ `<Double-Button-1>` event handler that updates active index. @param event: Tkinter event object. @return: None. """ # Updates active index self.indexcur_set_by_event(event, notify=True) def _listbox_widget_update( self, keep_active, ): """ Update listbox widget's items and selection. @param keep_active: Whether keep or clear active index. @return: None. """ # Remove old items from listbox widget self._listbox.delete(0, END) # Insert new items into listbox widget. # For each ListboxVidget items. for index, item in enumerate(self.items()): # Get item text item_text = self._item_to_text(item) # Insert the item text into listbox widget self._listbox.insert(index, item_text) # Set the item's normal background color self._listbox.itemconfig(index, background=self._normal_bg) # Set the item's normal foreground color self._listbox.itemconfig(index, foreground=self._normal_fg) # Set the item's selected background color self._listbox.itemconfig(index, selectbackground=self._selected_bg) # Set the item's selected foreground color self._listbox.itemconfig(index, selectforeground=self._selected_fg) # If keep active index if keep_active: # Use old active index indexcur = self._indexcur # If not keep active index else: # Set active index to -1 indexcur = self._indexcur = -1 # Clear old selection self._listbox.selection_clear(0, END) # Set new selection. # `-1` works. self._listbox.selection_set(indexcur) # Set new active index. # `-1` works. self._listbox.activate(indexcur) # If new active index is valid if indexcur != -1: # Set active background color self._listbox.itemconfig(indexcur, background=self._active_bg) # Set active foreground color self._listbox.itemconfig(indexcur, foreground=self._active_fg) # Make the active item visible self._listbox.see(indexcur)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent, background="#8080FF") self.parent = parent self.initUI() def initUI(self): self.parent.title("EQ GuildViewer 0.1") fontb = Font(size=12, weight="bold") # inicializo variables self.ant = None self.lastLine = 0 self.name = "" # frame padre area = Frame(self) area.pack(side=BOTTOM, fill=BOTH, expand=1) areab = Frame(self) areab.pack(side=TOP, fill=BOTH, expand=1) # scroll players self.scrollbar2 = Scrollbar(areab, orient=VERTICAL) # construimos un menu con todos los nombres del diccionario y un boton self.refreshButton = Button(areab, text="""PARSEA!""", command=self.onRefresh, bd=2, relief="groove") self.listboxLogs = Listbox( areab, width=50, activestyle="none", highlightthickness=0, yscrollcommand=self.scrollbar2.set, relief=RIDGE ) self.listboxLogs.pack(side=LEFT, fill=Y) self.scrollbar2.pack(side=LEFT, fill=Y) self.refreshButton.pack(side=LEFT, fill=BOTH, expand=1) for player in optionsDictionary: self.listboxLogs.insert(END, player) # scroll self.scrollbar = Scrollbar(area, orient=VERTICAL) self.scrollbar.pack(side=RIGHT, fill=Y) # area1 area1 = Frame(area) area1.pack(side=LEFT, fill=Y) lbl = Label(area1, text="Name") self.listbox = Listbox( area1, yscrollcommand=self.scrollbar.set, font=fontb, relief=FLAT, highlightthickness=0, activestyle="none" ) lbl.pack(side=TOP) self.listbox.pack(side=BOTTOM, fill=Y, expand=1) # area2 area2 = Frame(area) area2.pack(side=LEFT, fill=Y) lbl2 = Label(area2, text="Level") self.listbox2 = Listbox( area2, yscrollcommand=self.scrollbar.set, font=fontb, relief=FLAT, highlightthickness=0, activestyle="none" ) lbl2.pack(side=TOP) self.listbox2.pack(side=BOTTOM, fill=Y, expand=1) # area3 area3 = Frame(area) area3.pack(side=LEFT, fill=Y) lbl3 = Label(area3, text="Class") self.listbox3 = Listbox( area3, yscrollcommand=self.scrollbar.set, font=fontb, relief=FLAT, highlightthickness=0, activestyle="none" ) lbl3.pack(side=TOP) self.listbox3.pack(side=BOTTOM, fill=Y, expand=1) # area4 area4 = Frame(area) area4.pack(side=LEFT, fill=Y) lbl4 = Label(area4, text="Race") self.listbox4 = Listbox( area4, yscrollcommand=self.scrollbar.set, font=fontb, relief=FLAT, highlightthickness=0, activestyle="none" ) lbl4.pack(side=TOP) self.listbox4.pack(side=BOTTOM, fill=Y, expand=1) # area3 area5 = Frame(area) area5.pack(side=LEFT, fill=Y) lbl5 = Label(area5, text="Zone") self.listbox5 = Listbox( area5, yscrollcommand=self.scrollbar.set, font=fontb, relief=FLAT, highlightthickness=0, activestyle="none" ) lbl5.pack(side=TOP) self.listbox5.pack(side=BOTTOM, fill=Y, expand=1) self.pack(fill=BOTH, expand=1) # config-scrollbar self.scrollbar.config(command=self.yview) self.scrollbar2["command"] = self.listboxLogs.yview # bindeos de acciones self.listbox.bind("<<ListboxSelect>>", self.onSelect) self.listbox.bind("<MouseWheel>", self.onTest) self.listbox2.bind("<<ListboxSelect>>", self.onSelect) self.listbox2.bind("<MouseWheel>", self.onTest) self.listbox3.bind("<<ListboxSelect>>", self.onSelect) self.listbox3.bind("<MouseWheel>", self.onTest) self.listbox4.bind("<<ListboxSelect>>", self.onSelect) self.listbox4.bind("<MouseWheel>", self.onTest) self.listbox5.bind("<<ListboxSelect>>", self.onSelect) self.listbox5.bind("<MouseWheel>", self.onTest) self.listboxLogs.bind("<<ListboxSelect>>", self.onSelectPlayer) # mostrar la barra de scroll def yview(self, *args): self.listbox.yview(*args) self.listbox2.yview(*args) self.listbox3.yview(*args) self.listbox4.yview(*args) self.listbox5.yview(*args) # accion de la rueda del raton def onTest(self, val): return "break" # seleccionar un elementos de una listbox def onSelect(self, val): try: if self.ant != None: self.listbox.itemconfig(self.ant, background="#FFFFFF") self.listbox2.itemconfig(self.ant, background="#FFFFFF") self.listbox3.itemconfig(self.ant, background="#FFFFFF") self.listbox4.itemconfig(self.ant, background="#FFFFFF") self.listbox5.itemconfig(self.ant, background="#FFFFFF") self.listbox.itemconfig(val.widget.curselection(), background="#C0C0C0") self.listbox2.itemconfig(val.widget.curselection(), background="#C0C0C0") self.listbox3.itemconfig(val.widget.curselection(), background="#C0C0C0") self.listbox4.itemconfig(val.widget.curselection(), background="#C0C0C0") self.listbox5.itemconfig(val.widget.curselection(), background="#C0C0C0") self.ant = val.widget.curselection() except: None # print('No hay valores') # dependiendo de que nombre se elija en el menu cargamos en lastLine la linea de ese nombre del diccionario def onSelectPlayer(self, val): try: self.name = val.widget.get(val.widget.curselection()) self.lastLine = optionsDictionary[self.name] # print(self.name, ' ', self.lastLine) except: None # print('No hay valores') # recorremos el fichero log al clickar sobre el boton 'Refresh!' def onRefresh(self): if self.name != "": yes = False count = 0 dictionary = {} dictionaryAuxiliar = {} stringLog = "../eqlog_" + str(self.name) + "_project1999.txt" with open(stringLog, "r") as log: for i in range(int(self.lastLine)): next(log) count = count + 1 for line in log: match = re.match("\[.*\] \[(.*) (.*)\] (.*) \((.*)\) <.*> ZONE: (.*)", line) matchRole = re.match("\[.*\] \[(.*)\] (.*) <.*>", line) matchToken = re.match("\[.*\] You say, 't0000'", line) matchTokenI = re.match("\[.*\] You say, 't0001'", line) if matchTokenI != None: yes = True elif match != None and yes: dictionaryAuxiliar[match.group(3)] = ( match.group(1), match.group(2), match.group(4), match.group(5), ) elif matchRole != None and yes: dictionaryAuxiliar[matchRole.group(2)] = [(matchRole.group(1))] elif matchToken != None and yes: dictionary = dictionaryAuxiliar.copy() dictionaryAuxiliar.clear() yes = False count = count + 1 # bucle para sacar datos, primero eliminamos todo lo que haya self.listbox.delete(0, self.listbox.size()) self.listbox2.delete(0, self.listbox2.size()) self.listbox3.delete(0, self.listbox3.size()) self.listbox4.delete(0, self.listbox4.size()) self.listbox5.delete(0, self.listbox5.size()) for member in dictionary: self.listbox.insert(END, member) self.listbox2.insert(END, dictionary[member][0]) try: self.listbox3.insert(END, dictionary[member][1]) self.listbox4.insert(END, dictionary[member][2]) self.listbox5.insert(END, dictionary[member][3]) except IndexError as error: self.listbox3.insert(END, "-") self.listbox5.insert(END, "-") self.listbox4.insert(END, "-") # print(dictionary) # print('Longitud', len(dictionary)) # guardamos la linea ultima leida en el diccionario # self.lastLine = count # optionsDictionary[self.name] = count # print('Despues:', optionsDictionary) # guardamos el diccionario en el archivo options options = open("options.txt", "w") for player in optionsDictionary: options.write(str(player) + ":" + str(optionsDictionary[player])) options.close()
class ProblemBrowser(object): def __init__(self): self.action = None self.root = root = Tk() root.title('Never gonna fold you up') root.protocol("WM_DELETE_WINDOW", self.close) root.pack_propagate(True) scrollbar = Scrollbar(root, orient=tkinter.VERTICAL) self.problem_list = Listbox(root, exportselection=False, yscrollcommand=scrollbar.set) self.problem_list.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT) scrollbar.config(command=self.problem_list.yview) scrollbar.pack(side=tkinter.LEFT, fill=tkinter.Y) self.problem_list.bind('<<ListboxSelect>>', lambda evt: self.populate_problem_canvas()) self.problem_canvas = Canvas(root, bd=1, relief=tkinter.SUNKEN, width=500, height=500) self.problem_canvas.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT) self.problem_canvas.bind("<Configure>", lambda evt: self.populate_problem_canvas()) button_frame = Frame(root) button_frame.pack(fill=tkinter.Y, side=tkinter.LEFT) # Reposition the figure so it's center of mass is at 0.5, 0.5 v = IntVar() self.center_cb = Checkbutton(button_frame, text="center", variable=v, command=lambda: self.populate_problem_canvas()) self.center_cb.var = v self.center_cb.pack(side=tkinter.TOP) # Use meshes.reconstruct_facets instead of polygon/hole logic. v = IntVar() self.reconstruct_cb = Checkbutton(button_frame, text="reconstruct", variable=v, command=lambda: self.populate_problem_canvas()) self.reconstruct_cb.var = v self.reconstruct_cb.pack(side=tkinter.TOP) self.populate_problems() self.current_problem_name = None self.current_problem = None def populate_problems(self): self.problem_list.delete(0, tkinter.END) for file in sorted((get_root() / 'problems').iterdir()): self.problem_list.insert(tkinter.END, file.stem) def populate_problem_canvas(self): sel = self.problem_list.curselection() if not sel: return assert len(sel) == 1 name = self.problem_list.get(sel[0]) if name != self.current_problem_name: self.current_problem_name = name self.current_problem = load_problem(name) if self.current_problem: p = self.current_problem if self.center_cb.var.get(): p = center_problem(p) if self.reconstruct_cb.var.get(): facets = meshes.reconstruct_facets(p) facets = meshes.keep_real_facets(facets, p) skeleton = [e for f in facets for e in edges_of_a_facet(f)] p = Problem(facets, skeleton) draw_problem(self.problem_canvas, p) def run(self): self.root.mainloop() def close(self): if self.root: self.root.destroy() self.root = None
def __init__(self, master, columns, column_weights=None, cnf={}, **kw): """ Construct a new multi-column listbox widget. :param master: The widget that should contain the new multi-column listbox. :param columns: Specifies what columns should be included in the new multi-column listbox. If ``columns`` is an integer, the it is the number of columns to include. If it is a list, then its length indicates the number of columns to include; and each element of the list will be used as a label for the corresponding column. :param cnf, kw: Configuration parameters for this widget. Use ``label_*`` to configure all labels; and ``listbox_*`` to configure all listboxes. E.g.: >>> mlb = MultiListbox(master, 5, label_foreground='red') """ # If columns was specified as an int, convert it to a list. if isinstance(columns, int): columns = list(range(columns)) include_labels = False else: include_labels = True if len(columns) == 0: raise ValueError("Expected at least one column") # Instance variables self._column_names = tuple(columns) self._listboxes = [] self._labels = [] # Pick a default value for column_weights, if none was specified. if column_weights is None: column_weights = [1] * len(columns) elif len(column_weights) != len(columns): raise ValueError('Expected one column_weight for each column') self._column_weights = column_weights # Configure our widgets. Frame.__init__(self, master, **self.FRAME_CONFIG) self.grid_rowconfigure(1, weight=1) for i, label in enumerate(self._column_names): self.grid_columnconfigure(i, weight=column_weights[i]) # Create a label for the column if include_labels: l = Label(self, text=label, **self.LABEL_CONFIG) self._labels.append(l) l.grid(column=i, row=0, sticky='news', padx=0, pady=0) l.column_index = i # Create a listbox for the column lb = Listbox(self, **self.LISTBOX_CONFIG) self._listboxes.append(lb) lb.grid(column=i, row=1, sticky='news', padx=0, pady=0) lb.column_index = i # Clicking or dragging selects: lb.bind('<Button-1>', self._select) lb.bind('<B1-Motion>', self._select) # Scroll whell scrolls: lb.bind('<Button-4>', lambda e: self._scroll(-1)) lb.bind('<Button-5>', lambda e: self._scroll(+1)) lb.bind('<MouseWheel>', lambda e: self._scroll(e.delta)) # Button 2 can be used to scan: lb.bind('<Button-2>', lambda e: self.scan_mark(e.x, e.y)) lb.bind('<B2-Motion>', lambda e: self.scan_dragto(e.x, e.y)) # Dragging outside the window has no effect (diable # the default listbox behavior, which scrolls): lb.bind('<B1-Leave>', lambda e: 'break') # Columns can be resized by dragging them: l.bind('<Button-1>', self._resize_column) # Columns can be resized by dragging them. (This binding is # used if they click on the grid between columns:) self.bind('<Button-1>', self._resize_column) # Set up key bindings for the widget: self.bind('<Up>', lambda e: self.select(delta=-1)) self.bind('<Down>', lambda e: self.select(delta=1)) self.bind('<Prior>', lambda e: self.select(delta=-self._pagesize())) self.bind('<Next>', lambda e: self.select(delta=self._pagesize())) # Configuration customizations self.configure(cnf, **kw)
def second_window(root, info): def next_step(): idxs = lbox.curselection() for blogger in idxs: name = bloggers()[blogger] if name not in info['bloggers']: info['bloggers'].append(name) if 'Blogs' in info['platforms']: blog_posts(root, info) else: third_window(root, info) def cantfind(info=info): idxs = lbox.curselection() for blogger in idxs: name = bloggers()[blogger] if name not in info['bloggers']: info['bloggers'].append(name) add_blogger(info=info) def active_next(*args): send.state(['!disabled', 'active']) def back(): idxs = lbox.curselection() for blogger in idxs: name = bloggers()[blogger] if name not in info['bloggers']: info['bloggers'].append(name) first_window(root, info=info) c = ttk.Frame(root, padding=(5, 0, 0, 0)) c.grid(column=0, row=0, sticky=(N, W, E, S)) background_image = tkinter.PhotoImage(file='%s/Desktop/natappy/images/moon.gif' % home) background_label = tkinter.Label(c, image=background_image) background_label.image = background_image background_label.place(x=0, y=0, relwidth=1, relheight=1) root.grid_columnconfigure(0, weight=3) root.grid_rowconfigure(0, weight=3) lbox = Listbox(c, selectmode=MULTIPLE) lbox.grid(column=0, row=1, rowspan=11, columnspan=7, sticky=( N, W, S), padx=(10, 10), pady=(1, 1), ipadx=75) yscroll = ttk.Scrollbar(command=lbox.yview, orient=VERTICAL) yscroll.grid(row=0, column=0, padx=(0, 10), sticky=(N, W, S)) lbox.configure(yscrollcommand=yscroll.set) for blogger in bloggers(): lbox.insert(END, blogger) lbox.bind("<<ListboxSelect>>") lbox.yview_scroll(40, 'units') cantfind = ttk.Button(c, text='Add new bloggers', command=cantfind) cantfind.grid(column=4, row=1, padx=(10, 0), sticky=(N, S, E, W), pady=(20, 10)) send = ttk.Button(c, text='Next', command=next_step, default='active', state='disabled') send.grid(column=6, row=11, sticky=E, pady=20, padx=(2, 20)) close = ttk.Button(c, text='Back', command=back, default='active') close.grid(column=5, row=11, sticky=S + E, pady=20, padx=2) lbox.bind('<<ListboxSelect>>', active_next) if info['bloggers']: for blogger in info['bloggers']: i = bloggers().index(blogger) lbox.selection_set(i) active_next() for i in range(len(bloggers()), 2): lbox.itemconfigure(i, background='#f0f0ff') c.grid_columnconfigure(0, weight=1) c.grid_rowconfigure(5, weight=1) root.title('2/5 Select bloggers') root.geometry('680x550+300+40')
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 = tkinter.font.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 = tkinter.font.Font(family='helvetica', weight='bold', size=self._size.get()) self._font = tkinter.font.Font(family='helvetica', size=self._size.get()) if self._size.get() < 0: big = self._size.get()-2 else: big = self._size.get()+2 self._bigfont = tkinter.font.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.label() 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().label().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 tkinter.messagebox 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.label()['color'] = '#20a050' (oldx, oldy) = oldtree.label().bbox()[:2] (newx, newy) = widget.label().bbox()[:2] widget.move(oldx-newx, oldy-newy) if top: self._cframe.add_widget(widget, 0, 5) widget.move(30-widget.label().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.label().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.label()['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.label()['color'] = 'black' else: subtree['color'] = 'black' self._redraw_quick() widget.label()['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.label()) 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().label() 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 Controller: SNAP_RADIUS = 5 def __init__(self, tk: Tk): tk.title("Layered Polygons") menubar = Menu(tk) menu_file = Menu(menubar, tearoff=0) menu_file.add_command(label="New...", command=self._new_scene) menu_file.add_command(label="Open...", command=self._open_scene) menu_file.add_separator() menu_file.add_command(label="Save", command=self._save_scene) menu_file.add_command(label="Save As...", command=self._save_scene_as) menu_file.add_separator() menu_export = Menu(menu_file, tearoff=0) menu_export.add_command(label="Wavefront (.obj)...", command=self._export_obj) menu_file.add_cascade(label="Export As", menu=menu_export) menu_file.add_separator() menu_file.add_command(label="Quit", command=self._quit_app) menubar.add_cascade(label="File", menu=menu_file) tk.config(menu=menubar) paned = PanedWindow(tk, relief=RAISED) paned.pack(fill=BOTH, expand=1) frame = Frame(paned) paned.add(frame) self._canvas = LayPolyCanvas(frame) bar_x = Scrollbar(frame, orient=HORIZONTAL) bar_x.pack(side=BOTTOM, fill=X) bar_x.config(command=self._canvas.xview) bar_y = Scrollbar(frame, orient=VERTICAL) bar_y.pack(side=RIGHT, fill=Y) bar_y.config(command=self._canvas.yview) self._canvas.config(xscrollcommand=bar_x.set, yscrollcommand=bar_y.set) self._canvas.pack(side=LEFT, expand=True, fill=BOTH) # Thanks to the two guys on Stack Overflow for that! # ( http://stackoverflow.com/a/7734187 ) self._layer_list = Listbox(paned, selectmode=SINGLE) paned.add(self._layer_list) self._scene = None self._current_layer = None self._is_drawing_polygon = False self._tk = tk self._canvas.bind("<Button-1>", self._canvas_left_click) self._canvas.bind("<Button-3>", self._canvas_right_click) self._canvas.bind("<Motion>", self._canvas_mouse_moved) self._layer_list.bind("<<ListboxSelect>>", self._layer_change) self._current_path = None def _canvas_left_click(self, event): if not self._scene or not self._current_layer: return x, y = self._canvas.window_to_canvas_coords(event.x, event.y) if self._is_drawing_polygon: polygon = self._current_layer.get_polygon_at(-1) # Move vtx away from mouse to not interfere with search for closest polygon.get_vertex_at(-1).\ set_coords(x-self.SNAP_RADIUS, y-self.SNAP_RADIUS) closest_vertex = self._current_layer.get_closest_vertex( x, y, self.SNAP_RADIUS) if closest_vertex: polygon.remove_vertex_at(-1) if closest_vertex is polygon.get_vertex_at(0): self._is_drawing_polygon = False else: polygon.add_vertex(closest_vertex) polygon.add_vertex(Vertex(x, y)) else: polygon.get_vertex_at(-1)\ .set_coords(x, y) polygon.add_vertex(Vertex(x, y)) self._canvas.notify_polygon_change(self._current_layer .get_polygon_count()-1) else: # Create start vertex or use already existing one start_vertex = self._current_layer\ .get_closest_vertex(x, y, self.SNAP_RADIUS) if not start_vertex: start_vertex = Vertex(x, y) # Vertex for mouse cursor next_vertex = Vertex(x, y) self._current_layer.add_polygon( Polygon([start_vertex, next_vertex])) self._is_drawing_polygon = True self._canvas.notify_layer_change() def _canvas_right_click(self, event): if not self._current_layer: return if self._is_drawing_polygon: self._current_layer.remove_polygon_at(-1) self._is_drawing_polygon = False else: x, y = self._canvas.window_to_canvas_coords(event.x, event.y) for i in range(0, self._current_layer.get_polygon_count()): if self._current_layer.get_polygon_at(i).contains(x, y): self._current_layer.remove_polygon_at(i) break self._canvas.notify_layer_change() def _canvas_mouse_moved(self, event): if self._is_drawing_polygon: x, y = self._canvas.window_to_canvas_coords(event.x, event.y) self._current_layer.get_polygon_at(-1).get_vertex_at(-1)\ .set_coords(x, y) self._canvas.notify_polygon_change(self._current_layer .get_polygon_count()-1) def _layer_change(self, event): selection = self._layer_list.curselection() if len(selection) > 0 and self._scene: layer = self._scene.get_layer_at(selection[0]) if layer: self._is_drawing_polygon = False self._current_layer = layer self._canvas.notify_new_layer(self._current_layer) def _set_scene(self, scene: Scene) -> bool: if scene.get_layer_count() <= 0: messagebox.showerror("Error!", "Scene has no layers!") return False self._scene = scene # Prepare canvas # TODO Extra 10px padding for canvas width, height = self._scene.get_size() self._canvas.config(scrollregion=(0, 0, width, height)) # Empty listbox, fill it, select first entry self._layer_list.delete(0, self._layer_list.size()-1) for i in range(0, self._scene.get_layer_count()): self._layer_list.insert(i, self._scene.get_layer_at(i).get_name()) self._layer_list.selection_set(0) self._layer_list.event_generate("<<ListboxSelect>>") return True def _set_current_path(self, path): self._current_path = path if path: self._tk.title(path + " - Layered Polygons") else: self._tk.title("Untitled - Layered Polygons") def _new_scene(self): path = filedialog.askopenfilename(defaultextension=".ora", filetypes=[("OpenRaster files", ".ora")]) if not path: return scene = ora.read(path) if not scene: messagebox.showerror("Error!", "File could not be opened!") return if self._set_scene(scene): self._set_current_path(None) def _open_scene(self): path = filedialog.askopenfilename(defaultextension=".lp", filetypes=[("Layered polygons" " files", ".lp")]) if not path: return scene = lp.read(path) if not scene: messagebox.showerror("Error!", "File could not be opened!") return if self._set_scene(scene): self._set_current_path(path) def _save_scene_help(self, path): if lp.save(path, self._scene): self._set_current_path(path) else: messagebox.showerror("Error!", "File could not be saved!") def _save_scene(self): if not self._current_path: self._save_scene_as() return self._save_scene_help(self._current_path) def _save_scene_as(self): if not self._scene: return path = filedialog.asksaveasfilename(defaultextension=".lp", filetypes=[("Layered polygons" " files", ".lp")]) if path: self._save_scene_help(path) def _export_obj(self): if not self._scene: return path_obj = filedialog.asksaveasfilename(defaultextension=".obj", filetypes=[("Wavefront object" " files", ".obj")]) if not path_obj: return path_obj, path_mtl, path_data = obj.get_paths(path_obj) obj.save(path_obj, path_mtl, path_data, self._scene) def _quit_app(self): self._tk.quit() exit()
class Searcher(Frame): """ Keyword Searcher This is a very simple python program, which is designed for finding specified key-word in files. Just for fun! """ def __init__(self, master=None, cnf={}, **kwargs): super(Searcher, self).__init__(master, cnf, **kwargs) self._root_path_var = StringVar() self._keyword_var = StringVar(self) self._listbox = None self._result_queue = None self.pack(fill=BOTH, expand=YES, padx=5, pady=5) self.make_widgets() self._consumer() # config for main window self.master.title('Keyword Searcher') def make_widgets(self): frm1 = Frame(self) frm1.pack(side=TOP, fill=X) Entry(frm1, textvariable=self._root_path_var, font=DEFAULT_FONT).pack(side=LEFT, fill=X, expand=YES) Button(frm1, text='Add directory', font=DEFAULT_FONT, command=lambda: self._root_path_var.set(askdirectory(title='Add directory'))).pack(side=RIGHT) frm2 = Frame(self) frm2.pack(side=TOP, fill=X) keyword_ent = Entry(frm2, textvariable=self._keyword_var, font=DEFAULT_FONT) keyword_ent.pack(side=LEFT, fill=X, expand=YES) Button(frm2, text='Find', font=DEFAULT_FONT, command=self.find).pack(side=RIGHT) vs = Scrollbar(self) hs = Scrollbar(self) self._listbox = Listbox(self) vs.pack(side=RIGHT, fill=Y) vs.config(command=self._listbox.yview) hs.pack(side=BOTTOM, fill=X) hs.config(command=self._listbox.xview, orient='horizontal') self._listbox.config(yscrollcommand=vs.set, xscrollcommand=hs.set, font=DEFAULT_FONT) self._listbox.pack(fill=BOTH, expand=YES) self._listbox.bind('<Double-1>', self._navigate_to) def find(self): self._result_queue = queue.Queue() self._listbox.delete('0', 'end') Thread(target=self._find, args=(self._root_path_var.get(), self._keyword_var.get()), daemon=True).start() def _find(self, path, keyword): if not os.path.exists(path): return None for this_dir, sub_dirs, files in os.walk(path): for file in files: file_type = guess_type(file)[0] if file_type and 'text' in file_type: fp = os.path.join(this_dir, file) self._result_queue.put(fp) if keyword in open(fp).read() else None def _consumer(self): if self._result_queue: try: fp = self._result_queue.get(block=False) except queue.Empty: pass else: self._listbox.insert('end', fp) # auto scroll. self._listbox.yview('end') self.after(100, self._consumer) def _navigate_to(self, event): """ Only works on Ubuntu platform currently. Double click to navigate to selected path. It's a very convenient function. :return: None """ print(event) # get active item from listbox path = self._listbox.get('active') print(path) # open nautilus with param path, before that, check your platform. if 'ubuntu' in (os.popen('uname -a').read()).lower(): os.system('/usr/bin/nautilus {}'.format(path)) else: pass
class ShiftReduceApp(object): """ A graphical tool for exploring the shift-reduce parser. The tool displays the parser's stack and the remaining text, and allows the user to control the parser's operation. In particular, the user can shift tokens onto the stack, and can perform reductions on the top elements of the stack. A "step" button simply steps through the parsing process, performing the operations that ``nltk.parse.ShiftReduceParser`` would use. """ def __init__(self, grammar, sent, trace=0): self._sent = sent self._parser = SteppingShiftReduceParser(grammar, trace) # Set up the main window. self._top = Tk() self._top.title('Shift Reduce Parser Application') # Animations. animating_lock is a lock to prevent the demo # from performing new operations while it's animating. self._animating_lock = 0 self._animate = IntVar(self._top) self._animate.set(10) # = medium # The user can hide the grammar. self._show_grammar = IntVar(self._top) self._show_grammar.set(1) # Initialize fonts. self._init_fonts(self._top) # Set up key bindings. self._init_bindings() # Create the basic frames. self._init_menubar(self._top) self._init_buttons(self._top) self._init_feedback(self._top) self._init_grammar(self._top) self._init_canvas(self._top) # A popup menu for reducing. self._reduce_menu = Menu(self._canvas, tearoff=0) # Reset the demo, and set the feedback frame to empty. self.reset() self._lastoper1['text'] = '' ######################################### ## Initialization Helpers ######################################### def _init_fonts(self, root): # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html> self._sysfont = tkinter.font.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 = tkinter.font.Font(family='helvetica', weight='bold', size=self._size.get()) self._font = tkinter.font.Font(family='helvetica', size=self._size.get()) def _init_grammar(self, parent): # Grammar view. self._prodframe = listframe = Frame(parent) self._prodframe.pack(fill='both', side='left', padx=2) self._prodlist_label = Label(self._prodframe, font=self._boldfont, text='Available Reductions') self._prodlist_label.pack() self._prodlist = Listbox(self._prodframe, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._prodlist.pack(side='right', fill='both', expand=1) self._productions = list(self._parser.grammar().productions()) for production in self._productions: self._prodlist.insert('end', (' %s' % production)) self._prodlist.config(height=min(len(self._productions), 25)) # Add a scrollbar if there are more than 25 productions. if 1:#len(self._productions) > 25: listscroll = Scrollbar(self._prodframe, orient='vertical') self._prodlist.config(yscrollcommand = listscroll.set) listscroll.config(command=self._prodlist.yview) listscroll.pack(side='left', fill='y') # If they select a production, apply it. self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select) # When they hover over a production, highlight it. self._hover = -1 self._prodlist.bind('<Motion>', self._highlight_hover) self._prodlist.bind('<Leave>', self._clear_hover) def _init_bindings(self): # Quit self._top.bind('<Control-q>', self.destroy) self._top.bind('<Control-x>', self.destroy) self._top.bind('<Alt-q>', self.destroy) self._top.bind('<Alt-x>', self.destroy) # Ops (step, shift, reduce, undo) self._top.bind('<space>', self.step) self._top.bind('<s>', self.shift) self._top.bind('<Alt-s>', self.shift) self._top.bind('<Control-s>', self.shift) self._top.bind('<r>', self.reduce) self._top.bind('<Alt-r>', self.reduce) self._top.bind('<Control-r>', self.reduce) self._top.bind('<Delete>', self.reset) self._top.bind('<u>', self.undo) self._top.bind('<Alt-u>', self.undo) self._top.bind('<Control-u>', self.undo) self._top.bind('<Control-z>', self.undo) self._top.bind('<BackSpace>', self.undo) # Misc self._top.bind('<Control-p>', self.postscript) self._top.bind('<Control-h>', self.help) self._top.bind('<F1>', self.help) self._top.bind('<Control-g>', self.edit_grammar) self._top.bind('<Control-t>', self.edit_sentence) # Animation speed control self._top.bind('-', lambda e,a=self._animate:a.set(20)) self._top.bind('=', lambda e,a=self._animate:a.set(10)) self._top.bind('+', lambda e,a=self._animate:a.set(4)) def _init_buttons(self, parent): # Set up the frames. self._buttonframe = buttonframe = Frame(parent) buttonframe.pack(fill='none', side='bottom') Button(buttonframe, text='Step', background='#90c0d0', foreground='black', command=self.step,).pack(side='left') Button(buttonframe, text='Shift', underline=0, background='#90f090', foreground='black', command=self.shift).pack(side='left') Button(buttonframe, text='Reduce', underline=0, background='#90f090', foreground='black', command=self.reduce).pack(side='left') Button(buttonframe, text='Undo', underline=0, background='#f0a0a0', foreground='black', command=self.undo).pack(side='left') def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label='Reset Parser', underline=0, command=self.reset, accelerator='Del') filemenu.add_command(label='Print to Postscript', underline=0, command=self.postscript, accelerator='Ctrl-p') filemenu.add_command(label='Exit', underline=1, command=self.destroy, accelerator='Ctrl-x') menubar.add_cascade(label='File', underline=0, menu=filemenu) editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label='Edit Grammar', underline=5, command=self.edit_grammar, accelerator='Ctrl-g') editmenu.add_command(label='Edit Text', underline=5, command=self.edit_sentence, accelerator='Ctrl-t') menubar.add_cascade(label='Edit', underline=0, menu=editmenu) rulemenu = Menu(menubar, tearoff=0) rulemenu.add_command(label='Step', underline=1, command=self.step, accelerator='Space') rulemenu.add_separator() rulemenu.add_command(label='Shift', underline=0, command=self.shift, accelerator='Ctrl-s') rulemenu.add_command(label='Reduce', underline=0, command=self.reduce, accelerator='Ctrl-r') rulemenu.add_separator() rulemenu.add_command(label='Undo', underline=0, command=self.undo, accelerator='Ctrl-u') menubar.add_cascade(label='Apply', underline=0, menu=rulemenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_checkbutton(label="Show Grammar", underline=0, variable=self._show_grammar, command=self._toggle_grammar) viewmenu.add_separator() viewmenu.add_radiobutton(label='Tiny', variable=self._size, underline=0, value=10, command=self.resize) viewmenu.add_radiobutton(label='Small', variable=self._size, underline=0, value=12, command=self.resize) viewmenu.add_radiobutton(label='Medium', variable=self._size, underline=0, value=14, command=self.resize) viewmenu.add_radiobutton(label='Large', variable=self._size, underline=0, value=18, command=self.resize) viewmenu.add_radiobutton(label='Huge', variable=self._size, underline=0, value=24, command=self.resize) menubar.add_cascade(label='View', underline=0, menu=viewmenu) animatemenu = Menu(menubar, tearoff=0) animatemenu.add_radiobutton(label="No Animation", underline=0, variable=self._animate, value=0) animatemenu.add_radiobutton(label="Slow Animation", underline=0, variable=self._animate, value=20, accelerator='-') animatemenu.add_radiobutton(label="Normal Animation", underline=0, variable=self._animate, value=10, accelerator='=') animatemenu.add_radiobutton(label="Fast Animation", underline=0, variable=self._animate, value=4, accelerator='+') menubar.add_cascade(label="Animate", underline=1, menu=animatemenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label='About', underline=0, command=self.about) helpmenu.add_command(label='Instructions', underline=0, command=self.help, accelerator='F1') menubar.add_cascade(label='Help', underline=0, menu=helpmenu) parent.config(menu=menubar) def _init_feedback(self, parent): self._feedbackframe = feedbackframe = Frame(parent) feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3) self._lastoper_label = Label(feedbackframe, text='Last Operation:', font=self._font) self._lastoper_label.pack(side='left') lastoperframe = Frame(feedbackframe, relief='sunken', border=1) lastoperframe.pack(fill='x', side='right', expand=1, padx=5) self._lastoper1 = Label(lastoperframe, foreground='#007070', background='#f0f0f0', font=self._font) self._lastoper2 = Label(lastoperframe, anchor='w', width=30, foreground='#004040', background='#f0f0f0', font=self._font) self._lastoper1.pack(side='left') self._lastoper2.pack(side='left', fill='x', expand=1) def _init_canvas(self, parent): self._cframe = CanvasFrame(parent, background='white', width=525, closeenough=10, border=2, relief='sunken') self._cframe.pack(expand=1, fill='both', side='top', pady=2) canvas = self._canvas = self._cframe.canvas() self._stackwidgets = [] self._rtextwidgets = [] self._titlebar = canvas.create_rectangle(0,0,0,0, fill='#c0f0f0', outline='black') self._exprline = canvas.create_line(0,0,0,0, dash='.') self._stacktop = canvas.create_line(0,0,0,0, fill='#408080') size = self._size.get()+4 self._stacklabel = TextWidget(canvas, 'Stack', color='#004040', font=self._boldfont) self._rtextlabel = TextWidget(canvas, 'Remaining Text', color='#004040', font=self._boldfont) self._cframe.add_widget(self._stacklabel) self._cframe.add_widget(self._rtextlabel) ######################################### ## Main draw procedure ######################################### def _redraw(self): scrollregion = self._canvas['scrollregion'].split() (cx1, cy1, cx2, cy2) = [int(c) for c in scrollregion] # Delete the old stack & rtext widgets. for stackwidget in self._stackwidgets: self._cframe.destroy_widget(stackwidget) self._stackwidgets = [] for rtextwidget in self._rtextwidgets: self._cframe.destroy_widget(rtextwidget) self._rtextwidgets = [] # Position the titlebar & exprline (x1, y1, x2, y2) = self._stacklabel.bbox() y = y2-y1+10 self._canvas.coords(self._titlebar, -5000, 0, 5000, y-4) self._canvas.coords(self._exprline, 0, y*2-10, 5000, y*2-10) # Position the titlebar labels.. (x1, y1, x2, y2) = self._stacklabel.bbox() self._stacklabel.move(5-x1, 3-y1) (x1, y1, x2, y2) = self._rtextlabel.bbox() self._rtextlabel.move(cx2-x2-5, 3-y1) # Draw the stack. stackx = 5 for tok in self._parser.stack(): if isinstance(tok, Tree): attribs = {'tree_color': '#4080a0', 'tree_width': 2, 'node_font': self._boldfont, 'node_color': '#006060', 'leaf_color': '#006060', 'leaf_font':self._font} widget = tree_to_treesegment(self._canvas, tok, **attribs) widget.label()['color'] = '#000000' else: widget = TextWidget(self._canvas, tok, color='#000000', font=self._font) widget.bind_click(self._popup_reduce) self._stackwidgets.append(widget) self._cframe.add_widget(widget, stackx, y) stackx = widget.bbox()[2] + 10 # Draw the remaining text. rtextwidth = 0 for tok in self._parser.remaining_text(): widget = TextWidget(self._canvas, tok, color='#000000', font=self._font) self._rtextwidgets.append(widget) self._cframe.add_widget(widget, rtextwidth, y) rtextwidth = widget.bbox()[2] + 4 # Allow enough room to shift the next token (for animations) if len(self._rtextwidgets) > 0: stackx += self._rtextwidgets[0].width() # Move the remaining text to the correct location (keep it # right-justified, when possible); and move the remaining text # label, if necessary. stackx = max(stackx, self._stacklabel.width()+25) rlabelwidth = self._rtextlabel.width()+10 if stackx >= cx2-max(rtextwidth, rlabelwidth): cx2 = stackx + max(rtextwidth, rlabelwidth) for rtextwidget in self._rtextwidgets: rtextwidget.move(4+cx2-rtextwidth, 0) self._rtextlabel.move(cx2-self._rtextlabel.bbox()[2]-5, 0) midx = (stackx + cx2-max(rtextwidth, rlabelwidth))/2 self._canvas.coords(self._stacktop, midx, 0, midx, 5000) (x1, y1, x2, y2) = self._stacklabel.bbox() # Set up binding to allow them to shift a token by dragging it. if len(self._rtextwidgets) > 0: def drag_shift(widget, midx=midx, self=self): if widget.bbox()[0] < midx: self.shift() else: self._redraw() self._rtextwidgets[0].bind_drag(drag_shift) self._rtextwidgets[0].bind_click(self.shift) # Draw the stack top. self._highlight_productions() def _draw_stack_top(self, widget): # hack.. midx = widget.bbox()[2]+50 self._canvas.coords(self._stacktop, midx, 0, midx, 5000) def _highlight_productions(self): # Highlight the productions that can be reduced. self._prodlist.selection_clear(0, 'end') for prod in self._parser.reducible_productions(): index = self._productions.index(prod) self._prodlist.selection_set(index) ######################################### ## Button Callbacks ######################################### def destroy(self, *e): if self._top is None: return self._top.destroy() self._top = None def reset(self, *e): self._parser.initialize(self._sent) self._lastoper1['text'] = 'Reset App' self._lastoper2['text'] = '' self._redraw() def step(self, *e): if self.reduce(): return True elif self.shift(): return True else: if list(self._parser.parses()): self._lastoper1['text'] = 'Finished:' self._lastoper2['text'] = 'Success' else: self._lastoper1['text'] = 'Finished:' self._lastoper2['text'] = 'Failure' def shift(self, *e): if self._animating_lock: return if self._parser.shift(): tok = self._parser.stack()[-1] self._lastoper1['text'] = 'Shift:' self._lastoper2['text'] = '%r' % tok if self._animate.get(): self._animate_shift() else: self._redraw() return True return False def reduce(self, *e): if self._animating_lock: return production = self._parser.reduce() if production: self._lastoper1['text'] = 'Reduce:' self._lastoper2['text'] = '%s' % production if self._animate.get(): self._animate_reduce() else: self._redraw() return production def undo(self, *e): if self._animating_lock: return if self._parser.undo(): self._redraw() def postscript(self, *e): self._cframe.print_to_file() def mainloop(self, *args, **kwargs): """ Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes. """ if in_idle(): return self._top.mainloop(*args, **kwargs) ######################################### ## Menubar callbacks ######################################### def resize(self, size=None): if size is not None: self._size.set(size) size = self._size.get() self._font.configure(size=-(abs(size))) self._boldfont.configure(size=-(abs(size))) self._sysfont.configure(size=-(abs(size))) #self._stacklabel['font'] = ('helvetica', -size-4, 'bold') #self._rtextlabel['font'] = ('helvetica', -size-4, 'bold') #self._lastoper_label['font'] = ('helvetica', -size) #self._lastoper1['font'] = ('helvetica', -size) #self._lastoper2['font'] = ('helvetica', -size) #self._prodlist['font'] = ('helvetica', -size) #self._prodlist_label['font'] = ('helvetica', -size-2, 'bold') self._redraw() def help(self, *e): # The default font's not very legible; try using 'fixed' instead. try: ShowText(self._top, 'Help: Shift-Reduce Parser Application', (__doc__ or '').strip(), width=75, font='fixed') except: ShowText(self._top, 'Help: Shift-Reduce Parser Application', (__doc__ or '').strip(), width=75) def about(self, *e): ABOUT = ("NLTK Shift-Reduce Parser Application\n"+ "Written by Edward Loper") TITLE = 'About: Shift-Reduce Parser Application' try: from tkinter.messagebox import Message Message(message=ABOUT, title=TITLE).show() except: ShowText(self._top, TITLE, ABOUT) def edit_grammar(self, *e): CFGEditor(self._top, self._parser.grammar(), self.set_grammar) def set_grammar(self, grammar): self._parser.set_grammar(grammar) self._productions = list(grammar.productions()) self._prodlist.delete(0, 'end') for production in self._productions: self._prodlist.insert('end', (' %s' % production)) def edit_sentence(self, *e): sentence = " ".join(self._sent) title = 'Edit Text' instr = 'Enter a new sentence to parse.' EntryDialog(self._top, sentence, instr, self.set_sentence, title) def set_sentence(self, sent): self._sent = sent.split() #[XX] use tagged? self.reset() ######################################### ## Reduce Production Selection ######################################### def _toggle_grammar(self, *e): if self._show_grammar.get(): self._prodframe.pack(fill='both', side='left', padx=2, after=self._feedbackframe) self._lastoper1['text'] = 'Show Grammar' else: self._prodframe.pack_forget() self._lastoper1['text'] = 'Hide Grammar' self._lastoper2['text'] = '' def _prodlist_select(self, event): selection = self._prodlist.curselection() if len(selection) != 1: return index = int(selection[0]) production = self._parser.reduce(self._productions[index]) if production: self._lastoper1['text'] = 'Reduce:' self._lastoper2['text'] = '%s' % production if self._animate.get(): self._animate_reduce() else: self._redraw() else: # Reset the production selections. self._prodlist.selection_clear(0, 'end') for prod in self._parser.reducible_productions(): index = self._productions.index(prod) self._prodlist.selection_set(index) def _popup_reduce(self, widget): # Remove old commands. productions = self._parser.reducible_productions() if len(productions) == 0: return self._reduce_menu.delete(0, 'end') for production in productions: self._reduce_menu.add_command(label=str(production), command=self.reduce) self._reduce_menu.post(self._canvas.winfo_pointerx(), self._canvas.winfo_pointery()) ######################################### ## Animations ######################################### def _animate_shift(self): # What widget are we shifting? widget = self._rtextwidgets[0] # Where are we shifting from & to? right = widget.bbox()[0] if len(self._stackwidgets) == 0: left = 5 else: left = self._stackwidgets[-1].bbox()[2]+10 # Start animating. dt = self._animate.get() dx = (left-right)*1.0/dt self._animate_shift_frame(dt, widget, dx) def _animate_shift_frame(self, frame, widget, dx): if frame > 0: self._animating_lock = 1 widget.move(dx, 0) self._top.after(10, self._animate_shift_frame, frame-1, widget, dx) else: # but: stacktop?? # Shift the widget to the stack. del self._rtextwidgets[0] self._stackwidgets.append(widget) self._animating_lock = 0 # Display the available productions. self._draw_stack_top(widget) self._highlight_productions() def _animate_reduce(self): # What widgets are we shifting? numwidgets = len(self._parser.stack()[-1]) # number of children widgets = self._stackwidgets[-numwidgets:] # How far are we moving? if isinstance(widgets[0], TreeSegmentWidget): ydist = 15 + widgets[0].label().height() else: ydist = 15 + widgets[0].height() # Start animating. dt = self._animate.get() dy = ydist*2.0/dt self._animate_reduce_frame(dt/2, widgets, dy) def _animate_reduce_frame(self, frame, widgets, dy): if frame > 0: self._animating_lock = 1 for widget in widgets: widget.move(0, dy) self._top.after(10, self._animate_reduce_frame, frame-1, widgets, dy) else: del self._stackwidgets[-len(widgets):] for widget in widgets: self._cframe.remove_widget(widget) tok = self._parser.stack()[-1] if not isinstance(tok, Tree): raise ValueError() label = TextWidget(self._canvas, str(tok.label()), color='#006060', font=self._boldfont) widget = TreeSegmentWidget(self._canvas, label, widgets, width=2) (x1, y1, x2, y2) = self._stacklabel.bbox() y = y2-y1+10 if not self._stackwidgets: x = 5 else: x = self._stackwidgets[-1].bbox()[2] + 10 self._cframe.add_widget(widget, x, y) self._stackwidgets.append(widget) # Display the available productions. self._draw_stack_top(widget) self._highlight_productions() # # Delete the old widgets.. # del self._stackwidgets[-len(widgets):] # for widget in widgets: # self._cframe.destroy_widget(widget) # # # Make a new one. # tok = self._parser.stack()[-1] # if isinstance(tok, Tree): # attribs = {'tree_color': '#4080a0', 'tree_width': 2, # 'node_font': bold, 'node_color': '#006060', # 'leaf_color': '#006060', 'leaf_font':self._font} # widget = tree_to_treesegment(self._canvas, tok.type(), # **attribs) # widget.node()['color'] = '#000000' # else: # widget = TextWidget(self._canvas, tok.type(), # color='#000000', font=self._font) # widget.bind_click(self._popup_reduce) # (x1, y1, x2, y2) = self._stacklabel.bbox() # y = y2-y1+10 # if not self._stackwidgets: x = 5 # else: x = self._stackwidgets[-1].bbox()[2] + 10 # self._cframe.add_widget(widget, x, y) # self._stackwidgets.append(widget) #self._redraw() self._animating_lock = 0 ######################################### ## Hovering. ######################################### def _highlight_hover(self, event): # What production are we hovering over? index = self._prodlist.nearest(event.y) if self._hover == index: return # Clear any previous hover highlighting. self._clear_hover() # If the production corresponds to an available reduction, # highlight the stack. selection = [int(s) for s in self._prodlist.curselection()] if index in selection: rhslen = len(self._productions[index].rhs()) for stackwidget in self._stackwidgets[-rhslen:]: if isinstance(stackwidget, TreeSegmentWidget): stackwidget.label()['color'] = '#00a000' else: stackwidget['color'] = '#00a000' # Remember what production we're hovering over. self._hover = index def _clear_hover(self, *event): # Clear any previous hover highlighting. if self._hover == -1: return self._hover = -1 for stackwidget in self._stackwidgets: if isinstance(stackwidget, TreeSegmentWidget): stackwidget.label()['color'] = 'black' else: stackwidget['color'] = 'black'
class BookManagerUi(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.db = dao('blist') #데이터베이스 관리 클래스 생성 def initUI(self): self.parent.title("Book Manager") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.columnconfigure(0, pad=3) self.columnconfigure(1, pad=3) self.columnconfigure(2, pad=3) self.rowconfigure(0, pad=3) self.rowconfigure(1, pad=3) self.rowconfigure(2, pad=3) self.rowconfigure(3, pad=3) self.rowconfigure(4, pad=3) self.rowconfigure(5, pad=3) self.rowconfigure(6, pad=3) self.input_bname='' self.input_aname='' self.input_price=0 self.delete='' lb_bookname = Label(self, text="bookname:") lb_bookname.grid(row=0, column =0 ,sticky=W, pady=4, padx=5) self.entry_bookname = Entry(self) self.entry_bookname.grid(row=0, column = 1 ) lb_author = Label(self, text="author:") lb_author.grid(row=0, column =2,sticky=W, pady=4, padx=5) self.entry_author = Entry(self) self.entry_author.grid(row=0, column = 3 ) lb_price = Label(self, text="price:") lb_price.grid(row=0, column =4 ,sticky=W, pady=4, padx=5) self.entry_price = Entry(self) self.entry_price.grid(row=0, column = 5 ,padx=15) abtn = Button(self, text="Add", command=lambda:self.clicked_add()) abtn.grid(row=0, column=6) sbtn = Button(self, text="Serach", command = lambda:self.clicked_search()) sbtn.grid(row=1, column=6, pady=4) dbtn = Button(self, text="Delete", command = lambda:self.clicked_delete()) dbtn.grid(row=2, column=6, pady=4) self.lb = Listbox(self) self.lb.grid(row=3,column = 0, columnspan = 6,rowspan= 4, sticky = E+W+S+N) self.lb.bind("<<ListboxSelect>>", self.onSelect) #삭제를 위한 select부분 def onSelect(self,val): sender = val.widget idx = sender.curselection() value = sender.get(idx) self.delete = value # 데이터 추가 버튼 def clicked_add(self): bname =self.entry_bookname.get() aname = self.entry_author.get() price = self.entry_price.get() self.lb.delete(0,END) # 입력받을 데이터가 모자란지 검사 if(len(bname) >0 and len(aname)>0 and len(price)>0 ): #가격에 문자를 입력했을 경우 처리 try: priceI = eval(price) except: self.lb.insert(END,"you input wrong price. it must be integer") #사용자가 입력한 내용중 중복된 책이름이 있을 경우(저자는 책이 여러가지일 수 있으니 제외) rec = self.db.excute_select(bname,'') if ( len(rec) >0): self.lb.insert(END,bname +" is already in the database") else: self.db.insert_data(bname,aname,priceI) # 모든 조건 만족시 데이터 입력 수행 r =self.db.excute_select(bname,aname) for rs in r: self.lb.insert(END,str(rs)) else: s = StringVar() self.entry_price.config(textvariable = s) self.lb.insert(END,"you have to input more values") #검색버튼 def clicked_search(self): bname =self.entry_bookname.get() aname = self.entry_author.get() self.lb.delete(0,END) #책이름 또는 저자이름 둘중 하나만입력 되어도 검색 가능하도록 if(len(bname)>0 or len(aname)>0 ): rec = self.db.excute_select(bname,aname) for r in rec: self.lb.insert(END,str(r)) else: self.lb.insert(END,"you have to input more values(bookname or author") #삭제 버튼 def clicked_delete(self): self.lb.delete(0,END) q = self.db.excute_delete(self.delete) self.lb.insert(END,q+' is delete from database')
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="")