class SelectMultiple(TwoCells): def __init__(self, parent, text, values, **kwargs): super().__init__(parent, **kwargs) self.label = Label(self.frame, text=text) self.label.grid(column=0, row=0, padx=5, pady=5, sticky=W) self.selected_options = StringVar(self.frame) self.selected_options.set(values) self.listbox = Listbox(self.frame, listvariable=self.selected_options, selectmode=MULTIPLE) self.listbox.grid(column=1, row=0, padx=5, pady=5, sticky=E) def disable(self): self.listbox.configure(state=DISABLED) return self def enable(self): self.listbox.configure(state=NORMAL) return self def set(self, values): if values: self.enable() else: self.disable() self.listbox.selection_clear(0, self.listbox.size()) for value in values: for index in range(self.listbox.size()): if value == self.listbox.get(index): self.listbox.selection_set(index) self.listbox.event_generate("<<ListboxSelect>>") def get(self): return [self.listbox.get(i) for i in self.listbox.curselection()]
def build(self, listbox: tkinter.Listbox): if listbox.curselection().__len__() > 0: logger.debug("Building " + listbox.get(listbox.curselection()[0])) self.tile.construction = Game.Construction(self.game, self.tile.rel_pos_tuple, listbox.get(listbox.curselection()[0])) self.level.constructions.append(self.tile.construction) self.back_to_main_frame()
class Configuration(): def __init__(self, db): self.main = Tk() self.main.title("Configuration") self.db = db Button(self.main, text='New tab', command=self.NewTab).grid(row=0, column=0) self.maindaily_listbox = Listbox(self.main, exportselection=0) self.maindaily_listbox.grid(row=1, column=0) self.ls = [] self.d_tabs = self.db.get_tasks_for_table_('Tabs') for tab in self.d_tabs: self.maindaily_listbox.insert(END, tab) self.maindaily_listbox.config(width=20, height=len(self.d_tabs) + 1) self.EntryTask = Entry(self.main) self.EntryTask.grid(row=2, column=0) self.EntryTask.insert(0, 'new name') Button(self.main, text="Rename", command=self.Rename).grid(row=3, column=0) Button(self.main, text="Delete", command=self.Delete).grid(row=4, column=0) def Rename(self): NewName = str(self.EntryTask.get()) Tab2Update = self.maindaily_listbox.get( self.maindaily_listbox.curselection()) if len(NewName) > 0 and NewName != 'new name': for tab in self.d_tabs: if tab == Tab2Update: self.db.__update_table__('Tabs', 'tab_id', NewName, 'tab_id', Tab2Update) self.main.destroy() def Delete(self): Tab2Delete = self.maindaily_listbox.get( self.maindaily_listbox.curselection()) self.db.__delete_from_table__('Tabs', Tab2Delete, self.d_tabs[Tab2Delete]) self.main.destroy() def NewTab(self): tab = simpledialog.askstring("askstring", "Enter New Tab") position_id = 0 for tab in self.d_tabs: if int(self.d_tabs[tab]) > position_id: position_id = int(self.d_tabs[tab]) self.db.__insert_in_table__('Tabs', tab, str(position_id + 1)) self.maindaily_listbox.insert(END, tab) self.maindaily_listbox.config(width=20, height=len(self.d_tabs) + 1)
class MusicPlayer: def __init__(self, master): self.master = master master.title("Life In Music") master.geometry("350x700") self.var = StringVar() self.song_title = Label(master, font="Helvetica 12 bold", textvariable=self.var) self.song_title.pack() self.Button1 = Button(master, width=17, height=3, font="Helvetica 12 bold", text="PLAY", command=self.play, bg="blue", fg="white") self.Button1.pack(fill="x") self.Button2 = Button(master, width=17, height=3, font="Helvetica 12 bold", text="STOP", command=self.stop, bg="red", fg="white") self.Button2.pack(fill="x") self.Button3 = Button(master, width=17, height=3, font="Helvetica 12 bold", text="PAUSE", command=self.pause, bg="purple", fg="white") self.Button3.pack(fill="x") self.Button4 = Button(master, width=17, height=3, font="Helvetica 12 bold", text="UNPAUSE", command=self.unpause, bg="orange", fg="white") self.Button4.pack(fill="x") directory = askdirectory() os.chdir(directory) # it permits to chenge the current dir song_list = os.listdir() # it returns the list of files song self.play_list = Listbox( master, font="Helvetica 12 bold", bg="yellow", selectmode=SINGLE) for item in song_list: self.play_list.insert('end', item) self.play_list.pack(fill="both", expand="yes") self.close_button = Button(master, text="Close", command=master.quit) self.close_button.pack() pygame.init() pygame.mixer.init() def play(self): pygame.mixer.music.load(self.play_list.get(ACTIVE)) self.var.set(self.play_list.get(ACTIVE)) pygame.mixer.music.play() def stop(self): pygame.mixer.music.stop() def pause(self): pygame.mixer.music.pause() def unpause(self): pygame.mixer.music.unpause() def greet(self): print("Greetings!")
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)
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 grid_plotter_GUI: def __init__(self, filenames, selection): self.master = Tk() self.selection = selection self.master.title("Grid plotter") # Big title self.label = Label(self.master, text="Select the grid to plot:", font=("Courier", 18)) self.label.pack() # List box self.listbox = Listbox(self.master, font=("Courier", 14)) index = 1 for filename in filenames: self.listbox.insert(index, filename[:-5]) self.listbox.pack() # Finish button self.finish_button = Button(self.master, text="Display plot", command=self.finish) self.finish_button.pack() self.master.mainloop() def finish(self): self.selection[0] = self.listbox.get(self.listbox.curselection(), self.listbox.curselection()) self.master.destroy()
class Application(Frame): '''创建框架模板''' def __init__(self, master): super(Application, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): self.label1 = Label(self, text='Select youi items') self.label1.grid(row=0, column=0, sticky=W) # 创建选择列表控件 self.listbox1 = Listbox(self, selectmode=EXTENDED) items = ['item one', 'item two', 'item three'] # 添加选择条目 for item in items: self.listbox1.insert(END, item) self.listbox1.grid(row=1) self.button1 = Button(self, text='Submit', command=self.display) self.button1.grid(row=2, column=0, sticky=W) def display(self): # 获取被选中的条目 # items为选项索引组成的元组 items = self.listbox1.curselection() for item in items: str_item = self.listbox1.get(item) print(str_item) print('*' * 20)
def select_signals(self, listbox: tkk.Listbox, filter_window: tkk.Toplevel): # global selections self.selections = [*listbox.get(0, listbox.size())] listbox.grab_release() filter_window.destroy() print(f"selections: {self.selections}")
def insert_on_listbox(self, listbox: tk.Listbox, entry: tk.Entry, limit: int = 0): '''insere um valor na listbox especificada e apaga o conteudo da entry especificada, se um limite for expecificado ele vai checar se o limite da listbox não foi atingido ''' if not entry.get() == '': tamanho_listbox = len(set(listbox.get(0, tk.END))) if not tamanho_listbox > limit or limit == 0: listbox.insert(tk.END, entry.get()) entry.delete(0, tk.END)
class RegistryOfAuxiliary(): def __init__(self, frame, column): self.column = column self.frame = frame self.created() self.mounted() def created(self): self.labelTitle = Label(self.frame, text='Registration of applicants to auxiliary') self.labelTitle.grid(row=0, column=self.column, pady=10) self.listSubjects = Listbox(self.frame, cursor='mouse', width=30, height=10, selectmode=SINGLE, selectbackground='#BBA988') self.listSubjects.grid(row=1, column=self.column, pady=5) self.labelEstudent = Label(self.frame, text="id estudent") self.labelEstudent.grid(row=2, column=self.column, pady=5) self.entryEstudent = Entry(self.frame) self.entryEstudent.grid(row=3, column=self.column, pady=5) self.buttonSend = Button(self.frame, text='SEND', command=lambda: self.send()) self.buttonSend.grid(row=4, column=self.column, pady=5) self.labelMenssage = Label(self.frame, text='') self.labelMenssage.grid(row=5, column=self.column, pady=3) def mounted(self): self.showSubjects() def showSubjects(self): for subject in getSubjects(): self.listSubjects.insert(END, subject) def send(self): codSubject = self.listSubjects.get(ACTIVE)[0] codStudent = self.entryEstudent.get() try: msg = insertPostulation(codSubject, codStudent) self.changeMenssaje(self.labelMenssage, msg, 'green') except Exception as e: print(e) def changeMenssaje(self, menssaje, text, color): menssaje['text'] = text menssaje['fg'] = color
def get_listbox_selected_values(widget: tk.Listbox) -> List[str]: """Return values of selections in Listbox. :param widget: Listbox to process """ selections = widget.curselection() values = [] for i, __ in enumerate(selections): value = widget.get(selections[i]) values.append(value) return values
def selection_print_to_TextFrame(self, lb: tk.Listbox, tbox: tk.Text): # リストボックスで選択したテキスト取得 selected_idx = lb.curselection() if len(selected_idx) == 0: return selected_idx = selected_idx[0] words = lb.get(selected_idx) if self.find_indexces_list: self.update_textbox(tbox, words, self.find_indexces_list[selected_idx]) else: self.update_textbox(tbox, words)
class EntryOptionsWindow: def __init__(self, ls: str, tk: Tk, select_path=False) -> None: self.select_path = select_path self.List = ls self.Tk = tk self.Root = Toplevel(self.Tk) self.Root.withdraw() self.Frame = Frame(self.Root) self.Box = Listbox(self.Frame, selectmode='extended', width=54, height=24) for i in globals()[self.List]: self.Box.insert(END, i) self.Scroll = Scrollbar(self.Frame, command=self.Box.yview) self.Entry = Entry(self.Frame) self.ButtonAdd = Button(self.Frame, text='Добавить', command=self.__add_item) self.ButtonDel = Button(self.Frame, text='Удалить', command=self.__del_item) self.ButtonDone = Button(self.Frame, text='Готово', command=self.__save_list) self.ButtonExit = Button(self.Frame, text='Отмена', command=self.Root.destroy) def __add_item(self) -> None: if self.select_path: text = filedialog.askdirectory() else: text = self.Entry.get() if text: self.Box.insert(END, text) self.Entry.delete(0, END) def __del_item(self) -> None: select = list(self.Box.curselection()) select.reverse() for i in select: self.Box.delete(i) def __save_list(self) -> None: globals()[self.List] = list(self.Box.get(0, END)) self.Root.destroy() def main(self) -> None: center_win(self.Root, '500x400') self.Root.deiconify() self.Root.title(f'Editing {self.List}') self.Box.pack(side='left', expand=True) self.Scroll.pack(side='left', fill='y') self.Box.config(yscrollcommand=self.Scroll.set) self.Frame.pack(side='left', padx=10) if not self.select_path: self.Entry.pack(anchor='n') self.ButtonAdd.pack(fill='x') self.ButtonDel.pack(fill='x') self.ButtonDone.pack(fill='x') self.ButtonExit.pack(fill='x') self.Root.mainloop()
def removeGUI(): global win global frame if (frame != None): frame.destroy() frame = Frame(win, background='lawn green') lab1 = Label(frame, text="Delete hydrocarbon", fg="black", bg="lawn green", font=("Comic Sans MS", 20)) lab1.pack(pady=10) # create a listbox lists = Listbox(frame, width=20, height=18, selectmode=tk.SINGLE) lists.pack() #on buttonclick moves to remove function deleteBtn = Button(frame, text="Delete", height=2, width=8, fg="black", bg="lime green", font=("Comic Sans MS", 10), command=lambda: remove(lists.get(tk.ACTIVE))) deleteBtn.pack() btnHome = Button(frame, text="Home", command=createMainMenuGUI, height=2, width=8, fg="black", bg="green4", font=("Comic Sans MS", 10)) btnHome.pack() frame.pack() # connect to batabase conn = sqlite3.connect('Theoretical_Method.db') c = conn.cursor() # go through every single hydrocarbon name column and compare to the chosen one query = c.execute('SELECT Hydrocarbon FROM Theoretical').fetchall() for i in query: lists.insert(tk.END, i)
class DriversWindow: def __init__(self, parent, model): self.model = model self.parent = parent self.window = Toplevel(parent.window) self.window.title('Lista sterowników') self.window.geometry('600x400') self.window.rowconfigure(0, weight=1) self.window.columnconfigure(0, weight=1) self.x_scroll = Scrollbar(self.window, orient=tk.HORIZONTAL) self.y_scroll = Scrollbar(self.window, orient=tk.VERTICAL) self.x_scroll.grid(row=1, column=0, columnspan=2, sticky=tk.E + tk.W) self.y_scroll.grid(row=0, column=2, sticky=tk.N + tk.S) self.listbox = Listbox(self.window, xscrollcommand=self.x_scroll.set, yscrollcommand=self.y_scroll.set) self.x_scroll['command'] = self.listbox.xview self.y_scroll['command'] = self.listbox.yview threading.Thread(target=self.populate_list).start() self.prog_window = ProgressWindow(self, 'Trwa szukanie sterowników') self.prog_window.start() self.listbox.grid(row=0, column=0, sticky=tk.N + tk.E + tk.S + tk.W, columnspan=2) Button(self.window, text='Wybierz', command=self.pick_dev).grid(row=2, sticky=tk.NE, padx=10) Button(self.window, text='Anuluj', command=self.destroy).grid(row=2, column=1, sticky=tk.NW, padx=10) self.window.transient(master=parent.window) def pick_dev(self): self.model.project.devpath = self.listbox.get( self.listbox.curselection()).split()[-1] self.parent.refresh_driver() self.destroy() def populate_list(self): dev_list = self.model.list_dev_paths() for d in dev_list: if d is not '': self.listbox.insert(tk.END, d) self.prog_window.destroy() self.window.grab_set() def destroy(self): self.window.grab_release() self.window.destroy()
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())])
class Application(Frame): '''创建框架模板''' def __init__(self, master): super(Application, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): # 创建窗口菜单控件 menubar = Menu(self) filemenu = Menu(self) # 向菜单中添加菜单项 filemenu.add_command(label='Convert', command=self.convert) filemenu.add_command(label='Clear', command=self.clear) # 将filemenu添加为menubar的下拉菜单 menubar.add_cascade(label='File', menu=filemenu) menubar.add_command(label='Quit', command=self.quit) # 向窗口中添加菜单控件 root.config(menu=menubar) self.label1 = Label(self, text='Select youi items') self.label1.grid(row=0, column=0, sticky=W) # 创建选择列表控件 self.listbox1 = Listbox(self, selectmode=EXTENDED) items = ['item one', 'item two', 'item three'] # 添加选择条目 for item in items: self.listbox1.insert(END, item) self.listbox1.grid(row=1) self.button1 = Button(self, text='Submit', command=self.display) self.button1.grid(row=2, column=0, sticky=W) def display(self): # 获取被选中的条目 # items为选项索引组成的元组 items = self.listbox1.curselection() for item in items: str_item = self.listbox1.get(item) print(str_item) print('*' * 20) def convert(self): print('This is a convert command') def clear(self): print('This is a clear command') def quit(self): print('This is a quit command')
class PlayerView: directories = [] def __init__(self, parent_window): self.parent_window = parent_window self.frame = Frame(parent_window.window) self.button_play = Button(self.frame, text=f"Play", command=self.__button_play_clicked) self.button_stop = Button(self.frame, text=f"Stop", command=self.__button_stop_clicked) self.button_open = Button(self.frame, text=f"Open", command=self.__button_open_clicked) self.song_list = Listbox(self.frame) self.player = Player() self.song_list.grid(column=0, row=0) self.button_open.config(width=8) self.button_open.grid(column=0, row=1) self.button_stop.config(width=8) self.button_stop.grid(column=1, row=1) self.button_play.config(width=8) self.button_play.grid(column=2, row=1) def show(self): self.frame.grid(column=0, row=0) def hide(self): self.frame.grid_forget() def __button_open_clicked(self): open_file_dialog = OpenFileDialog() self.directories = open_file_dialog.show() for index, directory in enumerate(self.directories): self.song_list.insert(index, directory) def __button_play_clicked(self): if self.song_list.curselection(): selected_song = self.song_list.get(self.song_list.curselection()) self.player.play(selected_song) def __button_stop_clicked(self): self.player.stop()
class LoadGUI(Frame): """Loading frame which allows the users to pick quizzes. """ def __init__(self, master=None): Frame.__init__(self, master) self.grid(row=0, column=0, sticky="nsew") self.grid_columnconfigure(0, weight=1) self.cover_photo = PhotoImage(file="static/cover.png") self.cover_label = Label(self, image=self.cover_photo) self.cover_label.grid(row=0, column=0, padx=(20,20), pady=(20,10), sticky="ew") self.select_frame = LabelFrame(self, text="Select a quiz") self.select_frame.grid(row=1, column=0, padx=(20,20), pady=(10,20), sticky="ew") for i in range(0,4): self.select_frame.grid_rowconfigure(i, weight=1) self.select_frame.grid_columnconfigure(0, weight=4) self.select_frame.grid_columnconfigure(1, weight=1) self.quiz_list = Listbox(self.select_frame) self.quiz_list.grid(row=0, column=0, rowspan=4, padx=(10,10), pady=(10,10), sticky="ew") self.start_button = Button(self.select_frame, text="Start quiz", command=self.start_chosen) self.start_button.grid(row=0, column=1, padx=(0,10), pady=(10,5), sticky="nsew") self.refresh_button = Button(self.select_frame, text="Refresh list", command=self.refresh) self.refresh_button.grid(row=1, column=1, padx=(0,10), pady=(5,5), sticky="nsew") self.help_button = Button(self.select_frame, text="Help", command=var.HELP_URL) self.help_button.grid(row=2, column=1, padx=(0,10), pady=(5,5), sticky="nsew") self.quit_button = Button(self.select_frame, text="Quit", command=root.destroy) self.quit_button.grid(row=3, column=1, padx=(0,10), pady=(5,10), sticky="nsew") self.get_quizzes() def get_quizzes(self): """[summary] """ self.dir_list = sorted([i[:-5] for i in os.listdir() if i.endswith(".json") and "quiz" in i.lower()]) for f in self.dir_list: self.quiz_list.insert("end", f) def refresh(self): """[summary] """ self.quiz_list.delete(0, "end") self.get_quizzes() def start_chosen(self): """[summary] """ self.filename = self.quiz_list.get("active") + ".json" file_handler.parse_file(self.filename) file_handler.parse_leaderboard() quiz_gui.add_questions() quiz_gui.tkraise()
class ShapesMenu(object): """ """ def __init__(self, master, line_collection): try: self.width_of_entry = len(line_collection[0]) except IndexError: self.width_of_entry = 0 self.top = Toplevel(master) self.current_lines_listbox = Listbox(self.top) self.removed_lines_listbox = Listbox(self.top) self.submit = Button(self.top, text = "Ok", command=self.submit) self.remove_button = Button(self.top, text = "Remove", command=self.remove_line) self.cancel = Button(self.top, text = "Cancel", command=self.top.destroy) self.top.bind("<Return>", func=self.submit) self.current_lines = line_collection self.removed_lines = [] self.ids_internal = [] self.ids = [] for index, line in enumerate(self.current_lines): #removes the point data and converts the rest to strings id = line[1] if id not in self.ids_internal: self.ids_internal.append(id) self.ids.append(id) line = [str(element) for element in line[1:]] #put into the list self.current_lines_listbox.insert(index, " ".join(line)) self.current_lines_listbox.grid(row=0, column=0, columnspan=3) self.submit.grid(row=1, column=1) self.cancel.grid(row=1, column=2) self.remove_button.grid(row=1, column=0) def submit(self): #expose the internal IDs to remove to the exterior methods self.ids = self.ids_internal self.top.destroy() def remove_line(self): """Take the active line and remove it""" line_to_remove = self.current_lines_listbox.get(ANCHOR) id_to_remove = int(line_to_remove.split(" ")[0]) #remove it from the ID list self.ids_internal.remove(id_to_remove) #remove it from the listbox self.current_lines_listbox = self.current_lines_listbox.delete(ANCHOR)
class CreateSets(Frame): def __init__(self, parent): # super(createSets,self).__init__(parent) Frame.__init__(self, parent) self.parent = parent self.grid(row=0, column=0) self.parentWindow = 0 self.listBox = Listbox(self, selectmode=EXTENDED) self.listBox.grid(row=1, column=1) for item in ["one", "two", "three", "four"]: self.listBox.insert(END, item) self.buttonDel = Button(self, text="delite selected class", command=self.del_selected) # lambda ld=self.listBox:ld.delete(ANCHOR)) self.buttonDel.grid(row=0, column=0) self.entry = Entry(self, state=NORMAL) # self.entry.focus_set() self.entry.insert(0, "default") self.entry.grid(row=1, column=0) self.buttonInsert = Button(self, text="add new class", command=self.add) self.buttonInsert.grid(row=0, column=1) self.buttonDone = Button(self, text="done", command=self.done) self.buttonDone.grid(row=2, column=0) def done(self): self.parentWindow.childResultList = self.listBox.get(0, END) # print(self.listBox.get(0, END)) self.parent.destroy() def add(self): text = self.entry.get() self.listBox.insert(END, text) def del_selected(self): lb = self.listBox items = map(int, lb.curselection()) for item in items: lb.delete(item)
def text_list_popup(head, lst): import tkinter as tk from tkinter import Listbox win = tk.Tk() win.title(head) l = Listbox(win) l.insert(1, *lst) l.pack() win.bind( '<Return>', lambda _: [set_theme_cache(l.get(l.curselection()[0])), win.destroy()]) win.mainloop()
class FileSelectWindow: def __init__(self, win): global session, iRODSCredentials self.session = session self.window = win self.b1 = Button(win, text='Select', command=self.select) self.lb1 = Listbox(win) self.window.grid() Grid.rowconfigure(self.window, 0, weight=1) Grid.rowconfigure(self.window, 1, weight=1) Grid.columnconfigure(self.window, 0, weight=1) self.lb1.grid(row=0, column=0, padx="20", pady="1", sticky="nswe") self.b1.grid(row=1, column=0, padx="50", pady="1", sticky="ew") coll = session.collections.get("/" + iRODSCredentials["zone"] + "/" + "home" + "/" + iRODSCredentials["user"]) file_list = [] self.get_files_from_collections(coll, file_list) for counter in range(len(file_list)): self.lb1.insert(counter, file_list[counter]) def get_files_from_collections(self, coll, file_list): for obj in coll.data_objects: file_list.append(obj.path) for col in coll.subcollections: self.get_files_from_collections(col, file_list) def select(self): global session, selected_file, selection_success try: selection = self.lb1.get(self.lb1.curselection()) except: self.window.iconify() messagebox.showerror("Error", "No file selected!") self.window.deiconify() return selected_file = selection selection_success = True self.window.destroy()
class AddWindow(Tk): def __init__(self, parent_window): super().__init__() self.title("add schedule") self.entry = Entry(self) self.entry.grid(row=0, column=0, columnspan=2) self.entry.bind("<Key>", self.key_typed) self.listBox = Listbox(self) for i in WebExtractionHelper.get_hint(""): self.listBox.insert(END, i) self.listBox.grid(row=1, column=0, columnspan=2) self.cancel_button = Button(self, text='cancel', command=self.cancel) self.cancel_button.grid(row=2, column=0) self.selected_button = Button(self, text='select', command=self.selected) self.selected_button.grid(row=2, column=1) self.parent_window = parent_window def key_typed(self, event: EventType): self.listBox.delete(0, END) postfix = '' if event.char.isdigit() or event.char.isalpha(): postfix = event.char hints = WebExtractionHelper.get_hint(self.entry.get() + postfix) for hint in hints: self.listBox.insert(END, hint) def cancel(self): self.destroy() def selected(self): try: name: str = self.listBox.get(self.listBox.curselection()) FileExtractionHelper.put_to_file(name) except TclError: pass self.destroy() self.parent_window.rerender_list()
class updating_box(): def __init__(self, root, widget, li, gridx, gridy): self.li = li self.widget = widget gridx = gridx gridy = gridy self.basic_frame = ttk.Frame(root) self.basic_frame.grid(row=gridx, column=gridy) self.input_entry = ttk.Entry(self.basic_frame, textvariable=self.widget) self.input_entry.grid(row=0, column=1) self.lb = Listbox(self.basic_frame, width=20, height=4) self.lb.insert(0, *self.li) self.input_entry.bind('<KeyRelease>', lambda e: self.update_list()) self.lb.bind('<Return>', lambda e: self.selected_item()) self.lb.bind('<Double-Button-1>', lambda e: self.selected_item()) self.input_entry.bind('<Button-1>', lambda e: self.show_me()) self.input_entry.bind('<Return>', lambda e: self.hide_me()) def hide_me(self): self.lb.grid_forget() def show_me(self): self.lb.grid(row=1, column=1) def update_list(self): temp = list( filter( lambda x: x if self.widget.get().lower() in x.lower() else '', self.li)) self.lb.delete(0, END) self.lb.insert(0, *temp) def selected_item(self): for i in self.lb.curselection(): self.widget.set(self.lb.get(i)) self.lb.tk_focusNext().focus() self.lb.grid_forget()
class ListBoxChoice(object): def __init__(self, master=None, title="Title", message="Message", list=[]): self.selected_list = [] self.master = master self.list = list[:] self.master.geometry("300x250") # Width x Height self.master.grab_set() self.master.bind("<Return>", self._select) self.master.bind("<Escape>", self._cancel) self.master.title(title) Label(self.master, text=message).pack(padx=5, pady=5) self.listBox = Listbox(self.master, selectmode=MULTIPLE) self.listBox.pack(fill=BOTH) self.list.sort() for item in self.list: self.listBox.insert(END, item) buttonFrame = Frame(self.master) buttonFrame.pack(side=BOTTOM) chooseButton = Button(buttonFrame, text="Select", command=self._select) chooseButton.pack() cancelButton = Button(buttonFrame, text="Cancel", command=self._cancel) cancelButton.pack(side=RIGHT) def _select(self, event=None): try: self.selected_list = [self.listBox.get(i) for i in self.listBox.curselection()] except IndexError: self.selected_list = None self.master.destroy() def _cancel(self, event=None): self.listBox.selection_clear(0, END) def returnValue(self): self.master.wait_window() return self.selected_list
def display_history(self): frame = Frame() newWindow = Toplevel(frame) index = 1 fileList = Listbox(newWindow, selectmode=SINGLE) files = [] import os listElement = './Message History/' + self.name_widget.get() files = os.listdir(listElement) for f in files: fileList.insert(index, f) index = index + 1 newWindow.geometry("500x200") fileList.pack(side='top') self.select_history = Button( newWindow, text="Select", width=10, command=lambda: self.print(fileList.get(fileList.curselection()) )).pack()
class ReloadOption(Toplevel): def __init__(self): super().__init__() self.title('重载设置') self.reload_mode = None self.label = Label(self, text="请选择重新加载的范围:") self.lb = Listbox(self, width=40) self.fm = Frame(self) self.ok = Button(self.fm, text="重载", command=self.select_mode) self.cancel = Button(self.fm, text="取消", command=self.destroy) for item in ['最近一周', '最近一个月', '最近三个月', '最近半年', '最近一年', '全部重载']: self.lb.insert(END, item) self.lb.select_set(5) self.label.pack(side='top') self.lb.pack(side='top', fill='both', expand='YES') self.fm.pack(side='top') self.ok.pack(side='left') self.cancel.pack(side='right') def select_mode(self): self.reload_mode = self.lb.get(self.lb.curselection()) self.destroy()
def see_After(m): m.destroy() root=Tk() root.geometry("555x400") root.title("See All Election Details") leftFrame=Frame(root) leftFrame.pack(side=LEFT) midFrame=Frame(root) midFrame.pack(side=LEFT) rightFrame=Frame(root) rightFrame.pack(side=LEFT) load=Image.open("index.png") render=ImageTk.PhotoImage(load) img=Label(leftFrame,image=render) img.image=render img.pack() Label(midFrame,text="Elections", font = "Times 15 bold").pack(expand = True, fill = BOTH) Label(midFrame,text="", font = "Times 15 bold").pack() Eframe=Frame(midFrame) Eframe.pack(expand = True,fill = BOTH) scrollbarE=Scrollbar(Eframe) listBoxElection=Listbox(Eframe,width=30,selectmode=BROWSE) listBoxElection.config(yscrollcommand=scrollbarE.set) scrollbarE.config(command=listBoxElection.yview) listBoxElection.pack(expand = True, fill = BOTH,side=LEFT) scrollbarE.pack(fill = BOTH,side=RIGHT) Label(midFrame,text="").pack() Button(midFrame,text="Back",font = "Times 10 bold",command=lambda:adminPage.adminPageStart(root)).pack(expand = True, fill = BOTH) db.loadAfterElectionData(listBoxElection) all_items = listBoxElection.get(0, tk.END) print(all_items) listBoxElection.bind('<Double-Button-1>', lambda x:selectedElection(root,listBoxElection,all_items)) root.mainloop()
class ActivateTask(): def __init__(self, db): self.main = Tk() self.main.title("Activate Task") self.db = db self.PausedTasks = db.get_tasks_for_table_('PausedTasks') ttk.Label(self.main, text='Paused Tasks').grid(row=0, column=0) self.listbox = Listbox(self.main, selectmode=EXTENDED) self.listbox.grid(row=1, column=0) self.width = 5 for key in self.PausedTasks: self.listbox.insert(END, '==' + key + '==') for value in self.PausedTasks[key]: self.listbox.insert(END, value) if len(value) > self.width: self.width = len(value) self.listbox.config(width=self.width, height=10) #, justify=CENTER) ttk.Button(self.main, text="Activate", command=self.select).grid(row=2, column=0) def select(self): selection = self.listbox.curselection() for i in selection: Task2Activate = self.listbox.get(i) for key in self.PausedTasks: if Task2Activate == '==' + key + '==': pass else: for value in self.PausedTasks[key]: if value == Task2Activate: project = key self.db.__insert_in_table__('MainDailyGroups', project, Task2Activate) self.db.__delete_from_table__('PausedTasks', project, Task2Activate) self.main.destroy()
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 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 ListChooserDialog: def __init__(self, parent, listEntries, guiPrompt, allowManualFolderSelection, forceFolderOnlyChoosing=False): """ NOTE: do not call this constructor directly. Use the ListChooserDialog.showDialog function instead. """ self.forceFolderOnlyChoosing = forceFolderOnlyChoosing self.top = tkinter.Toplevel(parent) defaultPadding = {"padx":20, "pady":10} # Set a description for this dialog (eg "Please choose a game to mod" tkinter.Label(self.top, text=guiPrompt).pack() # Define the main listbox to hold the choices given by the 'listEntries' parameter listboxFrame = tkinter.Frame(self.top) # Define a scrollbar and a listbox. The yscrollcommand is so that the listbox can control the scrollbar scrollbar = tkinter.Scrollbar(listboxFrame, orient=tkinter.VERTICAL) self.listbox = Listbox(listboxFrame, selectmode=tkinter.BROWSE, yscrollcommand=scrollbar.set) # Also configure the scrollbar to control the listbox, and pack it scrollbar.config(command=self.listbox.yview) scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y) # Setting width to 0 forces auto-resize of listbox see: https://stackoverflow.com/a/26504193/848627 for item in listEntries: self.listbox.insert(tkinter.END, item) self.listbox.config(width=0) self.listbox.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=1) # Finally, pack the Frame so its contents are displayed on the dialog listboxFrame.pack(**defaultPadding) # If the user is allowed to choose a directory manually, add directory chooser button if allowManualFolderSelection: b2 = tkinter.Button(self.top, text="Choose Folder Manually", command=self.showDirectoryChooser) b2.pack(**defaultPadding) # Add an 'OK' button. When pressed, the dialog is closed b = tkinter.Button(self.top, text="OK", command=self.ok) b.pack(**defaultPadding) # This variable stores the returned value from the dialog self.result = None def showDirectoryChooser(self): if IS_MAC and not self.forceFolderOnlyChoosing: self.result = filedialog.askopenfilename(filetypes=[(None, "com.apple.application")]) else: self.result = filedialog.askdirectory() self.top.destroy() def ok(self): """ This function is called when the 'OK' button is pressed. It retrieves the value of the currently selected item, then closes the dialog :return: """ selected_value = None if len(self.listbox.curselection()) > 0: selected_index = self.listbox.curselection()[0] selected_value = self.listbox.get(selected_index) self.result = selected_value self.top.destroy() @staticmethod def showDialog(rootGUIWindow, choiceList, guiPrompt, allowManualFolderSelection, forceFolderOnlyChoosing=False): """ Static helper function to show dialog and get a return value. Arguments are the same as constructor :param rootGUIWindow: the parent tkinter object of the dialog (can be root window) :param choiceList: a list of strings that the user is to choose from :param guiPrompt: the description that will be shown on the dialog :param allowManualFolderSelection: if true, user is allowed to select a folder manually. :return: returns the value the user selected (string), or None if none available """ d = ListChooserDialog(rootGUIWindow, choiceList, guiPrompt, allowManualFolderSelection, forceFolderOnlyChoosing) rootGUIWindow.wait_window(d.top) return d.result
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
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 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 TextSelect(Frame): def __init__(self, client, anchor, items, destroyAnchor=False): """ Args: client: [SelectionClient] The window that text is returned to. anchor: A window that the text selection popup is created relative to. items: [str], items to display in the listbox. destroyAnchor: [bool] if true, destroy the anchor after positioning the window. """ self.top = Toplevel() self.anchor = anchor self.top.overrideredirect(1) self.top.wm_geometry('+%s+%s' % (anchor.winfo_rootx() + anchor.winfo_x(), anchor.winfo_rooty() + anchor.winfo_y() ) ) super(TextSelect, self).__init__(self.top) self.entry = Entry(self) self.client = client self.items = items self.place(x = 0.5, y = 0.5, height = 100, width = 100) self.entry.bind('<Return>', self.close) self.entry.bind('<KeyPress>', self.filter) self.entry.bind('<Escape>', self.abort) self.entry.bind('<Up>', self.up) self.entry.bind('<Down>', self.down) self.entry.pack() # Create the list of items. self.list = Listbox(self) for item in self.items: self.list.insert('end', item) self.list.pack() self.grid() self.entry.focus() # Reposition the select button against the anchor. We defer this # until after idle so that the anchor has a chance to get rendered. def reposition(*args): self.top.wm_geometry('+%s+%s' % ( anchor.winfo_rootx(), anchor.winfo_rooty()) ) if destroyAnchor: anchor.destroy() self.after_idle(reposition) def close(self, event): sel = self.list.curselection() if sel: item = self.list.get(sel[0]) else: item = self.entry.get() # Note that the order of this appears to be significant: destroying # before selecting leaves the focus in a weird state. self.client.selected(item) self.top.destroy() return 'braek' def abort(self, event): self.top.destroy() self.client.aborted() return 'break' def up(self, event): sel = self.list.curselection() if not sel: self.list.selection_set(0) return 'break' sel = sel[0] print('sel is %s size is %s' % (sel, self.list.size())) if sel > 0: print('setting selection to %s' % sel) self.list.selection_clear(sel) self.list.selection_set(sel - 1) self.list.see(sel) return 'break' def down(self, event): sel = self.list.curselection() if not sel: self.list.selection_set(0) return 'break' sel = sel[0] print('sel is %s size is %s' % (sel, self.list.size())) if sel < self.list.size() - 1: print('setting selection to %s' % (sel + 1)) self.list.selection_clear(sel) self.list.selection_set(sel + 1) self.list.see(sel) return 'break' def filter(self, event): """Filter the listbox based on the contents of the entryfield.""" # first add the character to the entry. currentText = self.entry.get() print(event.keysym) if event.keysym == 'BackSpace': # Handle backspace specially. if currentText: currentText = currentText[:-1] self.entry.delete(0, 'end') self.entry.insert(0, currentText) else: return 'break' else: # Assume normal character. Insert it. self.entry.insert('insert', event.char) currentText += event.char self.list.delete(0, 'end') pattern = currentText.upper() for item in self.items: if pattern in item.upper(): self.list.insert('end', item) return 'break'
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 LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): """init""" self.root = root or Tk() self.root.title("Pylint") # reporter self.reporter = None # message queue for output from reporter self.msg_queue = queue.Queue() self.msgs = [] self.filenames = [] self.rating = StringVar() self.tabs = {} self.report_stream = BasicStream(self) # gui objects self.lbMessages = None self.showhistory = None self.results = None self.btnRun = None self.information_box = None self.convention_box = None self.refactor_box = None self.warning_box = None self.error_box = None self.fatal_box = None self.txtModule = None self.status = None self.msg_type_dict = None self.init_gui() def init_gui(self): """init helper""" # setting up frames top_frame = Frame(self.root) mid_frame = Frame(self.root) radio_frame = Frame(self.root) res_frame = Frame(self.root) msg_frame = Frame(self.root) check_frame = Frame(self.root) history_frame = Frame(self.root) btn_frame = Frame(self.root) rating_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) mid_frame.pack(side=TOP, fill=X) history_frame.pack(side=TOP, fill=BOTH, expand=True) radio_frame.pack(side=TOP, fill=BOTH, expand=True) rating_frame.pack(side=TOP, fill=BOTH, expand=True) res_frame.pack(side=TOP, fill=BOTH, expand=True) check_frame.pack(side=TOP, fill=BOTH, expand=True) msg_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) # Message ListBox rightscrollbar = Scrollbar(msg_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.lbMessages = Listbox( msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white" ) self.lbMessages.pack(expand=True, fill=BOTH) rightscrollbar.config(command=self.lbMessages.yview) bottomscrollbar.config(command=self.lbMessages.xview) # History ListBoxes rightscrollbar2 = Scrollbar(history_frame) rightscrollbar2.pack(side=RIGHT, fill=Y) bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL) bottomscrollbar2.pack(side=BOTTOM, fill=X) self.showhistory = Listbox( history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white" ) self.showhistory.pack(expand=True, fill=BOTH) rightscrollbar2.config(command=self.showhistory.yview) bottomscrollbar2.config(command=self.showhistory.xview) self.showhistory.bind("<Double-Button-1>", self.select_recent_file) self.set_history_window() # status bar self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) # labels self.lblRatingLabel = Label(rating_frame, text="Rating:") self.lblRatingLabel.pack(side=LEFT) self.lblRating = Label(rating_frame, textvariable=self.rating) self.lblRating.pack(side=LEFT) Label(mid_frame, text="Recently Used:").pack(side=LEFT) Label(top_frame, text="Module or package").pack(side=LEFT) # file textbox self.txtModule = Entry(top_frame, background="white") self.txtModule.bind("<Return>", self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) # results box rightscrollbar = Scrollbar(res_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.results = Listbox( res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier" ) self.results.pack(expand=True, fill=BOTH, side=BOTTOM) rightscrollbar.config(command=self.results.yview) bottomscrollbar.config(command=self.results.xview) # buttons Button(top_frame, text="Open", command=self.file_open).pack(side=LEFT) Button(top_frame, text="Open Package", command=(lambda: self.file_open(package=True))).pack(side=LEFT) self.btnRun = Button(top_frame, text="Run", command=self.run_lint) self.btnRun.pack(side=LEFT) Button(btn_frame, text="Quit", command=self.quit).pack(side=BOTTOM) # radio buttons self.information_box = IntVar() self.convention_box = IntVar() self.refactor_box = IntVar() self.warning_box = IntVar() self.error_box = IntVar() self.fatal_box = IntVar() i = Checkbutton( check_frame, text="Information", fg=COLORS["(I)"], variable=self.information_box, command=self.refresh_msg_window, ) c = Checkbutton( check_frame, text="Convention", fg=COLORS["(C)"], variable=self.convention_box, command=self.refresh_msg_window, ) r = Checkbutton( check_frame, text="Refactor", fg=COLORS["(R)"], variable=self.refactor_box, command=self.refresh_msg_window ) w = Checkbutton( check_frame, text="Warning", fg=COLORS["(W)"], variable=self.warning_box, command=self.refresh_msg_window ) e = Checkbutton( check_frame, text="Error", fg=COLORS["(E)"], variable=self.error_box, command=self.refresh_msg_window ) f = Checkbutton( check_frame, text="Fatal", fg=COLORS["(F)"], variable=self.fatal_box, command=self.refresh_msg_window ) i.select() c.select() r.select() w.select() e.select() f.select() i.pack(side=LEFT) c.pack(side=LEFT) r.pack(side=LEFT) w.pack(side=LEFT) e.pack(side=LEFT) f.pack(side=LEFT) # check boxes self.box = StringVar() # XXX should be generated report = Radiobutton( radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window ) rawMet = Radiobutton( radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window ) dup = Radiobutton( radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window ) ext = Radiobutton( radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window, ) stat = Radiobutton( radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window, ) msgCat = Radiobutton( radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window, ) msg = Radiobutton( radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window ) report.select() report.grid(column=0, row=0, sticky=W) rawMet.grid(column=1, row=0, sticky=W) dup.grid(column=2, row=0, sticky=W) msg.grid(column=3, row=0, sticky=E) stat.grid(column=0, row=1, sticky=W) msgCat.grid(column=1, row=1, sticky=W) ext.grid(column=2, row=1, columnspan=2, sticky=W) # dictionary for check boxes and associated error term self.msg_type_dict = { "I": lambda: self.information_box.get() == 1, "C": lambda: self.convention_box.get() == 1, "R": lambda: self.refactor_box.get() == 1, "E": lambda: self.error_box.get() == 1, "W": lambda: self.warning_box.get() == 1, "F": lambda: self.fatal_box.get() == 1, } self.txtModule.focus_set() def select_recent_file(self, event): """adds the selected file in the history listbox to the Module box""" if not self.showhistory.size(): return selected = self.showhistory.curselection() item = self.showhistory.get(selected) # update module self.txtModule.delete(0, END) self.txtModule.insert(0, item) def refresh_msg_window(self): """refresh the message window with current output""" # clear the window self.lbMessages.delete(0, END) for msg in self.msgs: if self.msg_type_dict.get(msg[0])(): msg_str = self.convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], "black") self.lbMessages.itemconfigure(END, fg=fg_color) def refresh_results_window(self): """refresh the results window with current output""" # clear the window self.results.delete(0, END) try: for res in self.tabs[self.box.get()]: self.results.insert(END, res) except: pass def convert_to_string(self, msg): """make a string representation of a message""" if msg[2] != "": return "(" + msg[0] + ") " + msg[1] + "." + msg[2] + " [" + msg[3] + "]: " + msg[4] else: return "(" + msg[0] + ") " + msg[1] + " [" + msg[3] + "]: " + msg[4] def process_incoming(self): """process the incoming messages from running pylint""" while self.msg_queue.qsize(): try: msg = self.msg_queue.get(0) if msg == "DONE": self.report_stream.output_contents() return False # adding message to list of msgs self.msgs.append(msg) # displaying msg if message type is selected in check box if self.msg_type_dict.get(msg[0])(): msg_str = self.convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], "black") self.lbMessages.itemconfigure(END, fg=fg_color) except queue.Empty: pass return True def periodic_call(self): """determine when to unlock the run button""" if self.process_incoming(): self.root.after(100, self.periodic_call) else: # enabling button so it can be run again self.btnRun.config(state=NORMAL) def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def halt(self): """program halt placeholder""" return def file_open(self, package=False, _=None): """launch a file browser""" if not package: filename = askopenfilename( parent=self.root, filetypes=[("pythonfiles", "*.py"), ("allfiles", "*")], title="Select Module" ) else: filename = askdirectory(title="Select A Folder", mustexist=1) if filename == (): return self.txtModule.delete(0, END) self.txtModule.insert(0, filename) def update_filenames(self): """update the list of recent filenames""" filename = self.txtModule.get() if not filename: filename = os.getcwd() if filename + "\n" in self.filenames: index = self.filenames.index(filename + "\n") self.filenames.pop(index) # ensure only 10 most recent are stored if len(self.filenames) == 10: self.filenames.pop() self.filenames.insert(0, filename + "\n") def set_history_window(self): """update the history window with info from the history file""" # clear the window self.showhistory.delete(0, END) # keep the last 10 most recent files try: view_history = open(HOME + HISTORY, "r") for hist in view_history.readlines(): if not hist in self.filenames: self.filenames.append(hist) self.showhistory.insert(END, hist.split("\n")[0]) view_history.close() except IOError: # do nothing since history file will be created later return def run_lint(self, _=None): """launches pylint""" self.update_filenames() self.root.configure(cursor="watch") self.reporter = GUIReporter(self, output=self.report_stream) module = self.txtModule.get() if not module: module = os.getcwd() # cleaning up msgs and windows self.msgs = [] self.lbMessages.delete(0, END) self.tabs = {} self.results.delete(0, END) self.btnRun.config(state=DISABLED) # setting up a worker thread to run pylint worker = Thread(target=lint_thread, args=(module, self.reporter, self)) self.periodic_call() worker.start() # Overwrite the .pylint-gui-history file with all the new recently added files # in order from filenames but only save last 10 files write_history = open(HOME + HISTORY, "w") write_history.writelines(self.filenames) write_history.close() self.set_history_window() self.root.configure(cursor="")
class 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 MainAppController(Frame): """ Main Application for GUI """ def __init__(self, parent): """ Initialize Main Application """ Frame.__init__(self, parent) # create a style object style = Style() style.configure('D.TButton', foreground='red3') style.configure('R.TButton', foreground='DodgerBlue4', font=("TkTextFont", 9, 'bold')) style.configure('B.TButton', foreground='FireBrick4', font=("TkTextFont", 9, 'bold')) # Left frame, column 1 left_frame = Frame(master=self) left_frame.grid(row=1, column=1, padx=30, pady=35, rowspan=3) # Middle frame (info text, column 2) middle_frame = Frame(master=self) middle_frame.grid(row=1, column=2, padx=30, pady=35, rowspan=3) # Right frame (statistics, column 3) right_frame = Frame(master=self) right_frame.grid(row=1, column=3, padx=30, pady=35, rowspan=2) # LEFT FRAME WIDGET Label(left_frame, text="Book ID", font=("TkTextFont", 11)).grid(row=1, column=1, columnspan=3) self._book_list = Listbox(left_frame, height=10, width=10, font=("TkTextFont", 11), bg='LightSalmon2') self._book_list.grid(row=2, column=1) self._book_list.configure(justify="center") # Call this on select self._book_list.bind("<<ListboxSelect>>", self._update_textbox) # MIDDLE FRAME WIDGET Label(middle_frame, text="Book Summary", font=("TkTextFont", 11)).grid(row=1, column=2, columnspan=7) self._info_text = Text(master=middle_frame, height=10, width=45, font=("TkTextFont", 11), bg='plum2') self._info_text.grid(row=2, column=2, columnspan=7) self._info_text.tag_configure("bold", font=("TkTextFont", 10, "bold")) # RIGHT FRAME WIDGET Label(right_frame, text="Book Statistics", font=("TkTextFont", 11)).grid(row=1, column=1, columnspan=3) self._book_stat = Text(master=right_frame, height=10.5, width=30, font=("TkTextFont", 10), bg='LightSalmon2') self._book_stat.grid(row=2, column=1, rowspan=3) self._book_stat.tag_configure("bold", font=("TkTextFont", 10, "bold")) # Drop Down menu to add a book self._add_var = StringVar(left_frame) choices = ['eBook', 'Textbook'] OptionMenu(middle_frame, self._add_var, 'Select Type', *choices).grid(row=3, column=2, pady=5, columnspan=4) # Drop Down menu to update a book self._update_var = StringVar(left_frame) choices = ['eBook', 'Textbook'] OptionMenu(middle_frame, self._update_var, 'Select Type', *choices).grid(row=3, column=3, pady=5, columnspan=7) # A couple buttons - using TTK Button(left_frame, text="Delete Book", width=13, command=self._delete_book, style='D.TButton').grid(row=3, column=1, pady=5) Button(left_frame, text="Quit", width=13, command=self._quit_callback).grid(row=4, column=1) Button(middle_frame, text="Add Book", width=13, command=self._add_book).grid(row=4, column=2, columnspan=4) Button(middle_frame, text="Update Book", width=13, command=self._update_book).grid(row=4, column=3, columnspan=7) Button(right_frame, text="Borrow Book", width=13, command=self._borrow_cb, style='B.TButton').grid(row=5, column=1, pady=5) Button(right_frame, text="Return Book", width=13, command=self._return_cb, style='R.TButton').grid(row=6, column=1) # Now update the list and Statistics self._update_book_list() def _update_textbox(self, *args): """ Updates the info text box on the right, based on the current ID selected """ # This is a list, so we take just the first item (could be multi select...) try: selected_index = self._book_list.curselection()[0] except IndexError: return None book_id = self._book_list.get(selected_index) # Make a GET request r = requests.get( f"http://localhost:5000/library_manager/book/{book_id}") # Clear the text box self._info_text.delete(1.0, tk.END) # Check the request status code if r.status_code != 200: self._info_text.insert(tk.END, "Error running the request!") # For every item (key, value) in the JSON response, display them: for k, v in r.json().items(): self._info_text.insert(tk.END, f"{k.capitalize()}\t\t", "bold") self._info_text.insert(tk.END, f"{v}\n") self._update_book_stat() def _update_book_list(self): """ Update the List of Books """ r = requests.get("http://localhost:5000/library_manager/all") self._book_list.delete(0, tk.END) for s in r.json()["ebook"]: self._book_list.insert(tk.END, '{:^}'.format(s['book_id'])) self._book_list.itemconfig(tk.END, {'fg': 'Blue4'}) if s['is_borrowed']: self._book_list.itemconfig(tk.END, {'bg': 'khaki1'}) for s in r.json()["textbook"]: self._book_list.insert(tk.END, '{:^}'.format(s['book_id'])) self._book_list.itemconfig(tk.END, {'fg': 'Brown4'}) if s['is_borrowed']: self._book_list.itemconfig(tk.END, {'bg': 'khaki1'}) self._update_book_stat() def _update_book_stat(self): """ Update the List of Books """ r = requests.get("http://localhost:5000/library_manager/all/stats") self._book_stat.delete(1.0, tk.END) for k, v in r.json().items(): self._book_stat.insert(tk.END, f"{k}\t\t\t", "bold") self._book_stat.insert(tk.END, f"{v}\n") def _borrow_cb(self): """Borrow any book with the selected ID""" if not self._book_list.curselection(): mb.showerror('Error : Item not selected', 'Please select a book.') else: selected_index = self._book_list.curselection()[0] book_id = self._book_list.get(selected_index) r = requests.get( f"http://127.0.0.1:5000/library_manager/book/{book_id}") if r.json()['is_borrowed']: mb.showerror('Error : Bad selection', 'Book is already borrowed.') else: response = requests.put( f"http://127.0.0.1:5000/library_manager/{book_id}/borrow") if response.status_code == 200: self._update_book_list() def _return_cb(self): """Return any book with the selected ID to library""" if not self._book_list.curselection(): mb.showerror('Error : Item not selected', 'Please select a book.') else: selected_index = self._book_list.curselection()[0] book_id = self._book_list.get(selected_index) r = requests.get( f"http://127.0.0.1:5000/library_manager/book/{book_id}") if not r.json()['is_borrowed']: mb.showerror('Error : Bad selection', 'Book is already returned.') else: response = requests.put( f"http://127.0.0.1:5000/library_manager/{book_id}/return_book" ) if response.status_code == 200: self._update_book_list() def _add_ebook(self): """ Add eBook Popup """ self._popup_win = tk.Toplevel() self._popup = AddeBookPopup(self._popup_win, self._close_book_cb) def _add_textbook(self): """ Add Textbook Popup """ self._popup_win = tk.Toplevel() self._popup = AddTextbookPopup(self._popup_win, self._close_book_cb) def _add_book(self): """Redirect add book based on the type""" if self._add_var.get() == 'eBook': self._add_ebook() elif self._add_var.get() == 'Textbook': self._add_textbook() else: mb.showerror('Error : Type not selected', 'Please select a type.') def _update_book(self): """Update eBook attributes""" if self._update_var.get() == 'eBook': self._update_ebook() elif self._update_var.get() == 'Textbook': self._update_textbook() else: mb.showerror('Error : Type not selected', 'Please select a type.') def _update_ebook(self): """Update ebook attributes in the 'Book' database""" if not self._book_list.curselection(): mb.showerror('Error : Book not selected', 'Please select a book.') else: selected_index = self._book_list.curselection()[0] book_id = self._book_list.get(selected_index) r = requests.get( f"http://localhost:5000/library_manager/book/{book_id}") if r.json()['type'] != 'ebook': mb.showerror('Error : Invalid selection', 'Please select an ebook ID.') else: self._popup_win = tk.Toplevel() self._popup = UpdateeBookPopup(self._popup_win, book_id, self._close_book_cb) self._update_book_list() def _update_textbook(self): """Update textbook attributes in the 'Book' database""" if not self._book_list.curselection(): mb.showerror('Error : Book not selected', 'Please select a book.') else: self._popup_win = tk.Toplevel() selected_index = self._book_list.curselection()[0] book_id = self._book_list.get(selected_index) r = requests.get( f"http://localhost:5000/library_manager/book/{book_id}") if r.json()['type'] != 'textbook': mb.showerror('Error : Invalid selection', 'Please select a textbook ID.') else: self._popup = UpdateTextbookPopup(self._popup_win, book_id, self._close_book_cb) self._update_book_list() def _delete_book(self): """ Delete book Popup """ self._popup_win = tk.Toplevel() self._popup = DeleteBook(self._popup_win, self._close_book_cb) def _close_book_cb(self): """ Close Popup """ self._popup_win.destroy() self._update_book_list() def _quit_callback(self): """ Quit """ self.quit()
def piano_robot_frame(root, dc): song_list = [] name_list = [] piano_frame = ttk.Frame(root, padding=(3, 3), relief='raised') # Images # record_image = tkinter.PhotoImage(master=root, file='record_image.gif') # stop_image = tkinter.PhotoImage(file='black.square.gif') # play_image = tkinter.PhotoImage(file='play.gif') # Widgets for frame intro_label1 = ttk.Label(piano_frame, text='Welcome to the roomba piano!') intro_label2 = ttk.Label(piano_frame, text='Enter the duration for the notes') intro_label3 = ttk.Label(piano_frame, text='to be played (max 255):') duration_entry = ttk.Entry(piano_frame, width=5) recording_label1 = ttk.Label(piano_frame, text='Press the record button, then play a song.') recording_label2 = ttk.Label(piano_frame, text='Press stop when it is finished, give it a name,') recording_label3 = ttk.Label(piano_frame, text='and then press save to add it to your list. You') recording_label4 = ttk.Label(piano_frame, text='can play that song at any time by selecting') recording_label5 = ttk.Label(piano_frame, text='it in the box and then pressing play.') record_button = ttk.Button(piano_frame, text='Record', width=6) stop_button = ttk.Button(piano_frame, text='Stop', width=5) play_button = ttk.Button(piano_frame, text='Play Song') saved_songs_listbox = Listbox(piano_frame, height=6, width=30, selectmode='SINGLE') save_label = ttk.Label(piano_frame, text='Give your song a title:') save_entry = ttk.Entry(piano_frame, width=15) save_button = ttk.Button(piano_frame, text='Save Song') # delete_button = ttk.Button(piano_frame, text='Delete Song') # White keys constructed white_note_values = [31, 33, 35, 36, 38, 40, 41, 43, 45, 47, 48, 50, 52, 53, 55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72, 74, 76, 77, 79, 81, 83, 84, 86, 88, 89, 91, 93, 95, 96, 98, 100, 101, 103, 105, 107, 108, 110, 112, 113, 115, 117, 119, 120, 122, 124, 125, 127] letter_notes = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] white_keys = [] for k in range(len(white_note_values)): white_keys = white_keys + [ttk.Button(piano_frame, width=2)] # Sets text for white keys white_keys[0]['text'] = 'G' index = 0 for k in range(1, len(white_keys)): white_keys[k]['text'] = letter_notes[index] index = index + 1 if index > 6: index = 0 # White keys' commands for k in range(len(white_keys)): set_index(white_keys, k, dc, white_note_values, duration_entry) # Widget commands record_button['command'] = lambda: record_song(dc, 'start') stop_button['command'] = lambda: record_song(dc, None) save_button['command'] = lambda: add_song_to_list(dc, save_entry.get(), saved_songs_listbox, song_list, name_list) play_button['command'] = lambda: play_song(dc, saved_songs_listbox.get('active'), song_list, name_list) # delete_button['command'] = lambda: delete_song(name_list, song_list, saved_songs_listbox) # Grid the keys piano_frame.grid() intro_label1.grid(row=0, columnspan=10, sticky='W') intro_label2.grid(row=1, columnspan=10, sticky='W') intro_label3.grid(row=2, columnspan=10, sticky='W') duration_entry.grid(row=2, column=6, columnspan=2, sticky='E') recording_label1.grid(row=0, column=12, columnspan=12, sticky='W') recording_label2.grid(row=1, column=12, columnspan=12, sticky='W') recording_label3.grid(row=2, column=12, columnspan=12, sticky='W') recording_label4.grid(row=3, column=12, columnspan=12, sticky='W') recording_label5.grid(row=4, column=12, columnspan=12, sticky='W') record_button.grid(row=1, column=28, columnspan=2, sticky='W') stop_button.grid(row=1, column=30, columnspan=2, sticky='W') play_button.grid(row=1, column=32, columnspan=5, sticky='W') saved_songs_listbox.grid(row=0, rowspan=5, column=38, columnspan=10) save_label.grid(row=0, column=26, columnspan=12, sticky='W') save_entry.grid(row=0, column=32, columnspan=12, sticky='W') save_button.grid(row=2, column=28, columnspan=4) # delete_button.grid(row=2, column=32, columnspan=5, sticky='W') for k in range(len(white_keys)): white_keys[k].grid(row=10, column=k, pady=3)