class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid(sticky=N+S+E+W) self.mainframe() def mainframe(self): self.data = Listbox(self, bg='red') self.scrollbar = Scrollbar(self.data, orient=VERTICAL) self.data.config(yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.data.yview) for i in range(1000): self.data.insert(END, str(i)) self.run = Button(self, text="run") self.stop = Button(self, text="stop") self.data.grid(row=0, column=0, rowspan=4, columnspan=2, sticky=N+E+S+W) self.data.columnconfigure(0, weight=1) self.run.grid(row=4,column=0,sticky=EW) self.stop.grid(row=4,column=1,sticky=EW) self.scrollbar.grid(column=2, sticky=N+S)
class FeasDisp(ttk.Frame): """Widget for displaying all of the feasible states in the conflict.""" def __init__(self, master=None, conflict=None, *args): """Initialize the widget.""" ttk.Frame.__init__(self, master, padding=5) self.columnconfigure(1, weight=1) self.rowconfigure(2, weight=1) self.conflict = conflict self.dispFormat = StringVar(value='pattern') self.dispList = StringVar() self.feasList = [] self.fmts = {'Pattern': 'YN-', 'List (YN)': 'YN', 'List (ordered and [decimal])': 'ord_dec'} cBoxOpts = ('Pattern', 'List (YN)', 'List (ordered and [decimal])') self.feasText = ttk.Label(self, text='Feasible States') self.feasText.grid(row=0, column=0, columnspan=3) self.cBox = ttk.Combobox(self, textvariable=self.dispFormat, values=cBoxOpts, state='readonly') self.cBoxLb = ttk.Label(self, text='Format:') self.feasLBx = Listbox(self, listvariable=self.dispList) self.scrl = ttk.Scrollbar(self, orient=VERTICAL, command=self.feasLBx.yview) # ########### self.cBoxLb.grid(column=0, row=1, sticky=NSEW, pady=3) self.cBox.grid(column=1, row=1, columnspan=2, sticky=NSEW, pady=3) self.feasLBx.grid(column=0, row=2, columnspan=2, sticky=NSEW) self.scrl.grid(column=2, row=2, sticky=NSEW) self.cBox.bind('<<ComboboxSelected>>', self.fmtSel) self.feasLBx.configure(yscrollcommand=self.scrl.set) self.dispFormat.set('Pattern') self.fmtSel() def fmtSel(self, *args): """Action on selection of a new format.""" self.refreshList() def setFeas(self, feasList): """Change the list of feasible states to be displayed.""" self.feasList = feasList self.refreshList() def refreshList(self): """Update the list of feasible states displayed and the format.""" fmt = self.fmts[self.dispFormat.get()] if fmt == "YN-": feas = self.conflict.feasibles.dash if fmt == "YN": feas = self.conflict.feasibles.yn if fmt == "ord_dec": feas = self.conflict.feasibles.ordDec self.dispList.set(tuple(feas))
def Listatag(self): # Lista de tags * em fase de teste title = ['189.186.63.44.20','123.145.584.55.5', '','',''] titleList = Listbox(self, height=5) for t in title: titleList.insert(END, t) titleList.grid(row=7, column=2, columnspan=2, pady=5, sticky=W+E) titleList.bind("<<ListboxSelect>>", self.newTitle)
def initUI(self): self.parent.title("TVstream manager") self.stytle = ttk.Style() self.pack(fill=BOTH, expand=1) self.columnconfigure(0, weight=1, pad=2) self.columnconfigure(2, weight=1, pad=2) self.columnconfigure(4, pad=7) #self.rowconfigure(3, weight=1) #self.rowconfigure(4, weight=1, pad=7) lbll = Label(self, text="Lingua") lbll.grid(row=0,column=0,sticky=W, pady=4, padx=5) lble = Label(self, text="Emittenti") lble.grid(row=0,column=2,sticky=W, pady=1, padx=5) global langlst scrollang = Scrollbar(self) langlst = Listbox(self,font='Arial 9',yscrollcommand=scrollang.set) scrollang.config(command = langlst.yview) for i in lingue: langlst.insert(END, i) langlst.focus_set() langlst.bind("<<ListboxSelect>>", self.onSelectLang) langlst.grid(row=1,column=0, columnspan=2, padx=6,sticky=E+W+S+N) scrollang.grid(row=1,column=1, sticky=E+S+N) global emitlst scrollemit = Scrollbar(self) emitlst = Listbox(self,font='Arial 9',yscrollcommand=scrollemit.set) scrollemit.config(command = emitlst.yview ) emitlst.bind("<<ListboxSelect>>", self.onSelectEmittente) emitlst.grid(row=1,column=2, columnspan=2, padx=5,sticky=E+W+S+N) scrollemit.grid(row=1,column=3,sticky=E+S+N) lbltxt = Label(self, text="Output log") lbltxt.grid(row=2,column=0, columnspan=3, sticky=W, pady=4, padx=5) global area area = Text(self,height=10,font='Arial 9') area.grid(row=3, column=0, columnspan=5, rowspan=1, padx=5, sticky=E+W+S+N) scrolltxt = Scrollbar(self) scrolltxt.config(command = area.yview) scrolltxt.grid(row=3,column=4, columnspan=1, rowspan=1, sticky=E+N+S) play = Button(self, text='Play', command=self.playUrl, bg='gray', fg='black') play.grid(row=1,column=4,padx=4,sticky=E+W)
def _about_creatures(self): lb = Listbox(self.frame, height=15, width=50, selectmode=SINGLE) lb.bind('<<ListboxSelect>>', self._onselect) lb.grid(row=1, column=2) items = self.model.creatures.items() items = sorted(items, key=lambda k: k[0][0] * self.model.width + k[0][1]) for (x, y), creature in items: lb.insert(END, [x, y, creature.life]) self.canvas = NeuroCanvas(self.frame, (2, 2), 400, 300)
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 initUI(self): self.parent.title("Listbox") self.pack(fill=BOTH, expand=1) IP_list = ['IP Address 1', 'IP Address 2', 'IP Address 3', 'IP Address 4', 'IP Address 5', 'IP Address 6', 'IP Address 7', 'IP Address 8', 'IP Address 9', 'IP Address 10', 'IP Address 11', 'IP Address 12', 'IP Address 13', 'IP Address 14', 'IP Address 15', 'IP Address 16'] IP_numbers = ['150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1'] lb = Listbox(self) for i in IP_list: lb.insert(END, i) lb.bind("<<ListboxSelect>>", self.onSelect) lb.place(x=20, y=20) self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) self.label.place(x=20, y=270) # self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(3, weight=1) self.rowconfigure(5, pad=7) #lbl = Label(self, text="Windows") lb.grid(sticky=W, pady=40, padx=50) #lb = Text(self) lb.grid(row=1, column=0, columnspan=2, rowspan=4, padx=50, sticky=E+W+S+N) abtn = Button(self, text="Activate") abtn.grid(row=1, column=3) cbtn = Button(self, text="Close") cbtn.grid(row=2, column=3, pady=4) hbtn = Button(self, text="Help") hbtn.grid(row=5, column=0, padx=5) obtn = Button(self, text="OK") obtn.grid(row=5, column=3)
def new_random_swiss(main): players = [] def add_player(event): if e.get() is "": return players.append(e.get()) Lb.delete(0,END) for x in players: Lb.insert(0,x) e.delete(0,END) def remove_player(): l=len(players)-1 if Lb.curselection(): for x in Lb.curselection(): Lb.delete(x) players.pop(l-x) else: Lb.delete(0) players.pop(-1) Lb.delete(0,END) for x in players: Lb.insert(0,x) top = Toplevel(main) top.title("New Random Swiss") top.bind("<Return>",add_player) center_size(top,360,180) Label(top, text='Name:').grid(row=0,column=0) e = Entry(top,width=12) e.grid(row=0,column=1) e.focus_force() Button(top,text='Add', command=lambda:add_player(None) ).grid(row=1,column=0) Button(top,text='Remove', command=remove_player ).grid(row=1,column=1) Button(top,text='Cancel', command=top.destroy ).grid(row=2,column=0) Button(top,text='Finish', command=lambda:create_single_swiss(players,main)).grid(row=2,column=1) Sb = Scrollbar(top) Sb.grid(row=0,column=3,rowspan=3) Lb = Listbox(top,selectmode=EXTENDED,yscrollcommand=Sb.set) Lb.grid(row=0,rowspan=3,column=2) Sb.config(command=Lb.yview)
def setupGui(): global window global labelShows, labelEpisodes, labelDownloads global listShows, listEps, listDownloads global btnAbout, btnDownload, btnChooseFolder global folderFrame global folderName window = Tk() window.title('iView') window.minsize(300, 200) labelShows = Label(window, text='Shows') labelShows.grid(column=0, row=0, sticky=[N,S,E,W]) listShows = Listbox(window) listShows.grid(column=0, row=1, sticky=[N,S,E,W]) listShows.bind('<<ListboxSelect>>', indexEpsEv) indexShows() labelEpisodes = Label(window, text='Episodes') labelEpisodes.grid(column=1, row=0, sticky=[N,S,E,W]) listEps = Listbox(window) listEps.grid(column=1, row=1, sticky=[N,S,E,W]) listEps.bind('<<ListboxSelect>>', setEpNumEv) indexEps(0) labelDownloads = Label(window, text='Downloads') labelDownloads.grid(column=2, row=0, sticky=[N,S,E,W]) listDownloads = Listbox(window) listDownloads.grid(column=2, row=1, sticky=[N,S,E,W]) btnAbout = Button(window, text='About', command=about) btnAbout.grid(column=0, row=2, sticky=[N,S,E,W]) btnDownload = Button(window, text='Download', command=download) btnDownload.grid(column=1, row=2, sticky=[N,S,E,W]) btnChooseFolder = Button(window, text='Choose Download Folder', command=chooseDir) btnChooseFolder.grid(column=2, row=2, sticky=[N,S,E,W]) folderName = Text(window, height=1) folderName.grid(column=0, row=3, columnspan=3) folderName.insert(END, expanduser("~")+(':Videos:iView:'.replace(':', os.sep))) window.columnconfigure(0, weight=1) window.columnconfigure(1, weight=1) window.columnconfigure(2, weight=1) window.rowconfigure(1, weight=1) def updateDownloadList(): refreshDownloadList() window.after(1000, updateDownloadList) dlListThrd = threading.Thread(target=updateDownloadList) dlListThrd.setName('Update Download List') dlListThrd.start()
class SelectDeviceFrame(CopilotInnerFrame): def __init__(self, master, config, state): super(SelectDeviceFrame, self).__init__(master, config) self._state = state if self._state.action == 'copy': self._frame_lbl['text'] = 'Copy To Device' elif self._state.action == 'delete': self._frame_lbl['text'] = 'Delete From Device' self._next_btn['command'] = self._next_cmd self._dev_list = Listbox(self._master, font=self._config.item_font) self._dev_list.grid(row=1, column=0, columnspan=3, sticky='nsew') self._dev_list.configure(yscrollcommand=self._sb.set) self._sb['command'] = self._dev_list.yview self._refresh_drives() def _next_cmd(self): if len(self._dev_list.curselection()) > 0: item_idx = int(self._dev_list.curselection()[0]) self._state.to_device = self._parts[item_idx] if self._state.action == 'copy': self._new_state_window(DeviceToFrame, self._state) elif self._state.action == 'delete': self._new_state_window(CopyFileFrame, self._state) def _refresh_drives(self): self._parts = [] for drive in usb_drives(): for part in drive.partitions(): drive_opt = DriveOption(drive, part) self._parts.append(drive_opt) self._dev_list.insert('end', drive_opt)
author_text = StringVar() e2 = Entry(window, textvariable=author_text) e2.grid(row=0, column=3) year_text = StringVar() e3 = Entry(window, textvariable=year_text) e3.grid(row=1, column=1) isbn_text = StringVar() e4 = Entry(window, textvariable=isbn_text) e4.grid(row=1, column=3) # listbox lb1 = Listbox(window, height=6, width=35) lb1.grid(row=2, column=0, rowspan=6, columnspan=2) # scroll bar sb1 = Scrollbar(window) sb1.grid(row=2, column=2, rowspan=6) # apply scroll bar to listbox lb1.configure(yscrollcommand=sb1.set) sb1.configure(command=lb1.yview) # bind function to event type lb1.bind('<<ListboxSelect>>', get_selected_row) # buttons b1 = Button(window, text="View All", width=12, command=view) b1.grid(row=2, column=3)
class SectionTrois(Frame): """ """ def __init__(self, master, controller): Frame.__init__(self, master) self._controller = controller self.labels_() self.liste_box_historique() self.liste_box_solution() self.btn_supp_derniere_opetation() def labels_(self): """ """ self._label = Label(self, text="Historique de vos opérations", font=("Helvetica", 10, "bold"), pady=2) self._label.grid(row=0, column=0, padx=130, pady=5) self._label_s = Label( self, text= "Cliquez sur le bouton solution pour voir la resolution de cette partie !", font=("Helvetica", 10, "bold"), wraplength=200, pady=2) self._label_s.grid(row=0, column=1, padx=130, pady=5) def liste_box_historique(self): """ """ self._listebox_historique = Listbox(self, bd=2, relief="groove", width=50, font=("Helvetica", 10, "bold"), activestyle="none") self._listebox_historique.grid(row=1, column=0, pady=2) def liste_box_solution(self): self._listebox_solution = Listbox(self, bd=2, relief="groove", width=50, font=("Helvetica", 10, "bold"), activestyle="none") self._listebox_solution.grid(row=1, column=1, pady=2) def btn_supp_derniere_opetation(self): """ """ self._btn = Bouton( self, "SUPP derniere opération", lambda: self._controller. supprimer_derniere_operation(self._listebox_historique)) self._btn.fixer_des_options(font=("Helvetica", 15), state="disabled", padx=2, pady=5) self._btn.grid(row=2, column=0, pady=5) def activer_btn_supp(self): """ """ self._btn.fixer_des_options(state="normal") def desactive_btn_supp(self): """ """ self._btn.fixer_des_options(state="disabled") def afficher_operation(self, operation, indice_operateur): """ Affiche l'operation réçue en paramètre """ if self._btn["state"] == "disabled": self.activer_btn_supp() if indice_operateur == 1: if operation[0] >= operation[1]: self._listebox_historique.insert('end', [ operation[0], LES_OPERATEURS[1], operation[1], "=", operation[2] ]) else: self._listebox_historique.insert('end', [ operation[1], LES_OPERATEURS[1], operation[0], "=", operation[2] ]) elif indice_operateur == 3: if operation[0] % operation[1] == 0: self._listebox_historique.insert('end', [ operation[0], LES_OPERATEURS[3], operation[1], "=", operation[2] ]) else: self._listebox_historique.insert('end', [ operation[1], LES_OPERATEURS[3], operation[0], "=", operation[2] ]) else: self._listebox_historique.insert('end', [ operation[0], LES_OPERATEURS[indice_operateur], operation[1], "=", operation[2] ]) def vider_historique(self): """ """ self._listebox_historique.delete(0, 'end') def vider_solution(self): """ """ self._listebox_solution.delete(0, 'end')
def launch_app(): """ This function launch the program main frame """ mainframe = Tk() mainframe.title("Log File Analyzer") # center_window(parent=mainframe) header_label = Label(mainframe, text="Bienvenue dans Log File Analyzer." "Pour commencer, sélectionnez votre fichier de log." " Ensuite, veuillez préciser le type de log choisi", font=HEADER_MSG_LABEL) header_label.grid(row=0, columnspan=6, padx=20, pady=20) load_file_button = Button(mainframe, text='Sélectionner le fichier', command=lambda: open_file( load_file_label, number_lines_file_label, name_file_label)) load_file_button.grid(row=1, column=0, sticky=E, padx=20, pady=20) load_file_label = Label(mainframe, text=FILE_INFO['path'], font="Arial 10 italic") load_file_label.grid(row=1, column=1, columnspan=5, sticky=W, padx=20, pady=20) file_type = Label(mainframe, text="Type de fichier:", font=LABEL_BOLD_FONT) file_type.grid(row=2, sticky=E, padx=20, pady=20) log_type_var = StringVar(mainframe) # Set with options log_type_choices = list(FILE_PROPERTIES.keys()) log_type_var.set("-" * 10) # set the default option log_file_types = OptionMenu(mainframe, log_type_var, *log_type_choices) log_file_types.grid(row=2, column=1) filter_frames = {} # link function to change dropdown log_type_var.trace('w', lambda *args: change_log_file_type(log_type_var, filter_frames)) file_name = Label(mainframe, text="Nom du fichier:", font=LABEL_BOLD_FONT) file_name.grid(row=3, sticky=E, padx=20, pady=20) name_file_label = Label(mainframe, text='', font="Arial 10 italic") name_file_label.grid(row=3, column=1, columnspan=3, sticky=W, padx=20, pady=20) nb_lines = Label(mainframe, text="Nombre de lignes:", font=LABEL_BOLD_FONT) nb_lines.grid(row=4, sticky=E, padx=20, pady=20) number_lines_file_label = Label(mainframe, text='', font="Arial 10 italic") number_lines_file_label.grid(row=4, column=1, columnspan=3, sticky=W, padx=20, pady=20) for log_type_name in log_type_choices: filter_frame = Frame(mainframe) filter_frames[log_type_name] = filter_frame columns_names = FILE_PROPERTIES[log_type_name] searched_columns = {} searched_buttons = {} searched_result_listboxes = {} for column_index, column_value in enumerate(columns_names): new_search_label = Label(filter_frame, text=columns_names[column_index], font=LABEL_BOLD_FONT) new_search_label.grid(row=column_index, column=0, padx=20, pady=20, sticky=E) searched_columns[column_value] = StringVar() new_search_entry = Entry(filter_frame, textvariable=searched_columns[column_value]) new_search_entry.grid(row=column_index, column=1, padx=20, pady=20, sticky=W) new_listbox = Listbox(filter_frame) new_listbox.grid(row=column_index, column=3, padx=20, pady=20, sticky=W + E) new_scrollbar = Scrollbar(filter_frame, orient=VERTICAL, command=new_listbox.yview, width=30) new_scrollbar.grid(row=column_index, column=4) new_listbox.config(height=5, width=40, yscrollcommand=new_scrollbar.set) searched_result_listboxes[column_value] = new_listbox new_search_button = Button(filter_frame, text='->', command=lambda local_log_type_var=log_type_var, local_index=column_index, local_searched_column=searched_columns[column_value], local_result_list_box=searched_result_listboxes[column_value] : find_filter_field( local_log_type_var, local_index, local_searched_column, local_result_list_box, FILE_INFO['path'])) new_search_button.grid(row=column_index, column=2, padx=20, pady=20, sticky=W + E) searched_buttons[column_value] = new_search_button search_button = Button(filter_frame, text=' RECHERCHER ', command=lambda local_searched_columns=searched_columns: show_result_modal( mainframe, log_type_var, local_searched_columns, FILE_INFO['path'], FILE_PROPERTIES)) search_button.grid(row=len(columns_names), column=1, sticky=W, padx=20, pady=20) mainframe.mainloop()
class ChoixEcole: def __init__(self): # Initialise l'application change le titre et la positionne self.root = Tk() self.root.title("ChoixEcole") """Ouvre la base de données""" basededonne = filedialog.askopenfilename( title="Ouvrir un fichier", filetypes=[("db file", ".db")] ) model.connec(basededonne) """Ajoute un menu""" menubar = Menu(self.root) self.root.config(menu=menubar) menufichier = Menu(menubar, tearoff=0) menubar.add_cascade(label="Fichier", menu=menufichier) menufichier.add_command(label="Enregistrer ", command=self.save_file) menufichier.add_command(label="Enregistrer sous", command=self.save_file_as) self.filename = () self.root.resizable(False, False) self.entry_ecole = tkscrolled.ScrolledText(self.root, width=40, height=10,) self.button = [] self.ecolesselect = {} ######################################################################## # NOTES # ######################################################################## # On considère les notes entrées par l'utilisateur (sous forme de # "StringVar"). À chaque modification d'une de ces variables, on met # tout à jour. self.notes_vars = { "maths": StringVar(self.root), "physique": StringVar(self.root), "si": StringVar(self.root), "informatique": StringVar(self.root), "anglais": StringVar(self.root), "francais": StringVar(self.root), } for var in self.notes_vars.values(): var.trace("w", self.update) # self.notes représente soit une erreur de saisie des notes (avec None) # soit un dictionnaire "matière -> note(float)". self.notes = None ######################################################################## # CHOIX # ######################################################################## # On crée un dictonnaire modifié a chaque clique sur la ListeBox. self.choix = { "regions": None, "specialites": None, "alternance": None, "concours": None, "annee": None, } self.varsbuttons = { "specialites": IntVar(self.root), "regions": IntVar(self.root), "concours": IntVar(self.root), "alternance": IntVar(self.root), "annee": IntVar(self.root), "ecole": IntVar(self.root), } ######################################################################## # RENDU FORMULAIRE NOTES # ######################################################################## self.scale = Scale( self.root, orient="horizontal", from_=0, to=100, resolution=1, tickinterval=25, length=100, label="Augmentation %", command=self.update, ) Label(self.root, text="Maths").grid(row=2, column=1) Entry(self.root, textvariable=self.notes_vars["maths"]).grid(row=3, column=1) Label(self.root, text="Physique").grid(row=4, column=1) Entry(self.root, textvariable=self.notes_vars["physique"]).grid(row=5, column=1) Label(self.root, text="Si").grid(row=6, column=1) Entry(self.root, textvariable=self.notes_vars["si"]).grid(row=7, column=1) Label(self.root, text="Informatique").grid(row=8, column=1) Entry(self.root, textvariable=self.notes_vars["informatique"]).grid( row=9, column=1 ) Label(self.root, text="Anglais").grid(row=10, column=1) Entry(self.root, textvariable=self.notes_vars["anglais"]).grid(row=11, column=1) Label(self.root, text="Francais").grid(row=12, column=1) Entry(self.root, textvariable=self.notes_vars["francais"]).grid( row=13, column=1 ) ######################################################################## # RENDU FORMULAIRE choix # ######################################################################## self.specialites = Listbox( self.root, selectmode="multiple", exportselection=0, width=20, height=10 ) Label(self.root, text="Specialite").grid(row=0, column=6) self.specialites = Listbox( self.root, selectmode="multiple", exportselection=0, width=20, height=10 ) Label(self.root, text="Specialite").grid(row=0, column=6) self.regions = Listbox( self.root, selectmode="multiple", exportselection=0, width=20, height=10 ) Label(self.root, text="Region").grid(row=0, column=7) self.alternance = Listbox(self.root, exportselection=0, width=6, height=3) Label(self.root, text="Alternance").grid(row=11, column=6) self.concours = Listbox( self.root, selectmode="multiple", exportselection=0, width=20, height=10 ) Label(self.root, text="Admission").grid(row=0, column=9) self.annee = Listbox(self.root, exportselection=0, width=6, height=3) Label(self.root, text="Année").grid(row=11, column=7) self.specialites.grid(row=2, column=6, rowspan=10, padx=10) self.regions.grid(row=2, column=7, rowspan=10, padx=10) self.alternance.grid(row=13, column=6, rowspan=10, padx=10) self.concours.grid(row=2, column=9, rowspan=10, padx=10) self.annee.grid(row=13, column=7, rowspan=10, padx=10) ######################################################################## # Insertion des Bouton Peu importe # ######################################################################## Checkbutton( self.root, variable=self.varsbuttons["specialites"], text="Peu importe", command=self.update, ).grid(row=1, column=6) Checkbutton( self.root, variable=self.varsbuttons["regions"], text="Peu importe", command=self.update, ).grid(row=1, column=7) Checkbutton( self.root, variable=self.varsbuttons["alternance"], text="Peu importe", command=self.update, ).grid(row=12, column=6) Checkbutton( self.root, variable=self.varsbuttons["concours"], text="Peu importe", command=self.update, ).grid(row=1, column=9) Button( self.root, text="Plus d'information", command=self.information, width=15 ).grid(row=2, column=31) Button(self.root, text="Prix", command=self.calculprix, width=15).grid( row=2, column=32 ) ######################################################################## # Insertion des données # ######################################################################## for specialite in model.renvoie_specialites(): self.specialites.insert("end", specialite) for region in model.renvoie_regions(): self.regions.insert("end", region) for alternance in ["Oui", "Non"]: self.alternance.insert("end", alternance) for concours in model.renvoie_admission(): self.concours.insert("end", concours) for annee in ["3/2", "5/2"]: self.annee.insert("end", annee) ######################################################################## # On bind les ListBox # ######################################################################## self.entry_ecole.grid(row=2, column=20, rowspan=10) self.scale.grid(row=0, column=1, rowspan=2) self.specialites.bind("<<ListboxSelect>>", self.update) self.regions.bind("<<ListboxSelect>>", self.update) self.alternance.bind("<<ListboxSelect>>", self.update) self.concours.bind("<<ListboxSelect>>", self.update) self.annee.bind("<<ListboxSelect>>", self.update) self.update() self.root.mainloop() def valide_maj_notes(self): ######################################################################## # NOTES # ######################################################################## # On récupere la note entrée et on la vérifie try: notes = {} for nom_matiere, note_var in self.notes_vars.items(): note_float = float(note_var.get()) if note_float > 20 or note_float < 0: raise ValueError() else: if len(note_var.get()) in (2, 1): pass elif note_var.get()[2] == "." and len(note_var.get()) < 6: pass elif note_var.get()[1] == "." and len(note_var.get()) < 5: pass else: raise ValueError note_float += (self.scale.get() * note_float) / 100 notes[nom_matiere] = min(20,note_float) notes["modelisation"] = (notes["maths"] + notes["si"]) / 2 self.notes = notes except ValueError: # Une erreur est survenue lors de la conversion des notes self.notes = None def maj_choix(self): ######################################################################## # NOTES # ######################################################################## # On récupere l'index de la spécialite et le texte coché pour les autres variables # Et en fonction de certains cas on dit que self.choix=None self.choix = { "specialites": model.renvoie_idspe( self.specialites.get(i) for i in self.specialites.curselection() ), "regions": tuple(self.regions.get(i) for i in self.regions.curselection()), "concours": tuple( self.concours.get(i) for i in self.concours.curselection() ), "alternance": tuple( self.alternance.get(i) for i in self.alternance.curselection() ), "annee": tuple(self.annee.get(i) for i in self.annee.curselection()), } for cle in self.varsbuttons: if self.varsbuttons[cle].get() == 1: eval('self.'+cle+'.selection_clear(0, "end")') for cle in self.choix: if not self.choix[cle] or self.varsbuttons[cle].get() == 1: self.choix[cle] = None def update(self, *inutile): self.valide_maj_notes() self.maj_choix() self.construit_ecoles() self.affichage() def construit_ecoles(self): """On récupere les écoles disponibles dans la bdd et on les stocke """ self.ecolesselect = {} if self.notes != None: for j, ecoles in enumerate(model.filtre(self.choix, self.notes)): self.ecolesselect[j] = { "var": IntVar(self.root), "id": ecoles[0], "nom": ecoles[1], "admission": ecoles[2], "region": ecoles[3], "Alternance": ecoles[4], "Acronyme": ecoles[5], "Spe": ecoles[6], } def information(self): ######################################################################## # Information # ######################################################################## # Renvoie les spécialite offerte par l'école en fonction du choix de l'utilisateur window = Toplevel(self.root) window.resizable(True, True) vsb = Scrollbar(window, orient="vertical") vsb.grid(row=0, column=1, sticky="ns") hsb = Scrollbar(window, orient="horizontal") hsb.grid(row=1, column=0, sticky="ew") ca = Canvas(window, yscrollcommand=vsb.set, xscrollcommand=hsb.set) ca.grid(row=0, column=0, sticky="news") vsb.config(command=ca.yview) hsb.config(command=ca.xview) window.grid_rowconfigure(0, weight=1) window.grid_columnconfigure(0, weight=1) fr = Frame(ca) i=1 for a in ["Nom","Admission","Region","Alternance","Specialite"]: Label(fr, text=a).grid(row=0, column=i) i+=2 if self.choix["specialites"] == None: ListeSpe = list(self.specialites.get(0, "end")) else: ListeSpe = [ self.specialites.get(i) for i in self.specialites.curselection() ] if self.choix["alternance"] == None: alternance = ["Oui", "Non"] else: alternance = [self.choix["alternance"][0]] ligne = 1 for ecole in self.ecolesselect.values(): if ecole["var"].get() == 1: for i in [value for (key,value) in self.ecolesselect.items() if value['nom']==ecole['nom'] and value["Spe"] in ListeSpe and value["Alternance"] in alternance ]: j=1 for texte in [i["nom"],i["admission"],i["region"],i["Alternance"],i["Spe"]] : a = Entry(fr,width=60) a.insert(0,texte) a.grid(row=ligne, column=j) j+=2 a.config(state="disabled") ligne += 1 ca.create_window(0, 0, window=fr) fr.update_idletasks() ca.config(scrollregion=ca.bbox("all")) def calculprix(self): ecoles = [ecole["admission"] for ecole in self.ecolesselect.values() if ecole["var"].get()==1] prixboursier = model.prix_ecole(ecoles, "Boursier") prixnonboursier = model.prix_ecole(ecoles, "NonBoursier") Label(self.root, text=f"Prix Boursier \n {prixboursier}").grid(row=3, column=32) Label(self.root, text=f"Prix Non Boursier\n {prixnonboursier}").grid( row=4, column=32 ) def convertpdf(self, spacing=2): """Converti en PDF """ pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=12) data = [["Nom", "Résultat"]] admission, listeecoles = self.returntext() data += [[listeecoles[i], admission[i]] for i in range(len(admission))] col_width = pdf.w / 2.5 row_height = pdf.font_size for row in data: for item in row: pdf.cell(col_width, row_height * spacing, txt=item, border=1) pdf.ln(row_height * spacing) pdf.output(self.filename) def returntext(self): """Affiche le nom de l'école et a cote Refuse ou admis""" ecoleamoi = list( set( [ ecoles[5] for ecoles in model.filtre( {choix: None for choix in self.choix}, self.notes ) ] ) ) listeecoles = list( set( [ ecoles[5] for ecoles in model.filtre( {choix: None for choix in self.choix}, {Note: 20 for Note in self.notes}, ) ] ) ) admission = ["Admis"] * len(listeecoles) for i in range(len(listeecoles)): if listeecoles[i] not in ecoleamoi: admission[i] = "Refuse" return admission, listeecoles def save_file(self, whatever=None): if self.filename == (): self.save_file_as() self.convertpdf() def save_file_as(self, whatever=None): self.filename = filedialog.asksaveasfilename( defaultextension=".pdf", filetypes=[("PDF", "*.pdf"),] ) self.convertpdf() def affichage(self): """Affiche les écoles auquel on est admissible """ for i in self.button: i.destroy() self.entry_ecole.configure(state="normal") self.entry_ecole.delete(0.7, "end") if self.notes: textverification = [] for ecole in self.ecolesselect.values(): if ecole["Acronyme"] not in textverification: check = Checkbutton(text=ecole["Acronyme"], variable=ecole["var"]) self.entry_ecole.window_create(0.7, window=check) self.entry_ecole.insert(0.7, "\n") self.button.append(check) textverification.append(ecole["Acronyme"]) else: self.entry_ecole.insert(0.7, "Erreur lors de la saisie des notes.") self.entry_ecole.configure(state="disabled")
class SpeciesSearchDialog: def __init__(self, parent, caller): # main window self.parent = parent # dialog that called this second dialog self.caller = caller self.gui = Toplevel(parent.guiRoot) self.gui.grab_set() self.gui.focus() self.gui.columnconfigure(0, weight=1) self.gui.rowconfigure(1, weight=1) self.entrySearch = Entry(self.gui) self.buttonSearch = Button(self.gui, text=" Search ") self.buttonAdd = Button(self.gui, text=" Add Species ") self.buttonClose = Button(self.gui, text=" Close Window ") self.frameResults = Frame(self.gui) self.frameResults.columnconfigure(0, weight=1) self.frameResults.rowconfigure(0, weight=1) self.scrollResults = Scrollbar(self.frameResults, orient="vertical") self.scrollResults.grid(row=0, column=1, sticky="ns") self.listResults = Listbox(self.frameResults, width=70, height=20) self.listResults.grid(row=0, column=0, sticky="nswe") self.listResults.config(yscrollcommand=self.scrollResults.set) self.scrollResults.config(command=self.listResults.yview) self.entrySearch.grid(row=0, column=0, columnspan=2, sticky="we", padx=5, pady=5) self.frameResults.grid(row=1, column=0, columnspan=3, sticky="nswe", padx=5, pady=5) self.buttonSearch.grid(row=0, column=2, padx=5, pady=5, sticky="e") self.buttonAdd.grid(row=2, column=1, padx=5, pady=5, sticky="e") self.buttonClose.grid(row=2, column=2, padx=5, pady=5, sticky="e") self.gui.protocol("WM_DELETE_WINDOW", self.actionClose) self.buttonClose.bind("<ButtonRelease>", self.actionClose) self.buttonAdd.bind("<ButtonRelease>", self.actionAdd) self.buttonSearch.bind("<ButtonRelease>", self.actionSearch) self.entrySearch.bind("<Return>", self.actionSearch) self.gui.update() self.gui.minsize(self.gui.winfo_width(), self.gui.winfo_height()) self.gui.mainloop() def actionAdd(self, event): try: selection = self.listResults.selection_get() selectionSplit = selection.split(":\t", 1) selectionSplit2 = selectionSplit[1].split("\t") if not (selectionSplit[0], selectionSplit2[0]) in self.parent.optimizer.speciesList: self.parent.optimizer.speciesList.append((selectionSplit[0], selectionSplit2[0].strip())) self.caller.gui.event_generate("<<Update>>") except tkinter.TclError: # no selection pass def actionSearch(self, event): query = self.entrySearch.get() if query: self.listResults.delete(0, "end") results = self.parent.optimizer.SPSUMHandler.search(query) # sort results by nr of CDS results = sorted(results.items(), reverse=True, key=lambda x: (int(x[1][1]))) for name, (taxid, ncs) in results: self.listResults.insert("end", taxid + ":\t " + name + " \t(" + ncs + " CDS)") def actionClose(self, event=None): self.caller.gui.event_generate("<<Update>>", when="tail") self.gui.destroy()
addRecord = Button(frame1, text="Nowy Rekord", command=addRec) deleteRecord = Button(frame1, text="Usuń Rekord gdzie ->", command=delRec) record = Listbox(frame1, height=4) record.insert(1, "Id") record.insert(2, "Imię") record.insert(3, "Nazwisko") record.insert(4, "Wiek") l = Label(frame1, text="=") where = Entry(frame1) name.grid(row=0, column=0) dbName.grid(row=0, column=1) user.grid(row=0, column=2) userName.grid(row=0, column=3) surname.grid(row=0, column=4) userSurname.grid(row=0, column=5) age.grid(row=0, column=6) userAge.grid(row=0, column=7) createDb.grid(row=1, column=0) disconnect.grid(row=1, column=1) addRecord.grid(row=1, column=2) deleteRecord.grid(row=1, column=3) record.grid(row=1, column=4) l.grid(row=1, column=5) where.grid(row=1, column=6) frame1.grid(row=0) frame.grid(row=2) mainloop()
class Pdf_converter: def __init__(self): self._root = Tk() self._root.geometry("500x400") self._root.title("IMGPDF") self._Elements() Grid.rowconfigure(self._root, 0, weight=1) Grid.columnconfigure(self._root, 0, weight=1) self.supportedfiles = [ ('PDF files', '*.pdf*'), ('jpg files', '*.jpg*'), ('png files', '*.png*'), ('gif files', '*.gif*'), ('All files', '*.*') ] self.openfiles = [] self._root.mainloop() def _Elements(self): ##create button self._create = Button(self._root, text="Create", command=self._Create_pdf) ##lift up self._lift = Button(self._root, text="↑ Lift Up", command=self._Lift_up) ##push down self._push = Button(self._root, text="↓ Push Down", command=self._Push_down) ##addfiles self._addfiles = Button(self._root, text="Add Files", command=self._Select_files) ##scrollbars self._hscroll = Scrollbar(self._root, orient=HORIZONTAL) self._vscroll = Scrollbar(self._root) ##Listwidget / List box self._listbox = Listbox(self._root, width=40, xscrollcommand=self._hscroll.set, yscrollcommand=self._vscroll.set) self._hscroll.config(command=self._listbox.xview) self._vscroll.config(command=self._listbox.yview) #packing self._listbox.grid(column=0, columnspan=4, row=0, rowspan=6, sticky=N + E + W + S) self._hscroll.grid(column=0, row=6, columnspan=4, sticky=W + E) self._vscroll.grid(column=4, row=0, rowspan=6, sticky=N + S) self._addfiles.grid(column=3, row=7, sticky=W + E) self._create.grid(column=2, row=7, sticky=W + E) self._push.grid(column=5, row=1, sticky=S + E + W) self._lift.grid(column=5, row=0, sticky=N + W + E) def _Lift_up(self): #"to lift the element up." try: current = self._listbox.curselection()[0] value = self._listbox.get(current) if current != 0: upper = current - 1 self._listbox.insert(current, self._listbox.get(upper)) self._listbox.delete(current + 1) self._listbox.insert(upper, value) self._listbox.delete(upper + 1) self._listbox.selection_set(upper) self._listbox.activate(upper) except: print("Error in Lift Up") def _Push_down(self): #"to push the item down." try: current = self._listbox.curselection()[0] value = self._listbox.get(current) if current < self._listbox.size() - 1: lower = current + 1 self._listbox.insert(current, self._listbox.get(lower)) self._listbox.delete(current + 1) self._listbox.insert(lower, value) self._listbox.delete(lower + 1) self._listbox.selection_set(lower) self._listbox.activate(lower) except: print("Error in Push Down") def _Select_files(self): names = askopenfilename(defaultextension=".pdf", filetypes=self.supportedfiles, multiple=True) for file in names: self._listbox.insert(END, file) def _Create_pdf(self): #"To create pdf of the images and join then in the given sequence." self.final = asksaveasfilename(initialfile="merged.pdf", defaultextension=".pdf", filetypes=[('PDF files', '*.pdf*')]) self._merger() def _merger(self): file_list = self._listbox.get(0, END) newfile = self.final[:-4] + '0.pdf' if file_list[0][-4:] == '.jpg' or file_list[0][ -4:] == '.png' or file_list[0][-4:] == '.gif': fname = file_list[0][:-4] + '.pdf' image = Image.open(file_list[0]) pdf = image.convert('RGB') pdf.save(newfile) image.close() elif file_list[0][-4:] == '.pdf': pdf = open(file_list[0], 'rb') image = pdf.read() pdf.close() pdf = open(newfile, 'wb') pdf.write(image) pdf.close() for i in range(len(file_list)): if i != 0: pdfname = self.final[:-4] + '_' + str(i) + '.pdf' if file_list[i][-4:] == '.jpg' or file_list[i][ -4:] == '.png' or file_list[i][-4:] == '.gif': fname = file_list[i][:-4] + '.pdf' image = Image.open(file_list[i]) pdf = image.convert('RGB') pdf.save(pdfname) image.close() elif file_list[i][-4:] == '.pdf': pdf = open(file_list[i], 'rb') image = pdf.read() pdf.close() pdf = open(pdfname, 'wb') pdf.write(image) pdf.close() pdflist = [newfile, pdfname] merger = PdfFileMerger() for pdfs in pdflist: pdf = (open(pdfs, 'rb')) self.openfiles.append(pdf) merger.append(self.openfiles[-1]) newfile = newfile = self.final[:-4] + str(i) + '.pdf' with open(newfile, 'wb') as f: merger.write(f) self.openfiles[-1].close() self.openfiles[-2].close() remove(pdfname) remove(self.final[:-4] + str(i - 1) + '.pdf') pdf = open(newfile, 'rb') data = pdf.read() pdf.close() remove(newfile) pdf = open(self.final, 'wb') pdf.write(data) pdf.close()
class EquipamentoView(object): _janelaPrincipal_ = Tk() _equipamentoLabel_ = None _consumoLabel_ = None _horasLabel_ = None _precoLabel_ = None _totalLabel_ = None _equipamentoEntry_ = None _consumoEntry_ = None _horasEntry_ = None _precoEntry_ = None _insereButton_ = None _carregaButton_ = None _calculaButton_ = None _listaListBox_ = None def lerEquipamento(self): nome = self._equipamentoEntry_.get() consumo = int(self._consumoEntry_.get()) horas = int(self._horasEntry_.get()) equipamento = EquipamentoModelo(nome,consumo,horas) return equipamento def adicionaEquipamentoLista(self,equipamento): self._listaListBox_.insert(END,equipamento) def mostraTotal(self,total): preco = float(self._precoEntry_.get()) total = total * preco self._totalLabel_["text"] = "Total R$: " + str(total) def __init__(self,insereComando,carregaComando,calculaComando) -> None: super().__init__() self._equipamentoLabel_ = Label(master=self._janelaPrincipal_,text="Equipamento:") self._consumoLabel_ = Label(master=self._janelaPrincipal_,text="Consumo (KWh):") self._horasLabel_ = Label(master=self._janelaPrincipal_,text="Horas:") self._precoLabel_ = Label(master=self._janelaPrincipal_,text="Preco:") self._totalLabel_ = Label(master=self._janelaPrincipal_,text="Total R$:") self._equipamentoEntry_ = Entry(master=self._janelaPrincipal_,width = 20 ) self._consumoEntry_ = Entry(master=self._janelaPrincipal_,width = 4 ) self._horasEntry_ = Entry(master=self._janelaPrincipal_,width = 3 ) self._precoEntry_ = Entry(master=self._janelaPrincipal_,width = 5 ) self._insereButton_ = Button(master=self._janelaPrincipal_,text="Insere",command=insereComando) self._carregaButton_ = Button(master=self._janelaPrincipal_,text="Carrega",command=carregaComando) self._calculaButton_ = Button(master=self._janelaPrincipal_,text="Calcula",command=calculaComando) self._listaListBox_ = Listbox(master=self._janelaPrincipal_,width=40) self._equipamentoLabel_.grid(row=1,column=1) self._equipamentoEntry_.grid(row=1,column=2) self._consumoLabel_.grid(row=1,column=3) self._consumoEntry_.grid(row=1,column=4) self._horasLabel_.grid(row=2,column=1) self._horasEntry_.grid(row=2,column=2) self._precoLabel_.grid(row=2,column=3) self._precoEntry_.grid(row=2,column=4) self._insereButton_.grid(row=3,column=1) self._carregaButton_.grid(row=3,column=2) self._calculaButton_.grid(row=4,column=1) self._totalLabel_.grid(row=4,column=2) self._listaListBox_.grid(row=5,column=1,columnspan=3) def executar(self): self._janelaPrincipal_.mainloop()
class Shortcut_: def __init__(self, root): self.root = root self.root.wm_title("Johns' Docs Mapper") self.shares1 = [] self.shares2 = [] self.shares3 = [] self.listbox = Listbox(self.root, bg="gray", height=8, width=50) self.listbox.grid(row=5, rowspan=20, column=0, columnspan=5, sticky="e") self.lbl1 = ttk.Label(self.root, text='Loading... (Please Wait)') self.lbl1.grid(row=0, column=0, columnspan=3, sticky=W) bt2 = ttk.Button(self.root, text='Map Selected', command=self.Map_Selected) bt2.grid(row=0, column=4, columnspan=5, sticky=E) stMapper = Timer(0.01, self.formtable) stMapper.start() self.root.mainloop() def Map_Selected(self): self.listselect = str(self.listbox.get(ACTIVE)) self.listselect = self.listselect.split(' \\ ') path1 = self.listselect[1] server1 = self.listselect[0] netpath = server1 + '\\' + path1 target = '\\\\' + netpath wDir = '' shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(path1 + '.lnk') shortcut.Targetpath = target shortcut.WorkingDirectory = wDir shortcut.save() test = os.system('move /Y ' + '"' + path1 + '.lnk' + '" ' + '%userprofile%\\desktop') self.root.destroy() def formtable(self): print("If this window displays 'System error 53' Please disregard " "\nand continue waiting for program to load Shares") self.network = subprocess.Popen('net view', stdout=subprocess.PIPE).communicate() self.device = str(self.network) self.device1 = [] self.device2 = [] self.device = tuple(filter(None, self.device.split('\\n'))) for item in self.device: # Removes new line and other unwanted charicters "\n","\r"," " self.device1.append( item.replace('\n', '').replace('\\r', '').replace(' ', '')) # self.device1.append(item) self.device = self.device1 self.device2.append("localhost") for item in self.device: # Removes unwanted "\\" this is added to the network location later. if item.startswith("\\\\"): self.device2.append(re.sub('\\\\', '', item)) self.device = self.device2 for i in self.device: try: self.netviewshare = subprocess.Popen( 'net view %s' % i, stdout=subprocess.PIPE).communicate() self.shares1.append(self.netviewshare) except 1: pass for i in self.shares1: if 'There are no entries in the list' not in str(i): if 'Print' not in str(i): string = str(i).replace('--', '').replace( 'Disk', '').replace( '\\r\\nThe command completed successfully.', '').replace('\\r\\nUsers', '').replace('Shared resources at ', '\\r\\n') self.shares2.append(string) else: pass try: for i in self.shares2: t = str(i).split('\\r\\n') self.shares3.append(t) except IndexError: pass for i in self.shares3: t = 8 try: for item in range(5): if "', None" not in str(i[t]): if str(i[t]) != '': one = str(i[t]) one = one.split(' ') self.listbox.insert( END, str(i[1]) + " \\ " + str(one[0])) t += 1 except IndexError: pass self.lbl1.config(text=u'Done! Make Selection Then Click \u2192', font='Times 10')
class Combobox_Autocomplete(Entry, object): def __init__(self, master, list_of_items=None, autocomplete_function=None, listbox_width=None, listbox_height=7, ignorecase_match=False, startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs): if hasattr(self, "autocomplete_function"): if autocomplete_function is not None: raise ValueError( "Combobox_Autocomplete subclass has 'autocomplete_function' implemented" ) else: if autocomplete_function is not None: self.autocomplete_function = autocomplete_function else: if list_of_items is None: raise ValueError( "If not guiven complete function, list_of_items can't be 'None'" ) if ignorecase_match: if startswith_match: def matches_function(entry_data, item): return item.startswith(entry_data) else: def matches_function(entry_data, item): return item in entry_data self.autocomplete_function = lambda entry_data: ( item for item in self.list_of_items if matches_function(entry_data, item)) else: if startswith_match: def matches_function(escaped_entry_data, item): if re.match(escaped_entry_data, item, re.IGNORECASE): return True else: return False else: def matches_function(escaped_entry_data, item): if re.search(escaped_entry_data, item, re.IGNORECASE): return True else: return False def autocomplete_function(entry_data): escaped_entry_data = re.escape(entry_data) return [ item for item in self.list_of_items if matches_function(escaped_entry_data, item) ] self.autocomplete_function = autocomplete_function self._listbox_height = int(listbox_height) self._listbox_width = listbox_width self.list_of_items = list_of_items self._use_vscrollbar = vscrollbar self._use_hscrollbar = hscrollbar kwargs.setdefault("background", "white") if "textvariable" in kwargs: self._entry_var = kwargs["textvariable"] else: self._entry_var = kwargs["textvariable"] = StringVar() Entry.__init__(self, master, **kwargs) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) self._listbox = None # self.bind("<Tab>", self._on_tab) self.bind("<Up>", self._previous) self.bind("<Down>", self._next) self.bind('<Control-n>', self._next) self.bind('<Control-p>', self._previous) self.bind("<Return>", self._update_entry_from_listbox) self.bind("<Escape>", lambda event: self.unpost_listbox()) def _on_tab(self, event): self.post_listbox() return "break" def _on_change_entry_var(self, name, index, mode): entry_data = self._entry_var.get() if entry_data == '': self.unpost_listbox() self.focus() else: values = self.autocomplete_function(entry_data) if values: if self._listbox is None: self._build_listbox(values) else: self._listbox.delete(0, END) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) else: self.unpost_listbox() self.focus() def _build_listbox(self, values): listbox_frame = Frame() self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False) self._listbox.grid(row=0, column=0, sticky=N + E + W + S) self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox) self._listbox.bind("<Return>", self._update_entry_from_listbox) self._listbox.bind("<Escape>", lambda event: self.unpost_listbox()) self._listbox.bind('<Control-n>', self._next) self._listbox.bind('<Control-p>', self._previous) if self._use_vscrollbar: vbar = Scrollbar(listbox_frame, orient=VERTICAL, command=self._listbox.yview) vbar.grid(row=0, column=1, sticky=N + S) self._listbox.configure( yscrollcommand=lambda f, l: autoscroll(vbar, f, l)) if self._use_hscrollbar: hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command=self._listbox.xview) hbar.grid(row=1, column=0, sticky=E + W) self._listbox.configure( xscrollcommand=lambda f, l: autoscroll(hbar, f, l)) listbox_frame.grid_columnconfigure(0, weight=1) listbox_frame.grid_rowconfigure(0, weight=1) x = -self.cget("borderwidth") - self.cget("highlightthickness") y = self.winfo_height() - self.cget("borderwidth") - self.cget( "highlightthickness") if self._listbox_width: width = self._listbox_width else: width = self.winfo_width() listbox_frame.place(in_=self, x=x, y=y, width=width) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) def post_listbox(self): if self._listbox is not None: return entry_data = self._entry_var.get() if entry_data == '': return values = self.autocomplete_function(entry_data) if values: self._build_listbox(values) def unpost_listbox(self): if self._listbox is not None: self._listbox.master.destroy() self._listbox = None def get_value(self): return self._entry_var.get() def set_value(self, text, close_dialog=False): self._set_var(text) if close_dialog: self.unpost_listbox() self.icursor(END) self.xview_moveto(1.0) def _set_var(self, text): self._entry_var.trace_vdelete("w", self._trace_id) self._entry_var.set(text) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) def _update_entry_from_listbox(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if current_selection: text = self._listbox.get(current_selection) self._set_var(text) self._listbox.master.destroy() self._listbox = None self.focus() self.icursor(END) self.xview_moveto(1.0) return "break" def _previous(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection) == 0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == 0: index = END else: index -= 1 self._listbox.see(index) self._listbox.selection_set(first=index) self._listbox.activate(index) return "break" def _next(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection) == 0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == self._listbox.size() - 1: index = 0 else: index += 1 self._listbox.see(index) self._listbox.selection_set(index) self._listbox.activate(index) return "break"
def display_search_result(row): listbox = Listbox(frame, width=20, height=1) listbox.grid(row=9, columnspan=4, sticky=W + E) listbox.insert(END, row)
class GUI(Frame): def __init__(self, resources, master=None): Frame.__init__(self, master) self.resources = resources # Tkinter objects self.model_initial_names = None self.model_final_names = None self.widget_initial_names = None self.widget_final_names = None self.canvas_view = None self.model_height = None self.model_width = None self.vcmd = None self.selected_format = None self.validate = None # Initialize tkinter self.grid() self.create_objects() self.last_directory = "" # Lists for image name handling self.image_files = list() self.image_names = list() self.new_image_names = list() self.directory = "" # Thumbnails self.last_view = "" # Rules self.rule = None self.user_rule = "" def create_objects(self): top = self.winfo_toplevel() # Menu menu_top = Menu(top) top["menu"] = menu_top menu_top.add_command(label="About...") # Image line form_general = Frame(self, padx=10, pady=10) form_general.grid(row=0, column=0) # Original names form_initial_data = LabelFrame(form_general, text="Images", padx=10, pady=5) form_initial_data.grid(column=0, row=0, rowspan=2, sticky=N + S) initial_scroll_y = Scrollbar(form_initial_data, orient=VERTICAL) initial_scroll_y.grid(column=2, row=0, rowspan=5, sticky=N + S) self.model_initial_names = StringVar(self) self.widget_initial_names = Listbox( form_initial_data, height=27, width=35, activestyle="dotbox", listvariable=self.model_initial_names, selectmode=EXTENDED, yscrollcommand=initial_scroll_y.set) self.widget_initial_names.grid(column=0, row=0, rowspan=5, columnspan=2, sticky=N + S + W + E) initial_scroll_y["command"] = self.widget_initial_names.yview self.widget_initial_names.bind("<Double-Button-1>", self.select_name) self.widget_initial_names.bind("<<ListboxSelect>>", self.preview) button_up = Button(form_initial_data, image=self.resources["up"], command=self.name_up) button_up.grid(column=3, row=1, sticky=N + S) button_down = Button(form_initial_data, image=self.resources["down"], command=self.name_down) button_down.grid(column=3, row=3, sticky=N + S) button_add = Button(form_initial_data, image=self.resources["add"], command=self.add_file_names) button_add.grid(column=0, row=5, sticky=W + E) button_delete = Button(form_initial_data, image=self.resources["delete"], command=self.remove_file_names) button_delete.grid(column=1, row=5, sticky=W + E) # Preview form_preview = LabelFrame(form_general, text="Preview", padx=10, pady=5) form_preview.grid(column=1, row=0, columnspan=2, sticky=N + S + W + E, padx=10) form_preliminary = Frame(form_preview) form_preliminary.grid(column=1, row=0, sticky=N + S + W + E) self.canvas_view = Canvas(form_preliminary, width=256, height=256, bg="white", cursor="crosshair") self.canvas_view.grid(sticky=N + S + W + E) # Final names form_final_names = Frame(form_preview) form_final_names.grid(column=2, row=0, sticky=N + S + W + E) final_scroll_y = Scrollbar(form_final_names) final_scroll_y.grid(column=1, row=0, sticky=N + S) self.model_final_names = StringVar() self.widget_final_names = Listbox(form_final_names, height=18, width=35, activestyle="dotbox", listvariable=self.model_final_names, selectmode=SINGLE, yscrollcommand=final_scroll_y.set) self.widget_final_names.grid(column=0, row=0, sticky=N + W + E) final_scroll_y["command"] = self.widget_final_names.yview self.widget_final_names.bind("<Double-Button-1>", self.select_name) self.widget_final_names.bind("<<ListboxSelect>>", self.preview) # Options line form_options = Frame(form_general) form_options.grid(row=1, column=1, columnspan=2, sticky=E + W, padx=10) # ..dimensions self.model_width = StringVar() self.model_height = StringVar() form_dimensions = LabelFrame(form_options, text="Dimensions (0 = no change)", padx=10, pady=10) form_dimensions.grid(row=0, column=1, sticky=N + S + W + E, padx=5) self.vcmd = (form_dimensions.register(self.event_on_validate), "%S", "%P") label_width = Label(form_dimensions, text="Width") label_width.grid(column=0, row=1, sticky=W) entry_width = Entry(form_dimensions, validate="key", validatecommand=self.vcmd, textvariable=self.model_width, justify=RIGHT) entry_width.grid(column=1, row=1, sticky=E + W) entry_width.insert(END, "0") label_height = Label(form_dimensions, text="Height") label_height.grid(column=0, row=2, sticky=W) entry_height = Entry(form_dimensions, validate="key", validatecommand=self.vcmd, textvariable=self.model_height, justify=RIGHT) entry_height.grid(column=1, row=2, sticky=E + W) entry_height.insert(END, "0") # .. formats form_formats = LabelFrame(form_options, text="Formats", padx=10, pady=10) form_formats.grid(row=0, column=0, rowspan=2, sticky=N + S + E + W) formats = ["No change", "JPG", "GIF", "BMP", "PNG", "TIFF"] self.selected_format = StringVar(value="No change") for n in range(len(formats)): radio_format = Radiobutton(form_formats, text=formats[n], value=formats[n], variable=self.selected_format) radio_format.grid(row=n + 1, column=0, sticky=W) # .. name change self.validate = (form_dimensions.register(self.event_validate_rule), "%P") form_names = LabelFrame(form_options, text="Names", padx=10, pady=10) form_names.grid(row=1, column=1, sticky=N + S + E + W, padx=5) self.selected_name = IntVar(value=0) radio_nochange = Radiobutton(form_names, text="No change", value=0, variable=self.selected_name, command=self.rule_change) radio_nochange.grid(row=1, column=0, columnspan=2, sticky=W) radio_name_only = Radiobutton(form_names, text="Name + N", value=1, variable=self.selected_name, command=self.rule_change) radio_name_only.grid(row=2, column=0, sticky=W) self.entry_name_only = Entry(form_names, width=10, validate="key", validatecommand=self.validate) self.entry_name_only.grid(row=2, column=1, sticky=W + E) radio_rule = Radiobutton(form_names, text="Rule", value=2, variable=self.selected_name, command=self.rule_change) radio_rule.grid(row=3, column=0, sticky=W) self.button_change = Button(form_names, text="Change", command=self.custom_rule) self.button_change.grid(row=3, column=1, sticky=W + E) self.entry_name_only["state"] = DISABLED self.button_change["state"] = DISABLED # ..directory form_directory = LabelFrame(form_options, text="Destination", padx=10, pady=10) form_directory.grid(row=0, column=2, sticky=N + S + W) button_directory = Button(form_directory, image=self.resources["dir"], command=self.choose_directory) button_directory.grid(row=0, column=0, sticky=N + S + E + W) self.label_selected_directory = Label(form_directory, text="<Directory not chosen>", width=25, anchor=W) self.label_selected_directory.grid(row=0, column=1, stick=W + E) # .. convert self.button_convert = Button(form_options, image=self.resources["convert_d"], state=DISABLED, height=91, command=self.convert_images) self.button_convert.grid(row=1, column=2, sticky=E + W + S) #### EVENTS ############################################ def add_file_names(self): new_names = get_image_file_names(self, self.last_directory) if len(new_names) > 0: names = get_names_in_path(new_names) self.image_files.extend(new_names) self.image_names.extend(names) self.change_names() self.refresh_names() self.last_directory = os.path.split(new_names[0])[0] def remove_file_names(self): indices = self.widget_initial_names.curselection() while len(indices) > 0: ind = indices[0] self.widget_initial_names.delete(ind) self.image_files.pop(int(ind)) self.image_names.pop(int(ind)) indices = self.widget_initial_names.curselection() if self.last_view not in self.image_files: self.canvas_view.delete("Image") self.change_names() self.refresh_names(True) def name_up(self): indices = list(self.widget_initial_names.curselection()) for n in range(len(indices)): indices[n] = int(indices[n]) indices.sort() for n in range(len(indices)): idx = indices[n] if idx != 0 and idx - 1 not in indices: x = self.image_files.pop(idx) self.image_files.insert(idx - 1, x) indices[n] -= 1 self.image_names = get_names_in_path(self.image_files) self.change_names() self.refresh_names() for n in indices: self.widget_initial_names.selection_set(n) def name_down(self): indices = list(self.widget_initial_names.curselection()) for n in range(len(indices)): indices[n] = int(indices[n]) indices.sort() indices = indices[::-1] total = len(self.image_files) for n in range(len(indices)): indices[n] = int(indices[n]) idx = indices[n] if idx != total - 1 and idx + 1 not in indices: x = self.image_files.pop(idx) self.image_files.insert(idx + 1, x) indices[n] += 1 self.image_names = get_names_in_path(self.image_files) self.change_names() self.refresh_names() for n in indices: self.widget_initial_names.selection_set(n) def change_names(self): # Apply name rule self.new_image_names = self.image_names[:] for n in range(len(self.new_image_names)): self.new_image_names[n] = os.path.splitext( self.new_image_names[n])[0] if self.rule is not None: self.new_image_names = change_names_with_rule( self.new_image_names, self.rule)[0] return True def select_name(self, e): indices = e.widget.curselection() if len(indices) > 0: ind = int(indices[-1]) if e.widget == self.widget_initial_names: self.widget_final_names.selection_clear(0, END) self.widget_final_names.selection_set(ind) self.widget_final_names.see(ind) else: self.widget_initial_names.selection_clear(0, END) self.widget_initial_names.selection_set(ind) self.widget_initial_names.see(ind) def refresh_names(self, only_last=False): if not only_last: self.model_initial_names.set('') for n in self.image_names: self.widget_initial_names.insert(END, n) self.model_final_names.set('') for n in self.new_image_names: self.widget_final_names.insert(END, n) def preview(self, e): indices = e.widget.curselection() if len(indices) > 0: idx = int(indices[-1]) if self.last_view == self.image_files[idx]: return else: self.last_view = self.image_files[idx] try: current_image = Image.open(self.image_files[idx]) current_image.thumbnail((256, 256)) self.photo = ImageTk.PhotoImage(current_image) self.canvas_view.delete("Image") self.canvas_view.create_image(128, 128, image=self.photo) self.canvas_view.addtag_all("Image") except: showerror( "Error in preview", "It was not possible to preview image: " + self.image_files[idx]) def rule_change(self): n = self.selected_name.get() if n == 0: self.entry_name_only["state"] = DISABLED self.button_change["state"] = DISABLED self.rule = None elif n == 1: self.entry_name_only["state"] = NORMAL self.button_change["state"] = DISABLED self.rule = make_naming_rule(self.entry_name_only.get()) elif n == 2: self.entry_name_only["state"] = DISABLED self.button_change["state"] = NORMAL self.custom_rule() self.change_names() self.refresh_names(True) def custom_rule(self): input_rule = AskRule(self, self.user_rule) if input_rule.result is not None: self.user_rule = input_rule.result rule = compile_rule(self.user_rule) if rule is None: showerror("Error - Rule", "Compilation error") else: self.rule = rule self.change_names() self.refresh_names(True) def event_validate_rule(self, text): self.rule = make_naming_rule(text) self.change_names() self.refresh_names(True) return True def choose_directory(self): directory = get_save_directory() if directory != "": self.directory = directory if len(directory) > 25: directory = directory[0:5] + "..." + directory[-16:] self.label_selected_directory["text"] = directory if self.directory != "": self.button_convert["state"] = NORMAL self.button_convert["image"] = self.resources["convert"] else: self.button_convert["state"] = DISABLED self.button_convert["image"] = self.resources["convert_d"] def convert_images(self): if len(self.image_files) == 0: showinfo("No images", "No images were selected.") return selected_format = self.selected_format.get() width = self.model_width.get() if width == "": width = 0 else: width = int(width) height = self.model_height.get() if height == "": height = 0 else: height = int(height) current_directory = self.directory for n in range(len(self.image_files)): path = self.image_files[n] name = self.new_image_names[n] name = os.path.splitext(name)[0] current_image = Images(path) if not current_image.is_valid(): showerror("Error while converting", "Unable to open image: " + path) else: if not (width == 0 and height == 0): current_image.change_size(width, height) if selected_format != "No change": current_image.change_format(selected_format) current_image.save(current_directory, name) def event_on_validate(self, modification, text): try: if len(text) > 5: return False n = int(modification) return True except ValueError: return False
class App(tkinter.Tk): def __init__(self, parent, app_dir): tkinter.Tk.__init__(self, parent) self.parent = parent # var declaration self.app_dir = app_dir self.filenames = [] # tyoe: list[str] self.file_list = None # type: tkinter.Listbox self.output = os.path.join(app_dir, 'output.pdf') # type: str # init self.initialize() def initialize(self): # set the app size self.geometry("{}x{}".format(WIDTH, HEIGHT)) # create frames left_frame = Frame(self, bg='cyan', width=WIDTH // 2, height=HEIGHT, pady=3) right_frame = Frame(self, bg='lavender', width=WIDTH // 2, height=HEIGHT, pady=3) # layout all main containers with some scale self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=1) self.grid_rowconfigure(0, weight=1) # stick frames to positions (side by side) left_frame.grid(row=0, column=0, sticky='nsew') right_frame.grid(row=0, column=1, sticky='nsew') # create widgets label_pdf = Label(left_frame, text='PDFs') self.file_list = Listbox(left_frame) label_cmds = Label(right_frame, text='Commands') button_import = tkinter.Button(right_frame, text='Import', command=self._get_files) button_up = tkinter.Button(right_frame, text='up', command=self._list_move_up) button_down = tkinter.Button(right_frame, text='Down', command=self._list_move_down) button_remove = tkinter.Button(right_frame, text='remove', command=self._list_remove) button_merge = tkinter.Button(right_frame, text='Merge!', command=self._merge) # layout widgets label_pdf.grid(row=0, column=0) self.file_list.grid(row=1, column=0) label_cmds.grid(row=0, column=1) button_import.grid(row=1, column=1) button_up.grid(row=2, column=1) button_down.grid(row=3, column=1) button_remove.grid(row=4, column=1) button_merge.grid(row=5, column=1) self.update_listbox() def insert_temp_list(self): """ Temp list for debugging """ self.filenames = ['cat.pdf', 'dog.pdf', 'meow.pdf'] self.update_listbox() def _get_files(self): """ Prompt the user for the files that they wish to merge. All files are added to a list """ # a list of filetype tuples (filename, extension) filetypes = [("pdf files", "*.pdf")] # Read in the selected files filenames = filedialog.askopenfilenames( initialdir=self.app_dir, title="Select pdf's to merge. Ctrl + click for multiple", filetypes=filetypes) # add files for filename in filenames: self.filenames.append(filename) self.update_listbox() def update_listbox(self): """ Redraws the listbox to show self.filenames """ # delete all elements from list self.file_list.delete(0, tkinter.END) # add list items. last name only for filename in self.filenames: self.file_list.insert(tkinter.END, os.path.basename(filename)) def _list_move_up(self): """ Move the selected element up if possible """ index = self.get_selected_index() if (index is not None) and (index != 0): up = index - 1 # swap elements upwards list_swap(self.filenames, index, up) self.update_listbox() # set the cursor position within the list self.select_line(up) def _list_move_down(self): """ Move the selected element down if possible """ index = self.get_selected_index() if (index is not None) and (index != len(self.filenames) - 1): down = index + 1 # swap elements downwards list_swap(self.filenames, index, down) self.update_listbox() # set the cursor position within the list self.select_line(down) def _list_remove(self): """ Remove the selected item * if not selected, nothing happens * if possible the selection cursor does not move * if you are removing the latest element the selection moves back one * if you remove the last element, nothing is selected """ index = self.get_selected_index() # ensure something is selected if index is None: return # remove element self.filenames.pop(index) self.update_listbox() # work out where the cursor should be max_pos = len(self.filenames) if index < max_pos: self.select_line(index) elif max_pos != 0: self.select_line(index - 1) def select_line(self, index): """ select a line within self.file_list if the index makes sense """ if index < len(self.filenames): self.file_list.activate(index) self.file_list.select_set(index) def get_selected_index(self): """ Return the index of the element selected in self.file_list. None if nothing is selected """ selected = self.file_list.curselection() if len(selected) > 0: return selected[0] return None def _merge(self): """ Callback for when files all pdf files are ready to be merged """ # check if any pdfs have been selected if len(self.filenames) == 0: print('No files have been selected. Nothing that can be done') return # prompt the user for the output file name self.set_output_file_name() # Run merge for all the files merge_all(self.filenames, self.output) def set_output_file_name(self): """ Prompts the user to select the output file name """ # a list of filetype tuples (filename, extension) filetypes = [("pdf files", "*.pdf")] # Read in the user desired file location output = filedialog.asksaveasfilename(initialdir=self.app_dir, title="Output merged", filetypes=filetypes) # check if the extension is actually pdf (fix shorthanding) self.output = output if output.endswith('pdf') else (output + '.pdf')
class MyFirstGUI: fileData = RejectingDict() last_statusbar_value = '' def __init__(self, master): self.master = master master.title("Сертификаты из ТТН") master.geometry("300x100") master.grid_columnconfigure(index=0, minsize=350, weight=5) #master.grid_columnconfigure(index = 1, weight = 0) menu = Menu(master, tearoff=0) #need to store submenu to be able to address it from others subs self.submenu2 = Menu(master, tearoff=0) self.submenu3 = Menu(master, tearoff=0) self.submenu4 = Menu(master, tearoff=0) self.menubar = Menu(menu, tearoff=0) menu.add_command(label="Open", command=self.open) menu.add_separator() menu.add_command(label="Exit", command=master.destroy) #cascade index = 0 self.menubar.add_cascade(label="File", menu=menu, state="normal") self.submenu2.add_command(label="Copies", command=self.copies, state="disabled") #cascade index = 1 self.menubar.add_cascade(label="Operations", menu=self.submenu2) self.submenu4.add_command(label="Options", command=self.options) #cascade index = 2 self.menubar.add_cascade(label="Settings", menu=self.submenu4) self.commandAbout = self.submenu3.add_command(label="About", command=self.about) #cascade index = 3 self.menubar.add_cascade(label="Help", menu=self.submenu3) self.lbMain = Listbox( master, selectmode='extended', state="disabled", width=50, #width in characters height=5 #number of lines ) self.scrollbar = Scrollbar(master, orient='vertical') self.lbMain.config(yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.lbMain.yview) self.scrollbar.grid( row=0, column=0, ipady=0, sticky='e' # just to the right side East ) self.lbMain.grid( row=0, column=0, sticky='n, s, e, w' #to all sides ) # status bar status_frame = Frame(master, height=10) self.status = Label(status_frame, text="this is the status bar") self.status.pack(fill="both", expand=True) status_frame.grid(row=1, column=0) self.lbMain.bind('<<ListboxSelect>>', self.on_lbSelect) self.submenu3.bind('<<MenuSelect>>', self.about_status) self.submenu3.bind('<Enter>', self.about_status) self.submenu4.bind('<<MenuSelect>>', self.options_status) self.submenu4.bind('<Enter>', self.options_status) self.submenu3.bind('<Leave>', self.status_leave) self.submenu4.bind('<Leave>', self.status_leave) master.config(menu=self.menubar) def about_status(self, event): self.last_statusbar_value = self.status['text'] self.status['text'] = 'About' print(event.widget) def options_status(self, event): self.last_statusbar_value = self.status['text'] self.status['text'] = 'Options' print(event.widget) def status_leave(self, event): self.status['text'] = self.last_statusbar_value def about(self): messagebox.showinfo( title="About", message="Program reads TTNs from Excel files " + "and prints either quality certificates Consignee-wise or prepares" + " PDFs with complacency certificates on the same basis") def options(self): pass def open(self): print("Opening files") filename = Dialog.askopenfilename( initialdir=os.path.dirname(__file__), title="Файлы с ТТН", #need to leave comma to build 1-x tuple filetypes=(("Excel files", "*.xls"), ), multiple=True) if len(filename) == 0: return for nm in filename: try: ob = TTNReader(nm) self.fileData[ob.TTN_data["TTN_Number"]] = ob #filling in the listbox if self.lbMain.size() == 0: self.lbMain.config(state='normal') self.lbMain.insert('end', str(ob.TTN_data["TTN_Number"])) except: continue def on_lbSelect(self, evt): if len(self.lbMain.curselection()) != 0: self.submenu2.entryconfig('Copies', state="normal") else: self.submenu2.entryconfig('Copies', state="disabled") def copies(self): """ Prepares PDFs with inscriptions """ for ttn in self.lbMain.curselection(): print(self.fileData[int(self.lbMain.get(ttn))].TTN_data["path"])
class ViewPessoa(object): _janelaPrincipal_ = Tk() _nomeLabel_ = None _cargoLabel_ = None _codCargoLabel_ = None _idadeLabel_ = None _salarioLabel_ = None _nomeEntry_ = None _cargoEntry_ = None _codCargoEntry_ = None _idadeEntry_ = None _salarioEntry_ = None _pessoaListBox_ = None _cargoListBox_ = None _inserirButton_ = None _carregarButton_ = None _carregarNomeButton_ = None _insCargoButton_ = None _carCargosButton_ = None _carNomeCargoButton_ = None _mediaSalLabel_ = None _mediaButton_ = None def lerPessoa(self): nome = self._nomeEntry_.get() idade = int(self._idadeEntry_.get()) salario = float(self._salarioEntry_.get()) pessoa = Pessoa(nome, idade, salario) return pessoa def adicionaPessoa(self, pessoa): self._pessoaListBox_.insert(END, pessoa) def lerCargo(self): #nome = self._nomeEntry_.get() #salario = float(self._salarioEntry_.get()) #pessoa = Pessoa(nome,idade,salario) #return null pass def adicionaCargo(self, cargo): #self._pessoaListBox_.insert(END,pessoa) pass def mostraMedia(self, media): self._mediaSalLabel_["text"] = "Media R$: " + str(media) def __init__(self, comandoinserir, comandocarregar, mediasalario): super().__init__() self._nomeLabel_ = Label(master=self._janelaPrincipal_, text="Nome:") self._idadeLabel_ = Label(master=self._janelaPrincipal_, text="Idade:") self._salarioLabel_ = Label(master=self._janelaPrincipal_, text="Salario:") self._mediaSalLabel_ = Label(master=self._janelaPrincipal_, text="Media R$: 0.0") self._cargoLabel_ = Label(master=self._janelaPrincipal_, text="Cargo:") self._codCargoLabel_ = Label(master=self._janelaPrincipal_, text="Cod.Cargo:") self._nomeEntry_ = Entry(master=self._janelaPrincipal_, width=20) self._idadeEntry_ = Entry(master=self._janelaPrincipal_, width=5) self._salarioEntry_ = Entry(master=self._janelaPrincipal_, width=6) self._cargoEntry_ = Entry(master=self._janelaPrincipal_, width=20) self._codCargoEntry_ = Entry(master=self._janelaPrincipal_, width=5) self._pessoaListBox_ = Listbox(master=self._janelaPrincipal_) self._cargoListBox_ = Listbox(master=self._janelaPrincipal_) self._inserirButton_ = Button(master=self._janelaPrincipal_, text="Inserir Pessoa", command=comandoinserir) self._carregarButton_ = Button(master=self._janelaPrincipal_, text="Carregar Pessoas", command=comandocarregar) self._mediaButton_ = Button(master=self._janelaPrincipal_, text="Media Salarios", command=mediasalario) self._nomeLabel_.grid(row=1, column=1) self._nomeEntry_.grid(row=1, column=2) self._salarioLabel_.grid(row=2, column=1) self._salarioEntry_.grid(row=2, column=2) self._idadeLabel_.grid(row=3, column=1) self._idadeEntry_.grid(row=3, column=2) self._cargoLabel_.grid(row=1, column=3) self._cargoEntry_.grid(row=1, column=4) self._codCargoLabel_.grid(row=2, column=3) self._codCargoEntry_.grid(row=2, column=4) self._pessoaListBox_.grid(row=4, rowspan=5, column=2) self._cargoListBox_.grid(row=4, rowspan=5, column=4) self._inserirButton_.grid(row=4, column=1) self._carregarButton_.grid(row=5, column=1) self._mediaButton_.grid(row=6, column=1) self._mediaSalLabel_.grid(row=7, column=1) def executar(self): self._janelaPrincipal_.mainloop()
class UBX_PRESET_Frame(Frame): """ UBX Preset and User-defined configuration command panel. """ def __init__(self, app, container, *args, **kwargs): """ Constructor. :param Frame app: reference to main tkinter application :param Frame container: reference to container frame (config-dialog) :param args: optional args to pass to Frame parent class :param kwargs: optional kwargs to pass to Frame parent class """ self.__app = app # Reference to main application class self.__master = self.__app.get_master() # Reference to root class (Tk) self.__container = container Frame.__init__(self, self.__container.container, *args, **kwargs) self._img_send = ImageTk.PhotoImage(Image.open(ICON_SEND)) self._img_pending = ImageTk.PhotoImage(Image.open(ICON_PENDING)) self._img_confirmed = ImageTk.PhotoImage(Image.open(ICON_CONFIRMED)) self._img_warn = ImageTk.PhotoImage(Image.open(ICON_WARNING)) self._preset_command = None self._body() self._do_layout() self._attach_events() self.reset() def _body(self): """ Set up frame and widgets. """ self._lbl_presets = Label(self, text=LBLPRESET, anchor="w") self._lbx_preset = Listbox( self, border=2, relief="sunken", bg=ENTCOL, height=5, width=30, justify=LEFT, exportselection=False, ) self._scr_presetv = Scrollbar(self, orient=VERTICAL) self._scr_preseth = Scrollbar(self, orient=HORIZONTAL) self._lbx_preset.config(yscrollcommand=self._scr_presetv.set) self._lbx_preset.config(xscrollcommand=self._scr_preseth.set) self._scr_presetv.config(command=self._lbx_preset.yview) self._scr_preseth.config(command=self._lbx_preset.xview) self._lbl_send_command = Label(self) self._btn_send_command = Button( self, image=self._img_send, width=50, command=self._on_send_preset, ) def _do_layout(self): """ Layout widgets. """ self._lbl_presets.grid(column=0, row=0, columnspan=6, padx=3, sticky=(W, E)) self._lbx_preset.grid(column=0, row=1, columnspan=3, rowspan=6, padx=3, pady=3, sticky=(W, E)) self._scr_presetv.grid(column=2, row=1, rowspan=6, sticky=(N, S, E)) self._scr_preseth.grid(column=0, row=7, columnspan=3, sticky=(W, E)) self._btn_send_command.grid(column=3, row=1, rowspan=6, ipadx=3, ipady=3, sticky=(E)) self._lbl_send_command.grid(column=4, row=1, rowspan=6, ipadx=3, ipady=3, sticky=(E)) (cols, rows) = self.grid_size() for i in range(cols): self.grid_columnconfigure(i, weight=1) for i in range(rows): self.grid_rowconfigure(i, weight=1) self.option_add("*Font", self.__app.font_sm) def _attach_events(self): """ Bind listbox selection events. """ self._lbx_preset.bind("<<ListboxSelect>>", self._on_select_preset) def reset(self): """ Reset panel. """ # Load user-defined presets if there are any self._userpresets = self.__app.file_handler.load_user_presets() idx = 0 for pst in PRESET_COMMMANDS: self._lbx_preset.insert(idx, pst) idx += 1 for upst in self._userpresets: self._lbx_preset.insert(idx, "USER " + upst) idx += 1 def _on_select_preset(self, *args, **kwargs): # pylint: disable=unused-argument """ Preset command has been selected. """ idx = self._lbx_preset.curselection() self._preset_command = self._lbx_preset.get(idx) def _on_send_preset(self, *args, **kwargs): # pylint: disable=unused-argument """ Preset command send button has been clicked. """ confirmed = True try: if self._preset_command == PSTRESET: confirmed = self._do_factory_reset() elif self._preset_command == PSTSAVE: confirmed = self._do_save_config() elif self._preset_command == PSTMINNMEAON: self._do_set_minnmea() elif self._preset_command == PSTALLNMEAON: self._do_set_allnmea(1) elif self._preset_command == PSTALLNMEAOFF: self._do_set_allnmea(0) elif self._preset_command == PSTMINUBXON: self._do_set_minNAV() elif self._preset_command == PSTALLUBXON: self._do_set_allNAV(1) elif self._preset_command == PSTALLUBXOFF: self._do_set_allNAV(0) elif self._preset_command == PSTALLINFON: self._do_set_inf(True) elif self._preset_command == PSTALLINFOFF: self._do_set_inf(False) elif self._preset_command == PSTALLLOGON: self._do_set_log(4) elif self._preset_command == PSTALLLOGOFF: self._do_set_log(0) elif self._preset_command == PSTALLMONON: self._do_set_mon(4) elif self._preset_command == PSTALLMONOFF: self._do_set_mon(0) elif self._preset_command == PSTALLRXMON: self._do_set_rxm(4) elif self._preset_command == PSTALLRXMOFF: self._do_set_rxm(0) elif self._preset_command == PSTPOLLPORT: self._do_poll_prt() elif self._preset_command == PSTPOLLINFO: self._do_poll_inf() elif self._preset_command == PSTPOLLALL: self._do_poll_all() else: self._do_user_defined(self._preset_command) if confirmed: self._lbl_send_command.config(image=self._img_pending) self.__container.set_status("Command(s) sent", "blue") self.__container.set_pending(UBX_PRESET, ("ACK-ACK", "ACK-NAK", "MON-VER")) else: self.__container.set_status("Command(s) cancelled", "blue") except Exception as err: # pylint: disable=broad-except self.__container.set_status(f"Error {err}", "red") self._lbl_send_command.config(image=self._img_warn) def _do_poll_all(self): """ Poll INF message configuration. """ for msgtype in UBX_PAYLOADS_POLL: if msgtype[0:3] == "CFG" and msgtype not in ( "CFG-INF", "CFG-MSG", "CFG-PRT-IO", "CFG-TP5-TPX", ): msg = UBXMessage("CFG", msgtype, POLL) self.__app.serial_handler.serial_write(msg.serialize()) def _do_poll_prt(self): """ Poll PRT message configuration for each port. """ for portID in range(5): msg = UBXMessage("CFG", "CFG-PRT", POLL, portID=portID) self.__app.serial_handler.serial_write(msg.serialize()) def _do_poll_inf(self): """ Poll INF message configuration. """ for payload in (b"\x00", b"\x01"): # UBX & NMEA msg = UBXMessage("CFG", "CFG-INF", POLL, payload=payload) self.__app.serial_handler.serial_write(msg.serialize()) def _do_set_inf(self, onoff: int): """ Turn on device information messages INF. :param int onoff: on/off boolean """ if onoff: mask = b"\x1f" # all INF msgs else: mask = b"\x01" # errors only for protocolID in (b"\x00", b"\x01"): # UBX and NMEA reserved1 = b"\x00\x00\x00" infMsgMaskDDC = mask infMsgMaskUART1 = mask infMsgMaskUART2 = mask infMsgMaskUSB = mask infMsgMaskSPI = mask reserved2 = b"\x00" payload = (protocolID + reserved1 + infMsgMaskDDC + infMsgMaskUART1 + infMsgMaskUART2 + infMsgMaskUSB + infMsgMaskSPI + reserved2) msg = UBXMessage("CFG", "CFG-INF", SET, payload=payload) self.__app.serial_handler.serial_write(msg.serialize()) self._do_poll_inf() # poll results def _do_set_log(self, msgrate: int): """ Turn on all device logging messages LOG. :param int msgrate: message rate (i.e. every nth position solution) """ for msgtype in UBX_MSGIDS: if msgtype[0:1] == b"\x21": self._do_cfgmsg(msgtype, msgrate) def _do_set_mon(self, msgrate): """ Turn on all device monitoring messages MON. :param int msgrate: message rate (i.e. every nth position solution) """ for msgtype in UBX_MSGIDS: if msgtype[0:1] == b"\x0A": self._do_cfgmsg(msgtype, msgrate) def _do_set_rxm(self, msgrate): """ Turn on all device receiver management messages RXM. :param int msgrate: message rate (i.e. every nth position solution) """ for msgtype in UBX_MSGIDS: if msgtype[0:1] == b"\x02": self._do_cfgmsg(msgtype, msgrate) def _do_set_minnmea(self): """ Turn on minimum set of NMEA messages (GGA & GSA & GSV). """ for msgtype in UBX_MSGIDS: if msgtype[0:1] == b"\xf0": # standard NMEA if msgtype in (b"\xf0\x00", b"\xf0\x02"): # GGA, GSA self._do_cfgmsg(msgtype, 1) elif msgtype == b"\xf0\x03": # GSV self._do_cfgmsg(msgtype, 4) else: self._do_cfgmsg(msgtype, 0) if msgtype[0:1] == b"\xf1": # proprietary NMEA self._do_cfgmsg(msgtype, 0) def _do_set_minNAV(self): """ Turn on minimum set of UBX-NAV messages (PVT & SVINFO). """ for msgtype in UBX_MSGIDS: if msgtype[0:1] == b"\x01": # UBX-NAV if msgtype == b"\x01\x07": # NAV-PVT self._do_cfgmsg(msgtype, 1) # elif msgtype == b"\x01\x30": # NAV-SVINFO (deprecated) # self._do_cfgmsg(msgtype, 4) elif msgtype == b"\x01\x35": # NAV-SAT self._do_cfgmsg(msgtype, 4) else: self._do_cfgmsg(msgtype, 0) def _do_set_allnmea(self, msgrate): """ Turn on all NMEA messages. :param int msgrate: message rate (i.e. every nth position solution) """ for msgtype in UBX_MSGIDS: if msgtype[0:1] in (b"\xf0", b"\xf1"): self._do_cfgmsg(msgtype, msgrate) def _do_set_allNAV(self, msgrate): """ Turn on all UBX-NAV messages. :param int msgrate: message rate (i.e. every nth position solution) """ for msgtype in UBX_MSGIDS: if msgtype[0:1] == b"\x01": self._do_cfgmsg(msgtype, msgrate) def _do_cfgmsg(self, msgtype: str, msgrate: int): """ Set rate for specified message type via CFG-MSG. NB A rate of n means 'for every nth position solution', so values > 1 mean the message is sent less often. :param str msgtype: type of config message :param int msgrate: message rate (i.e. every nth position solution) """ msgClass = int.from_bytes(msgtype[0:1], "little", signed=False) msgID = int.from_bytes(msgtype[1:2], "little", signed=False) msg = UBXMessage( "CFG", "CFG-MSG", SET, msgClass=msgClass, msgID=msgID, rateDDC=msgrate, rateUART1=msgrate, rateUSB=msgrate, rateSPI=msgrate, ) self.__app.serial_handler.serial_write(msg.serialize()) def _do_factory_reset(self) -> bool: """ Restore to factory defaults stored in battery-backed RAM but display confirmation message box first. :return: boolean signifying whether OK was pressed :rtype: bool """ if messagebox.askokcancel(DLGRESET, DLGRESETCONFIRM): clearMask = b"\x1f\x1f\x00\x00" loadMask = b"\x1f\x1f\x00\x00" deviceMask = b"\x07" # target RAM, Flash and EEPROM msg = UBXMessage( "CFG", "CFG-CFG", SET, clearMask=clearMask, loadMask=loadMask, deviceMask=deviceMask, ) self.__app.serial_handler.serial_write(msg.serialize()) return True return False def _do_save_config(self) -> bool: """ Save current configuration to persistent storage but display confirmation message box first. :return: boolean signifying whether OK was pressed :rtype: bool """ if messagebox.askokcancel(DLGSAVE, DLGSAVECONFIRM): saveMask = b"\x1f\x1f\x00\x00" deviceMask = b"\x07" # target RAM, Flash and EEPROM msg = UBXMessage("CFG", "CFG-CFG", SET, saveMask=saveMask, deviceMask=deviceMask) self.__app.serial_handler.serial_write(msg.serialize()) return True return False def _do_user_defined(self, command: str): """ Parse and send user-defined command(s). This could result in any number of errors if the uxbpresets file contains garbage, so there's a broad catch-all-exceptions in the calling routine. :param str command: user defined message constructor(s) """ try: seg = command.split(",") for i in range(1, len(seg), 4): ubx_class = seg[i].strip() ubx_id = seg[i + 1].strip() payload = seg[i + 2].strip() mode = int(seg[i + 3].rstrip("\r\n")) if payload != "": payload = bytes(bytearray.fromhex(payload)) msg = UBXMessage(ubx_class, ubx_id, mode, payload=payload) else: msg = UBXMessage(ubx_class, ubx_id, mode) self.__app.serial_handler.serial_write(msg.serialize()) except Exception as err: # pylint: disable=broad-except self.__app.set_status(f"Error {err}", "red") self._lbl_send_command.config(image=self._img_warn) def update_status(self, cfgtype, **kwargs): """ Update pending confirmation status. :param str cfgtype: identity of UBX message containing config info :param kwargs: status keywords and values from UBX config message """ if cfgtype in ("ACK-ACK", "MON-VER"): self._lbl_send_command.config(image=self._img_confirmed) self.__container.set_status(f"{cfgtype} GET message received", "green") elif cfgtype == "ACK-NAK": self._lbl_send_command.config(image=self._img_warn) self.__container.set_status("PRESET command rejected", "red")
class Tela_cliente_login(Tela): '''Classe que modela a interface grafica da tela de login do cliente''' def __init__(self): super().__init__() self.janela.wm_title("cliente - DELIBRARY") self.txt_login = StringVar() self.txt_senha = StringVar() self.txt_id_livro = StringVar() self.txt_nome_livro = StringVar() self.txt_genero_livro = StringVar() self.txt_autor_livro = StringVar() self.txt_area_livro = StringVar() self.txt_editora_livro = StringVar() self.txt_edicao_livro = StringVar() self.ent_login = Entry(self.janela, textvariable=self.txt_login) self.ent_senha = Entry(self.janela, textvariable=self.txt_senha, show="*") self.btn_voltar_tela = Button(self.janela, width=15, text="Voltar") self.btn_login = Button(self.janela, width=15, text="Entrar") self.btn_cadastro = Button(self.janela, width=15, text="Cadastrar") self.lb_janela_cliente_login = Label(self.janela, text="LOGIN: "******"SENHA: ") self.lb_pesquisar_livro = Label(self.janela, text="Pesquisar livro") self.lbl_id_livro = Label(self.janela, text="ID") self.lbl_nome_livro = Label(self.janela, text="Nome") self.lbl_genero_livro = Label(self.janela, text="Genero") self.lbl_autor_livro = Label(self.janela, text="Autor") self.lbl_area_livro = Label(self.janela, text="Area") self.lbl_editora_livro = Label(self.janela, text="Editora") self.lbl_edicao_livro = Label(self.janela, text="Edicao") self.ent_id_livro = Entry(self.janela, textvariable=self.txt_id_livro) self.ent_nome_livro = Entry(self.janela, textvariable=self.txt_nome_livro) self.ent_genero_livro = Entry(self.janela, textvariable=self.txt_genero_livro) self.ent_autor_livro = Entry(self.janela, textvariable=self.txt_autor_livro) self.ent_area_livro = Entry(self.janela, textvariable=self.txt_area_livro) self.ent_editora_livro = Entry(self.janela, textvariable=self.txt_editora_livro) self.ent_edicao_livro = Entry(self.janela, textvariable=self.txt_edicao_livro) self.btn_pesquisar = Button(self.janela, width=15, text="Pesquisar") self.list = Listbox(self.janela, width=85) self.scroll = Scrollbar(self.janela) def config_layout(self): '''Metodo para configurar os widgets da janela''' self.lb_janela_cliente_login.grid(row=0, column=0) self.lb_janela_cliente_senha.grid(row=1, column=0) self.ent_login.grid(row=0, column=1) self.ent_senha.grid(row=1, column=1) self.btn_login.grid(row=2, column=1) self.btn_cadastro.grid(row=2, column=0) self.btn_voltar_tela.grid(row=3, column=1) self.lb_pesquisar_livro.grid(row=4, column=0) self.list.grid(row=5, column=2, rowspan=10) self.scroll.grid(row=5, column=3, rowspan=10) self.list.configure(yscrollcommand=self.scroll.set) self.scroll.configure(command=self.list.yview) self.lbl_id_livro.grid(row=5, column=0) self.lbl_nome_livro.grid(row=6, column=0) self.lbl_genero_livro.grid(row=7, column=0) self.lbl_autor_livro.grid(row=8, column=0) self.lbl_area_livro.grid(row=9, column=0) self.lbl_editora_livro.grid(row=10, column=0) self.lbl_edicao_livro.grid(row=11, column=0) self.ent_id_livro.grid(row=5, column=1) self.ent_nome_livro.grid(row=6, column=1) self.ent_genero_livro.grid(row=7, column=1) self.ent_autor_livro.grid(row=8, column=1) self.ent_area_livro.grid(row=9, column=1) self.ent_editora_livro.grid(row=10, column=1) self.ent_edicao_livro.grid(row=11, column=1) self.btn_pesquisar.grid(row=12, column=0) def iniciar(self): '''Metodo para desenhar a janela e processar eventos''' self.config_layout() return super().iniciar()
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("") # self.style = Style() # self.style.theme_use("clam") # self.pack(fill=BOTH, expand = 1) self.quitbutton = Button(self, text="Quit", command=lambda: self.quit()) self.quitbutton.grid(row=3, column=1, pady=4) self.labelErrorPointer = Label(self, text="◀") self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] self.optionCreate = "Create" self.optionUpcoming = "Upcoming" self.optionPast = "Past" self.prevmode = self.optionCreate self.curmode = self.optionCreate self.optionvar = tkinter.StringVar(self) self.optionvar.trace("w", self.permaloop) self.optionvar.set(self.optionCreate) self.option = OptionMenu(self, self.optionvar, self.optionCreate, self.optionUpcoming, self.optionPast) self.optionpostmodevar = tkinter.StringVar(self) self.optionpostmodevar.trace("w", self.permaloop) self.optionpostmodevar.set("url") self.optionpostmode = OptionMenu(self, self.optionpostmodevar, "url", "text") self.labelText = Label(self, text="Selftext:") self.entryText = Text(self) self.labelURL = Label(self, text="URL:") self.entryURL = Entry(self) self.entryURL.configure(width=60) self.sql = sqlite3.connect("sql.db") print("Loaded SQL Database") self.cur = self.sql.cursor() self.cur.execute( "CREATE TABLE IF NOT EXISTS upcoming(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT)" ) self.cur.execute( "CREATE TABLE IF NOT EXISTS past(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT, POSTLINK TEXT)" ) self.cur.execute("CREATE TABLE IF NOT EXISTS internal(NAME TEXT, ID INT)") print("Loaded Completed table") self.cur.execute("SELECT * FROM internal") f = self.cur.fetchone() if not f: print("Database is new. Adding ID counter") self.cur.execute("INSERT INTO internal VALUES(?, ?)", ["counter", 1]) self.idcounter = 1 else: self.idcounter = f[1] print("Current ID counter: " + str(self.idcounter)) self.sql.commit() sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() w = 853 h = 480 x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry("%dx%d+%d+%d" % (w, h, x, y - 50)) self.login() def login(self): try: self.quitbutton.grid_forget() self.quitbutton.grid(row=9000, column=0, columnspan=20) self.option.grid(row=1, column=0, columnspan=8, pady=8) self.updategui(fullclean=True) except praw.errors.InvalidUserPass: pass print("Invalid username or password") self.entryPassword.delete(0, 200) self.labelErrorPointer.grid(row=1, column=2) def permaloop(self, *args): self.curmode = self.optionvar.get() print("Was: " + self.prevmode + " | Now: " + self.curmode) if self.curmode != self.prevmode: self.prevmode = self.curmode self.updategui(fullclean=True) else: self.updategui(False) def getTime(self, bool): timeNow = datetime.datetime.now(datetime.timezone.utc) timeUnix = timeNow.timestamp() if bool == False: return timeNow else: return timeUnix def addentrytobase(self, subreddit, title, url="", body="", mode="", ptime=""): curtime = round(self.getTime(True)) try: t = ( self.entryMo.get() + " " + self.entryDa.get() + " " + self.entryYr.get() + " " + self.entryHH.get() + ":" + self.entryMM.get() ) plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M") plandate = plandate.timestamp() except ValueError: print("Invalid Day") return False if mode == "url": url = self.entryURL.get() body = "" if "http://" not in url and "https://" not in url: print("Please enter a proper URL") return False if mode == "text": body = self.entryText.get("1.0", "end") url = "" if plandate < curtime: print("Please enter a time in the future") return False if not all(char in string.ascii_letters + string.digits + "_-" for char in subreddit): print("Subreddit contains invalid characters") return False if len(subreddit) == 0: print("You must enter a subreddit") return False if len(title) == 0: print("You must enter a title") return False if len(title) > 300: print("Title is too long. " + str(len(title)) + "/300 char max") return False if len(body) > 15000: print("Body is too long. " + str(len(body)) + "/15,000 char max") print("Timestamp:", plandate) self.cur.execute( "INSERT INTO upcoming VALUES(?, ?, ?, ?, ?, ?)", [self.idcounter, subreddit, int(plandate), title, url, body], ) self.idcounter += 1 self.cur.execute("UPDATE internal SET ID=? WHERE NAME=?", [self.idcounter, "counter"]) self.sql.commit() print("Post Saved!") self.entryText.delete("1.0", "end") self.entryURL.delete(0, "end") self.entryTitle.delete(0, "end") # self.updategui(halfclean=True) def dropentryfrombase(self, ID): try: ID = int(ID) except ValueError: print("You must enter a number") return print("Dropping Item " + str(ID) + " from Upcoming") self.cur.execute("DELETE FROM upcoming WHERE ID=?", [ID]) self.sql.commit() self.updategui(fullclean=True) def printbasetofile(self, db): filea = open(db + ".txt", "w") if db == "past": self.cur.execute("SELECT * FROM past") if db == "upcoming": self.cur.execute("SELECT * FROM upcoming") f = self.cur.fetchall() print("Printed " + db + " unimpeded to file") for item in f: i = list(item) d = datetime.datetime.fromtimestamp(i[2]) i[2] = datetime.datetime.strftime(d, "%b %d %H:%M") i.remove("") print(str(i)[1:-1], file=filea) filea.close() def updategui(self, halfclean=False, fullclean=False): if self.curmode == self.optionCreate: try: print(self.optionpostmodevar.get()) if self.optionpostmodevar.get() == "url": self.entryText.delete("1.0", "end") self.labelText.grid_forget() self.entryText.grid_forget() self.labelURL.grid(row=8, column=0, columnspan=30) self.entryURL.grid(row=9, column=0, columnspan=12, pady=10) if self.optionpostmodevar.get() == "text": self.entryURL.delete(0, "end") self.labelURL.grid_forget() self.entryURL.grid_forget() self.labelText.grid(row=8, column=0, columnspan=30) self.entryText.configure(width=40, height=8) self.entryText.grid(row=9, column=0, columnspan=12) except AttributeError: pass if fullclean == True: print("Cleaning GUI") for item in self.labellist: item.grid_forget() for item in self.entrylist: item.grid_forget() for item in self.verifylist: item.grid_forget() for item in self.misclist: item.grid_forget() self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] if self.curmode == self.optionCreate: self.newrowindex = 6 self.labelSubreddit = Label(self, text="Subreddit: /r/") self.labelTitle = Label(self, text="Post title: ") self.entrySubreddit = Entry(self) self.entryTitle = Entry(self) self.labelHH = Label(self, text="Schedule time (Local timezone):") nowlist = datetime.datetime.strftime(datetime.datetime.now(), "%B %d %Y %H %M").split() self.entryMo = Spinbox( self, width=9, values=( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ), ) self.entryMo.delete(0, "end") self.entryMo.insert(0, nowlist[0]) self.entryDa = Spinbox(self, width=2, from_=1, to=31) self.entryDa.delete(0, "end") self.entryDa.insert(0, nowlist[1]) self.entryYr = Spinbox(self, width=4, from_=2014, to=2500) self.entryYr.delete(0, "end") self.entryYr.insert(0, nowlist[2]) self.entryHH = Spinbox(self, from_=0, to=23, width=2) self.entryHH.delete(0, "end") self.entryHH.insert(0, nowlist[3]) self.entryMM = Spinbox(self, from_=0, to=59, width=2) self.entryMM.delete(0, "end") self.entryMM.insert(0, nowlist[4]) self.buttonAddentry = Button( self, text="Save", command=lambda: self.addentrytobase( self.entrySubreddit.get(), self.entryTitle.get(), mode=self.optionpostmodevar.get() ), ) self.misclist.append(self.labelSubreddit) self.misclist.append(self.entrySubreddit) self.misclist.append(self.labelHH) self.misclist.append(self.entryHH) self.misclist.append(self.entryMM) self.misclist.append(self.entryMo) self.misclist.append(self.entryDa) self.misclist.append(self.entryYr) self.misclist.append(self.labelTitle) self.misclist.append(self.entryTitle) self.misclist.append(self.buttonAddentry) self.misclist.append(self.optionpostmode) self.misclist.append(self.labelText) self.misclist.append(self.entryText) self.misclist.append(self.labelURL) self.misclist.append(self.entryURL) self.labelSubreddit.grid(row=2, column=0, sticky="e") self.labelTitle.grid(row=3, column=0, sticky="e") self.entrySubreddit.grid(row=2, column=1, columnspan=3, sticky="w") self.entryTitle.grid(row=3, column=1, columnspan=3, sticky="w") self.entryMo.grid(row=4, column=1, sticky="e") self.entryDa.grid(row=4, column=2) self.entryYr.grid(row=4, column=3) self.labelHH.grid(row=4, column=0, sticky="se", pady=5) self.entryHH.grid(row=5, column=1, sticky="e") self.entryMM.grid(row=5, column=2, sticky="w") self.optionpostmode.grid(row=6, column=0, columnspan=20, pady=10) self.buttonAddentry.grid(row=200, column=0, columnspan=20) if self.curmode == self.optionUpcoming: self.cur.execute("SELECT * FROM upcoming") dobutton = True if self.curmode == self.optionPast: self.cur.execute("SELECT * FROM past") dobutton = False if self.curmode == self.optionPast or self.curmode == self.optionUpcoming: self.listboxId = Listbox(self) self.listboxId.configure(width=118, height=20, font=("Courier 8")) self.misclist.append(self.listboxId) self.listboxScroller = Scrollbar(self, orient="horizontal", command=self.listboxId.xview) self.listboxScroller.grid(row=4, column=0, columnspan=900) self.listboxId.grid(row=3, column=0, columnspan=10) self.listboxId.configure(xscrollcommand=self.listboxScroller.set) self.misclist.append(self.listboxScroller) self.buttonPrinter = Button(self, text="Print to .txt file") if self.curmode == self.optionPast: self.buttonPrinter.configure(command=lambda: self.printbasetofile("past")) if self.curmode == self.optionUpcoming: self.buttonPrinter.configure(command=lambda: self.printbasetofile("upcoming")) self.buttonPrinter.grid(row=6, column=0, columnspan=90) self.misclist.append(self.buttonPrinter) if dobutton == True: self.entryDelete = Entry(self) self.buttonDelete = Button( self, text="Delete Item: ", command=lambda: self.dropentryfrombase(self.entryDelete.get()) ) self.buttonDelete.grid(row=5, column=0, sticky="e") self.entryDelete.grid(row=5, column=1, sticky="w") self.misclist.append(self.entryDelete) self.misclist.append(self.buttonDelete) fetched = self.cur.fetchall() for item in fetched: d = datetime.datetime.fromtimestamp(item[2]) info = datetime.datetime.strftime(d, "%b %d %H:%M") if item[4] == "": infx = item[5] if item[5] == "": infx = item[4] if self.curmode == self.optionPast: infy = "." + item[6] else: infy = "" self.listboxId.insert( "end", item[0] + "." * (6 - len(item[0])) + item[1][:10] + "." * (12 - len(item[1][:10])) + info + "." * (15 - len(info[:14])) + item[3][:18] + "." * (20 - len(item[3][:14])) + infx[:45] + "." * (47 - len(infx[:45])) + infy, ) def morerows(self, label, columnm, columnn, limit, *args): self.redditlabel = Label(self, text=label) self.redditlabel.grid(row=self.newrowindex, column=columnm, sticky="e") self.labellist.append(self.redditlabel) self.redditentry = Entry(self) self.redditentry.grid(row=self.newrowindex, column=columnn, columnspan=9) self.entrylist.append(self.redditentry) self.newrowindex += 1 if self.newrowindex >= limit: self.morerowbutton.grid_forget() print(self.newrowindex)
def openCalculator(handler): global conversionresulttext, fromCurrencyInput, toCurrencyInput, amountInput, calculatorWindow currencyapi = get("https://api.exchangeratesapi.io/latest", data=None) if currencyapi.status_code == 200: #Check for reponse exchangerates = loads(currencyapi.content.decode()) exchangerates["rates"]["DUCO"] = float(ducofiat) calculatorWindow = Toplevel() #calculatorWindow.geometry("420x420") calculatorWindow.resizable(False, False) calculatorWindow.title("Duino-Coin Wallet - Calculator") calculatorWindow.configure(background = backgroundColor) calculatorWindow.transient([root]) textFont2 = Font(calculatorWindow, size=12,weight="bold") textFont3 = Font(calculatorWindow, size=14,weight="bold") textFont = Font(calculatorWindow, size=12,weight="normal") Label(calculatorWindow, text="CURRENCY CONVERTER", background = backgroundColor, foreground = foregroundColor, font = textFont3).grid(row=0, column=0) Label(calculatorWindow, text="FROM", background = backgroundColor, foreground = foregroundColor, font = textFont2).grid(row=1, column=0) fromCurrencyInput = Listbox(calculatorWindow, exportselection=False, background = backgroundColor, foreground = foregroundColor, selectbackground = "#7bed9f", border="0", font=textFont, width="20", height="13") fromCurrencyInput.grid(row=2, column=0) i=0 for currency in exchangerates["rates"]: fromCurrencyInput.insert(i, currency) i = i+1 Label(calculatorWindow, text="TO", background = backgroundColor, foreground = foregroundColor, font = textFont2).grid(row=1, column=1) toCurrencyInput = Listbox(calculatorWindow, exportselection=False, foreground = foregroundColor, background = backgroundColor, selectbackground = "#7bed9f", border="0", font=textFont, width="20", height="13") toCurrencyInput.grid(row=2, column=1) i=0 for currency in exchangerates["rates"]: toCurrencyInput.insert(i, currency) i = i+1 toCurrencyInput.select_set(0) toCurrencyInput.event_generate("<<ListboxSelect>>") fromCurrencyInput.select_set(32) fromCurrencyInput.event_generate("<<ListboxSelect>>") Label(calculatorWindow, text="AMOUNT", background = backgroundColor, foreground = foregroundColor, font = textFont2).grid(row=3, column=0) def clear_ccamount_placeholder(self): amountInput.delete("0", "100") amountInput = Entry(calculatorWindow, background = "#7bed9f", foreground=foregroundColor, border="0", font=textFont, width="20") amountInput.grid(row=4, column=0) amountInput.insert("0", str(getBalance())) amountInput.bind("<FocusIn>", clear_ccamount_placeholder) Button(calculatorWindow, text="Convert", background = "#FEEEDA", foreground=foregroundColor, command=currencyConvert, width="22").grid(row=3, column=1, pady=(5, 0)) conversionresulttext = StringVar(calculatorWindow) conversionresulttext.set("RESULT: 0.0") conversionresultLabel = Label(calculatorWindow, textvariable=conversionresulttext, background = backgroundColor, foreground = foregroundColor, font = textFont2) conversionresultLabel.grid(row=4, column=1) Label(calculatorWindow, text=" ", background = backgroundColor, foreground = foregroundColor, font = textFont2).grid(row=5, column=0) calculatorWindow.mainloop()
class CommandCacher( Frame ): def __init__( self, parent ): Frame.__init__( self, parent ) self.parent = parent self.parent.title('Milk Command Cacher') self.PWD=getcwd() self.opt_exec_with_term = IntVar() #first try if we have config directory self.config_dir=environ['HOME']+'/.config/MilkCommandCacher' if( access( self.config_dir, F_OK ) ): chdir( self.config_dir ) else: makedirs( self.config_dir ) #check config files if( access( 'config.ini', F_OK) ): config_file=open('config.ini', 'r') geometry_set = config_file.readline().strip() self.parent.geometry( geometry_set ) self.opt_exec_with_term.set( int( config_file.readline().strip() ) ) else: self.parent.geometry('600x410+200+100') self.opt_exec_with_term.set( 0 ) self.initUI() #check script directory & update the list self.script_dir = self.config_dir + '/scripts' if( access( self.script_dir, F_OK ) ): self.updateList() else: makedirs( self.script_dir ) #redirect close command to self defined command parent.protocol('WM_DELETE_WINDOW', self.quit ) #one should call this on each modification of files def updateList( self ): file_list = listdir( self.config_dir + '/scripts' ) self.script_list.delete( 0, END ) for file_name in sorted(file_list): self.script_list.insert( END, file_name ) #execute the script files def execute( self ): index = self.script_list.curselection() if index: chdir( self.PWD ) exec_file = self.script_list.get( index[0] ) if self.opt_exec_with_term.get() == 0: #normal execution Popen( [self.script_dir+'/'+exec_file] ) else: #execute the script files using term Popen( [TERM, '-e', self.script_dir+'/'+exec_file] ) self.quit() else: messagebox.showwarning( title='Warning', message='No script file selected.') #edit the file by using term & editor variables def editFile( self ): index = self.script_list.curselection() if index: exec_file = self.script_list.get( index[0] ) chdir( self.script_dir ) proc = Popen([TERM, '-e', EDITOR, exec_file]) proc.wait() else: messagebox.showwarning( title='Warning', message='No script file selected.') #create a new session file, and first append SHELL info def createFile( self, file_name ): chdir( self.script_dir ) if access( file_name, F_OK ): messagebox.showwarning( title='Warning', message='Session name already exist!') else: FILE=open(file_name, 'w') FILE.write('#!'+SHELL+'\n') FILE.close() proc = Popen([TERM, '-e', EDITOR, file_name]) proc.wait() chmod( file_name, int( '755', base=8 ) ) self.updateList() def copyCheck( self ): index = self.script_list.curselection() if index: src_file = self.script_list.get( index[0] ) self.popWidget( self.copyFile ) else: messagebox.showwarning( title='Warning', message='You should select a source file') def copyFile( self, file_name ): src_file = self.script_list.get( self.script_list.curselection()[0] ) chdir( self.script_dir ) if access( file_name, F_OK ): messagebox.showwarning( title='Warning', message='Session name already exist!') else: copyfile( src_file, file_name ) chmod( file_name, int( '755', base=8 ) ) self.updateList() #used to pop Customized entry widget def popWidget( self, function ): _geo = self.parent.geometry() _x = str( int( _geo.split('+')[1] ) + 200 ) _y = str( int( _geo.split('+')[2] ) + 200 ) return_val = list() entry_root = Toplevel() entry_root.geometry('+' + _x + '+' + _y ) entry_widget = EntryWidget( entry_root, function ) #Author & version info def about( self ): messagebox.showinfo(title='About', message='Command cacher '+VERSION+'\n Author: Milk Wu') #brief introduction about usage def usageHelp( self ): messagebox.showinfo(title='Usage', message='Select an item in the list and pick the action by buttons.' +' Scripts are put in ${HOME}/.config/MilkCommandCacher/scripts') #remove a session file def deleteFile( self ): index = self.script_list.curselection() if index: exec_file = self.script_list.get( index[0] ) if messagebox.askyesno(title='Delete file?', message='Are you sure to delete session \"' + exec_file + '\"?'): remove( self.script_dir + '/'+exec_file ) self.updateList() else: messagebox.showwarning( title='Warning', message='No script file selected.') #a Customized quit function def quit( self ): #save program geometry chdir( self.config_dir ) config_file=open('config.ini', 'w') config_file.write( self.parent.geometry() + '\n') config_file.write( str( self.opt_exec_with_term.get() ) + '\n') self.parent.destroy() #ui definition def initUI( self ): #pack framework self.pack( fill=BOTH, expand=1 ) #setting font FONT = ('serif', 10) #setting UI grid self.columnconfigure(0, weight=1) self.columnconfigure(2, pad=10) self.rowconfigure(6, pad=200, weight=1) #setting widgets #Label available_lb = Label( self, text='Availabel sessions:', font=FONT ) available_lb.grid( row=0, column=0, sticky=W ) #list y_scroll = Scrollbar( self, orient=VERTICAL ) y_scroll.grid( row=1, column=1, rowspan=9, sticky=N+S ) self.script_list = Listbox( self, bg='white', font=FONT, selectmode=SINGLE, yscrollcommand=y_scroll.set ) self.script_list.grid( row=1, column=0, rowspan=9, sticky=W+E+N+S ) #button exec_btn = Button( self, text='Execute', width=6, font=FONT, command=self.execute ) exec_btn.grid( row=1, column=2 ) copy_btn = Button( self, text='Copy', width=6, font=FONT, command=self.copyCheck ) copy_btn.grid( row=3, column=2 ) create_btn = Button( self, text='Create', width=6, font=FONT, command=lambda:self.popWidget( self.createFile ) ) create_btn.grid( row=2, column=2 ) edit_btn = Button( self, text='Edit', width=6, font=FONT, command=self.editFile ) edit_btn.grid( row=4, column=2 ) delete_btn = Button( self, text='Delete', width=6, font=FONT, command=self.deleteFile ) delete_btn.grid( row=5, column=2 ) help_btn = Button( self, text='Help', width=6, font=FONT, command=self.usageHelp ) help_btn.grid( row=7, column=3, sticky=E ) abt_btn = Button( self, text='About', width=6, font=FONT, command=self.about ) abt_btn.grid( row=8, column=3, sticky=E ) quit_btn = Button( self, text='Quit', width=6, font=FONT, command=self.quit ) quit_btn.grid( row=9, column=3, sticky=E ) #Option lbl2 = Label( self, text='Exeuction Options:' ) lbl2.grid( row=0, column=3, sticky=W ) execute_with_term = Checkbutton( self, text='Execute with terminal', variable=self.opt_exec_with_term ) execute_with_term.grid( row=1, column=3, sticky=E )
class ALL_IPtest(ttk.Frame): """ 任意IP地址扫描 扫描结显示到窗口 也可以选择导出到文本文件 """ def __init__(self, parent, mainframe): ttk.Frame.__init__(self, parent) self.mainframe = mainframe # 获取图片 self.ALLIP_img = ImageTk.PhotoImage(ALL_IPimg_image) self.infile_img = ImageTk.PhotoImage(infile_image) self.outFile_img = ImageTk.PhotoImage(outFile_image) self.go_img = ImageTk.PhotoImage(go_image) self.IPtest = ttk.Label(self, text='自定义扫描', image=self.ALLIP_img, compound='left', font=TITLE_FONT, foreground='#1296db') self.Get_IPtxt = ttk.Button( self, text="导入IP文件", image=self.infile_img, compound='left', command=lambda: self.start_ping()()) self.Go_Scanning = ttk.Button( self, text="开始扫描", image=self.go_img, compound='left') self.Out_ScanningTxt = ttk.Button( self, text="导出结果", image=self.outFile_img, compound='left', command=lambda: self.save_view()) self.Clean_ScanningTxt = ttk.Button( self, text="清空", command=lambda: self.cleane_view()) self.TestView = ttk.Label( self, text='扫描结果:', font=TITLE_FONT, foreground='#1296db') self.ping_test = [] # 结果显示 VERTICAL = "vertical" self.Scanning_L = Listbox(self, height=20, width=100) self.ScanViews = ttk.Scrollbar( self, orient=VERTICAL, command=self.Scanning_L.yview) self.Scanning_L['yscrollcommand'] = self.ScanViews.set ttk.Sizegrip().grid(column=2, row=4, sticky="se") self.ScanViews.grid(column=21, row=3, sticky="ns") self.Scanning_L.grid(column=1, row=3, sticky="nwes", columnspan=20, padx=5, pady=5) self.IPtest.grid(column=0, row=0, sticky="nwes", padx=5, pady=5) self.Get_IPtxt.grid(column=1, row=1, sticky="nwes", columnspan=1, rowspan=1, padx=5, pady=5) self.Go_Scanning.grid(column=2, row=1, sticky="nwes", columnspan=1, rowspan=1, padx=5, pady=5) self.Out_ScanningTxt.grid( column=20, row=20, sticky="nwes", columnspan=1, rowspan=1, padx=5, pady=5) self.Clean_ScanningTxt.grid( column=1, row=20, sticky="nwes", columnspan=1, rowspan=1, padx=5, pady=5) self.TestView.grid(column=1, row=2, sticky="nwes", padx=5, pady=5) # 获取IP def check_file(self): """ askopenfilename获取IP地址文件 """ self.open_filename = askopenfilename( title='打开文件', filetypes=[('All Files', '*')]) with open(self.open_filename, 'r') as f: self.startip = f.readlines() return(self.startip) # 处理IP def start_ping(self): """ 启动多线程 检查IP地址合法性 """ get_ALLip = self.check_file() pthread_list = [] self.Scanning_L.insert( 'end', '时间 IP地址 测试次数 通信状态') for line in get_ALLip: if len(line.strip()): ip = line.strip('\n') # 开始测试 pthread_list.append(threading.Thread( target=self.get_ping_result, args=(ip,))) for item in pthread_list: item.setDaemon(True) item.start() self.ping_test = [['时间', 'IP地址', 'Ping次数', '通信情况']] def get_ping_result(self, ip): """ 检查对应的IP是否被占用 """ cmd_str = "ping {0} -n 4 -w 600".format(ip) DETACHED_PROCESS = 0x00000008 # 不创建cmd窗口 time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') try: subprocess.run(cmd_str, creationflags=DETACHED_PROCESS, check=True) # 仅用于windows系统 except subprocess.CalledProcessError as err: self.Scanning_L.insert( 'end', '%s %s 4 通信失败' % (str(time_now), ip)) self.ping_test.append([time_now, ip, 4, '通信失败']) else: self.ping_test.append([time_now, ip, 4, '通信正常']) self.Scanning_L.insert( 'end', '%s %s 4 通信正常' % (str(time_now), ip)) self.Scanning_L.update() def cleane_view(self): self.Scanning_L.delete('0', 'end') def save_view(self): PingTest = xlwt.Workbook() # 新建一个excel sheet = PingTest.add_sheet('Ping测试数据结果') # 添加一个sheet页 row = 0 # 控制行 for stu in self.ping_test: col = 0 # 控制列 for s in stu: # 再循环里面list的值,每一列 sheet.write(row, col, s) col += 1 row += 1 PingTest.save('Ping测试数据结果.xls') # 保存到当前目录下 messagebox.showinfo('提示', '数据已导出到程序可执行文件目录下的(Ping测试数据结果.xls)文件中!')
class Tela_bibliotecario(Tela): '''Classe que modela a interface grafica da tela do bibliotecario depois de feito o login''' def __init__(self): super().__init__() self.janela.wm_title("bibliotecario - DELIBRARY") self.txt_nome_cliente = StringVar() self.txt_sobrenome_cliente = StringVar() self.txt_cpf_cliente = StringVar() self.txt_login_cliente = StringVar() self.txt_senha_cliente = StringVar() self.txt_email_cliente = StringVar() self.txt_id_livro = StringVar() self.txt_nome_livro = StringVar() self.txt_genero_livro = StringVar() self.txt_autor_livro = StringVar() self.txt_area_livro = StringVar() self.txt_editora_livro = StringVar() self.txt_edicao_livro = StringVar() self.lbl_janela_cliente = Label(self.janela, text="CRIAR/REMOVER ACESSO CLIENTE") self.lbl_nome_cliente = Label(self.janela, text="Nome") self.lbl_sobrenome_cliente = Label(self.janela, text="Sobrenome") self.lbl_cpf_cliente = Label(self.janela, text="CPF") self.lbl_email_cliente = Label(self.janela, text="Email ") self.lbl_login_cliente = Label(self.janela, text="Criar login") self.lbl_senha_cliente = Label(self.janela, text="Criar senha") self.ent_nome_cliente = Entry(self.janela, textvariable=self.txt_nome_cliente) self.ent_sobrenome_cliente = Entry( self.janela, textvariable=self.txt_sobrenome_cliente) self.ent_cpf_clienteo = Entry(self.janela, textvariable=self.txt_cpf_cliente) self.ent_login_cliente = Entry(self.janela, textvariable=self.txt_login_cliente) self.ent_senha_cliente = Entry(self.janela, textvariable=self.txt_senha_cliente) self.ent_email_cliente = Entry(self.janela, textvariable=self.txt_email_cliente) self.btn_criar_acesso_cliente = Button(self.janela, width=15, text="Criar Acesso") self.btn_retirar_acesso_cliente = Button(self.janela, width=15, text="Retirar Acesso") self.btn_ver_todos_cliente = Button(self.janela, width=15, text="Ver Todos") self.btn_realizar_emprestimo_devolucao = Button( self.janela, width=15, text="Emprestimo/Devolucao") self.btn_fechar = Button(self.janela, width=15, text="Sair") self.list_livro = Listbox(self.janela, width=72) self.scroll_livro = Scrollbar(self.janela) self.list_cliente = Listbox(self.janela, width=72) self.scroll_cliente = Scrollbar(self.janela) self.lbl_janela_livro = Label(self.janela, text="CADASTRO DE LIVRO") self.lbl_id_livro = Label(self.janela, text="ID") self.lbl_nome_livro = Label(self.janela, text="Nome") self.lbl_genero_livro = Label(self.janela, text="Genero") self.lbl_autor_livro = Label(self.janela, text="Autor") self.lbl_area_livro = Label(self.janela, text="Area") self.lbl_editora_livro = Label(self.janela, text="Editora") self.lbl_edicao_livro = Label(self.janela, text="Edicao") self.ent_id_livro = Entry(self.janela, textvariable=self.txt_id_livro) self.ent_nome_livro = Entry(self.janela, textvariable=self.txt_nome_livro) self.ent_genero_livro = Entry(self.janela, textvariable=self.txt_genero_livro) self.ent_autor_livro = Entry(self.janela, textvariable=self.txt_autor_livro) self.ent_area_livro = Entry(self.janela, textvariable=self.txt_area_livro) self.ent_editora_livro = Entry(self.janela, textvariable=self.txt_editora_livro) self.ent_edicao_livro = Entry(self.janela, textvariable=self.txt_edicao_livro) self.btn_cadastro_livro = Button(self.janela, width=15, text="Cadastrar Livro") self.btn_retirar_livro = Button(self.janela, width=15, text="Retirar Livro") self.btn_ver_todos_livros = Button(self.janela, width=15, text="Ver Todos") def config_layout(self): '''Metodo para configurar os widgets da janela''' self.lbl_janela_cliente.grid(row=0, column=0) self.lbl_nome_cliente.grid(row=1, column=0) self.lbl_sobrenome_cliente.grid(row=2, column=0) self.lbl_cpf_cliente.grid(row=3, column=0) self.lbl_email_cliente.grid(row=4, column=0) self.lbl_login_cliente.grid(row=5, column=0) self.lbl_senha_cliente.grid(row=6, column=0) self.ent_nome_cliente.grid(row=1, column=1) self.ent_sobrenome_cliente.grid(row=2, column=1) self.ent_cpf_clienteo.grid(row=3, column=1) self.ent_email_cliente.grid(row=4, column=1) self.ent_login_cliente.grid(row=5, column=1) self.ent_senha_cliente.grid(row=6, column=1) self.btn_criar_acesso_cliente.grid(row=7, column=0) self.btn_retirar_acesso_cliente.grid(row=7, column=1) self.btn_ver_todos_cliente.grid(row=8, column=0) self.list_cliente.grid(row=1, column=3, rowspan=8) self.scroll_cliente.grid(row=1, column=4, rowspan=8) self.list_cliente.configure(yscrollcommand=self.scroll_cliente.set) self.scroll_cliente.configure(command=self.list_cliente.yview) self.lbl_janela_livro.grid(row=9, column=0) self.lbl_id_livro.grid(row=10, column=0) self.lbl_nome_livro.grid(row=11, column=0) self.lbl_genero_livro.grid(row=12, column=0) self.lbl_autor_livro.grid(row=13, column=0) self.lbl_area_livro.grid(row=14, column=0) self.lbl_editora_livro.grid(row=15, column=0) self.lbl_edicao_livro.grid(row=16, column=0) self.ent_id_livro.grid(row=10, column=1) self.ent_nome_livro.grid(row=11, column=1) self.ent_genero_livro.grid(row=12, column=1) self.ent_autor_livro.grid(row=13, column=1) self.ent_area_livro.grid(row=14, column=1) self.ent_editora_livro.grid(row=15, column=1) self.ent_edicao_livro.grid(row=16, column=1) self.btn_cadastro_livro.grid(row=17, column=0) self.btn_retirar_livro.grid(row=17, column=1) self.btn_realizar_emprestimo_devolucao.grid(row=18, column=0) self.btn_ver_todos_livros.grid(row=18, column=1) self.btn_fechar.grid(row=19, column=0) self.list_livro.grid(row=10, column=3, rowspan=8) self.scroll_livro.grid(row=10, column=4, rowspan=8) self.list_livro.configure(yscrollcommand=self.scroll_livro.set) self.scroll_livro.configure(command=self.list_livro.yview) def iniciar(self): '''Metodo para desenhar a janela e processar eventos''' self.config_layout() return super().iniciar()
class OptimizerMainWindow: """ classdocs """ # TODO: change that name def reactToClick(self, event): a = AddRestrictionDialog(self) def __init__(self, optimizer): # always have a reference to model/controller self.optimizer = optimizer # setup main GUI and make stretchable self.guiRoot = Tk() self.guiRoot.title("OPTIMIZR") self.guiRoot.columnconfigure(1, weight=1) self.guiRoot.rowconfigure(0, weight=1) # left (settings) and right (sequences) part self.frameLeft = Frame(self.guiRoot) self.frameLeft.grid(row=0, column=0, sticky=W + E + N + S) self.frameLeft.columnconfigure(0, weight=1) self.frameRight = Frame(self.guiRoot) self.frameRight.grid(row=0, column=1, sticky=W + E + N + S) self.frameRight.columnconfigure(0, weight=1) self.frameRight.rowconfigure(0, weight=1) self.frameRight.rowconfigure(1, weight=1) self.frameSpeciesControll = LabelFrame(self.frameLeft, text="Species", pady=10, padx=10) self.frameSpeciesControll.columnconfigure(1, weight=1) self.frameOptimizationControll = LabelFrame(self.frameLeft, text="Optimization", pady=10, padx=10) self.frameRestrictionControll = LabelFrame(self.frameLeft, text="Restriction Enzymes", pady=10, padx=10) self.frameSpeciesControll.grid(row=0, column=0, sticky=W + E, padx=10, pady=10) self.frameOptimizationControll.grid(row=1, column=0, sticky=W + E, padx=10, pady=10) self.frameRestrictionControll.grid(row=2, column=0, sticky=W + E, padx=10, pady=10) # Species Controll Label(self.frameSpeciesControll, text="Source:").grid(row=0, column=0) Label(self.frameSpeciesControll, text="Target:").grid(row=1, column=0) self.comboSourceSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboSourceSpecies.grid(row=0, column=1, pady=5, sticky="ew") self.comboTargetSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboTargetSpecies.grid(row=1, column=1, pady=5, sticky="we") self.buttonSpeciesList = Button(self.frameSpeciesControll, text="Edit Species List") self.buttonSpeciesList.grid(row=2, column=1, pady=5, sticky="e") self.comboSourceSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) self.comboTargetSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Optimization Controll Label(self.frameOptimizationControll, text="Optimization Strategy:").grid(row=0, column=0) self.comboOptimizationStrategy = Combobox(self.frameOptimizationControll, state="readonly") self.comboOptimizationStrategy.grid(row=0, column=1) self.comboOptimizationStrategy["values"] = self.optimizer.possibleOptimizationStrategies self.comboOptimizationStrategy.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Restriction Enzymes self.listRestriction = Listbox(self.frameRestrictionControll) self.listRestriction.grid(row=0, column=0, columnspan=3, pady=5, sticky=W + E) self.frameRestrictionControll.columnconfigure(0, weight=1) self.buttonRestricionAdd = Button(self.frameRestrictionControll, text=" + ") self.buttonRestricionDel = Button(self.frameRestrictionControll, text=" - ") self.buttonRestricionAdd.grid(row=1, column=1, padx=5) self.buttonRestricionDel.grid(row=1, column=2, padx=5) # Source Sequence Frame self.frameSourceSequence = LabelFrame(self.frameRight, text="Source Sequence", padx=10, pady=10) self.frameResultSequence = LabelFrame(self.frameRight, text="Result Sequence", padx=10, pady=10) self.frameSourceSequence.grid(row=0, column=0, sticky="wens", padx=10, pady=10) self.frameResultSequence.grid(row=1, column=0, sticky="wens", padx=10, pady=10) self.buttonSourceLoad = Button(self.frameSourceSequence, text=" Load ") self.textSourceSeq = ScrolledText(self.frameSourceSequence, height=10) self.buttonSourceLoad.grid(row=0, column=1, sticky="e", pady=5) self.textSourceSeq.grid(row=1, column=0, columnspan=2, sticky="wens") self.frameSourceSequence.columnconfigure(0, weight=1) self.frameSourceSequence.rowconfigure(1, weight=1) self.textSourceSeq.frame.columnconfigure(1, weight=1) self.textSourceSeq.frame.rowconfigure(0, weight=1) self.buttonOptimize = Button(self.frameResultSequence, text=" OPTIMIZE! ") self.buttonOptimize.bind("<ButtonRelease>", self.actionOptimize) self.buttonRemoveRestriction = Button(self.frameResultSequence, text=" RESTRICTION-B-GONE! ") self.buttonRemoveRestriction.bind("<ButtonRelease>", self.actionRemoveRestricion) self.buttonSaveResult = Button(self.frameResultSequence, text=" Save ") self.textResultSequence = ScrolledText(self.frameResultSequence, height=10) self.buttonOptimize.grid(column=0, row=0, pady=5, sticky="w") self.buttonRemoveRestriction.grid(column=1, row=0, pady=5, padx=10, sticky="w") self.textResultSequence.grid(row=1, column=0, columnspan=4, sticky="wens") self.buttonSaveResult.grid(row=2, column=3, pady=5, sticky="e") self.frameResultSequence.columnconfigure(2, weight=1) self.frameResultSequence.rowconfigure(1, weight=1) self.textResultSequence.frame.columnconfigure(1, weight=1) self.textResultSequence.frame.rowconfigure(0, weight=1) self.textSourceSeq.bind("<<Modified>>", self.actionSequenceModified) self.textResultSequence.bind("<<Modified>>", self.actionSequenceModified) # generate color tags for textboxes for i in range(101): # green for normal codons (r, g, b) = colorsys.hsv_to_rgb(210 / 360, i / 100, 1.0) colorHex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255)) self.textSourceSeq.tag_config("normal" + str(i), background=colorHex) self.textResultSequence.tag_config("normal" + str(i), background=colorHex) # red for codons with restriction sites (r, g, b) = colorsys.hsv_to_rgb(5 / 360, i / 100, 1.0) colorHex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255)) self.textSourceSeq.tag_config("restrict" + str(i), background=colorHex) self.textResultSequence.tag_config("restrict" + str(i), background=colorHex) # Set (minimum + max) Window size self.guiRoot.update() self.guiRoot.minsize(self.guiRoot.winfo_width(), self.guiRoot.winfo_height()) self.buttonRestricionAdd.bind("<ButtonRelease>", self.reactToClick) self.buttonRestricionDel.bind("<ButtonRelease>", self.actionRestrictionEnzymeDelete) self.buttonSpeciesList.bind("<ButtonRelease>", self.actionEditSpeciesButton) self.buttonSourceLoad.bind("<ButtonRelease>", self.actionLoadSequence) self.buttonSaveResult.bind("<ButtonRelease>", self.actionSaveSequence) # TEST # self.listRestriction.insert("end", "EcoRI") # self.listRestriction.insert("end", "BamHI") # # dummy event to manually trigger update self.guiRoot.bind("<<Update>>", self.actionUpdate) self.actionUpdate(None) self.guiRoot.mainloop() def actionRestrictionEnzymeDelete(self, event): try: selectedEnzyme = self.listRestriction.selection_get() self.optimizer.restrictionEnzymeList.remove(selectedEnzyme) self.guiRoot.event_generate("<<Update>>") except tkinter.TclError: # no selection pass def actionUpdate(self, event): # print("update called") # clear list of restriction enzymes self.listRestriction.delete(0, "end") for r in self.optimizer.restrictionEnzymeList: self.listRestriction.insert("end", r) self.comboSourceSpecies.delete(0, "end") self.comboTargetSpecies.delete(0, "end") speciesValues = list() for (taxid, name) in self.optimizer.speciesList: speciesValues.append(taxid + ": " + name) self.comboSourceSpecies["values"] = speciesValues self.comboTargetSpecies["values"] = speciesValues if self.comboSourceSpecies.get() not in speciesValues: self.comboSourceSpecies.set("") if self.comboTargetSpecies.get() not in speciesValues: self.comboTargetSpecies.set("") self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) self.optimizer.saveConfig("config.ini") def actionEditSpeciesButton(self, event): speciesListDialog = SpeciesListDialog(self) def actionOptimizerSettingsChanged(self, event=None): # print("Something happened") strategy = self.comboOptimizationStrategy.get() sourceString = self.comboSourceSpecies.get() targetString = self.comboTargetSpecies.get() if not (strategy and sourceString and targetString): return sourceTaxid = sourceString.split(":")[0] targetTaxid = targetString.split(":")[0] self.optimizer.setOptimizer(sourceTaxid, targetTaxid, strategy) self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) # self.optimizer.testPrint() def actionOptimize(self, event=None): self.optimizer.runOptimization() self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) def actionRemoveRestricion(self, event=None): self.optimizer.runRestricionRemoval() self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) def actionSequenceModified(self, event=None): # necessary if, otherwise -> infinite loop if self.textSourceSeq.edit_modified(): seq = self.textSourceSeq.get("1.0", "end").strip() seq = stripCharsNotInList(seq.upper(), ["A", "C", "G", "T"]) self.optimizer.setSourceSeq(seq) oldInsert = self.textSourceSeq.index("insert") self.textSourceSeq.delete("1.0", "end") sourceCodons = self.optimizer.getCodonsForPrint(True) if not sourceCodons: self.textSourceSeq.insert("end", self.optimizer.sourceSequence) else: for (co, sc, r) in sourceCodons: if sc: if not r: self.textSourceSeq.insert("end", co, "normal" + str(int(sc * 100))) # print("normal"+str(int(sc*100))) else: self.textSourceSeq.insert("end", co, "restrict" + str(int(sc * 100))) else: # remainder without color self.textSourceSeq.insert("end", co) self.textSourceSeq.mark_set("insert", oldInsert) # reset the modified status at the very end self.textSourceSeq.edit_modified(False) if self.textResultSequence.edit_modified(): seq = self.textResultSequence.get("1.0", "end").strip() # self.optimizer.setOptimizedSeq(seq) oldInsert = self.textResultSequence.index("insert") self.textResultSequence.delete("1.0", "end") targetCodons = self.optimizer.getCodonsForPrint(False) if not targetCodons: self.textSourceSeq.insert("end", self.optimizer.optimizedSequence) else: for (co, sc, r) in targetCodons: if sc: if not r: self.textResultSequence.insert("end", co, "normal" + str(int(sc * 100))) # print("normal"+str(int(sc*100))) else: self.textResultSequence.insert("end", co, "restrict" + str(int(sc * 100))) else: # remainder without color self.textResultSequence.insert("end", co) self.textSourceSeq.mark_set("insert", oldInsert) self.textResultSequence.edit_modified(False) def actionLoadSequence(self, event=None): filename = tkinter.filedialog.askopenfilename() if filename: seq = sequenceIO.readFile(filename) self.textSourceSeq.delete("1.0", "end") self.textSourceSeq.insert("end", seq) self.textSourceSeq.edit_modified(True) def actionSaveSequence(self, event=None): filename = tkinter.filedialog.asksaveasfilename() if filename: # print("file is " + filename) with open(filename, mode="w") as fd: fd.write(self.optimizer.optimizedSequence)
class PayrollGui: def __init__(self): #database self.database = mysql.connector.connect(host = "123.2111.106.137", user = "******", passwd = "it@jcu") self.cursorObject = self.database.cursor() #create main window self.mainWindow = tkinter.Tk() self.mainWindow.title("Simmar-Tech Payroll System") self.mainWindow.resizable(1,1) self.mainWindow.maxsize(width = 900,height = 500) self.mainWindow.minsize(width = 700, height = 400) self.mainWindow.configure(background = "white") #create buttons self.homeButton = tkinter.Button(self.mainWindow, text = "Home", fg = "black", bg = "white",width = 25, command = self.displayHomeWindow) self.homeButton.grid(row = 0, column = 0,columnspan = 2) self.EmployeeDetailsButton = tkinter.Button(self.mainWindow, text = "Employee Details", fg = "black", bg = "white",width = 25, command = self.displayEmployeeDetailsWindow) self.EmployeeDetailsButton.grid(row = 0, column = 2, columnspan = 1) self.PayrollButton = tkinter.Button(self.mainWindow, text = "Payroll", fg = "black", bg = "white", width = 25,command = self.displayRunPayrollWindow) self.PayrollButton.grid(row = 0, column = 3, columnspan = 1) #create panels #home Panel self.newsPanel = tkinter.Label(self.mainWindow, text = "News", bg = "white") self.newsPanel.grid(column = 1, row = 1, columnspan = 5, rowspan = 5) #Add/Edit Employee Panels and field entries self.firstNameLabel = tkinter.Label(self.mainWindow, text='First Name:',width = 25) self.firstNameEntry = tkinter.Entry(self.mainWindow, text='First Name:',width = 25) self.middleNameLabel = tkinter.Label(self.mainWindow, text = 'Middle Names:',width = 25) self.middleNameEntry = tkinter.Entry(self.mainWindow, text = 'Middle Names:',width = 25) self.lastNameLabel= tkinter.Label(self.mainWindow, text = 'Last Name:', width = 25) self.lastNameEntry= tkinter.Entry(self.mainWindow, text = 'Last Name:', width = 25) self.genderLabel = tkinter.Label(self.mainWindow, text = 'Gender', width = 25) self.genderEntry = tkinter.Entry(self.mainWindow, width = 25) self.dateOfBirthLabel = tkinter.Label(self.mainWindow, text = 'Date of Birth', width = 25) self.dateOfBirthEntry = tkinter.Entry(self.mainWindow, text = 'Date of Birth', width = 25) self.addressLabel = tkinter.Label(self.mainWindow, text = 'Address', width = 25) self.addressEntry = tkinter.Entry(self.mainWindow, text = 'Address', width = 25) self.affiliationLabel = tkinter.Label(self.mainWindow,text = 'Affiliation', width = 25) self.affiliationEntry = tkinter.Entry(self.mainWindow,text = 'Affiliation', width = 25) self.classificationLabel = tkinter.Label(self.mainWindow, text = 'Classification', width = 25) self.classificationEntry = tkinter.Entry(self.mainWindow, text = 'Classification', width = 25) self.salaryLabel = tkinter.Label(self.mainWindow, text = 'Salary', width = 25) self.salaryEntry = tkinter.Entry(self.mainWindow, text = 'Salary', width = 25) self.hourlyRateLabel = tkinter.Label(self.mainWindow, text = 'Hourly Rate', width = 25) self.hourlyRateEntry = tkinter.Entry(self.mainWindow, text = 'Hourly Rate', width = 25) #Add/Edit Employee self.SearchButton = tkinter.Button(self.mainWindow, text = "Search", bg = "white", width = 25) self.DataField = tkinter.Entry(self.mainWindow, bg = "white", width = 60) self.addEmployeeButton = tkinter.Button(self.mainWindow, text = "Add Employee", bg = "white", width = 25,command = self.addEmployee) self.EditEmployeeButton = tkinter.Button(self.mainWindow, text = "Edit", bg = "white", width = 25) #List box self.employeeList = Listbox(self.mainWindow, width = 60, height = 10) self.payrollList = Listbox(self.mainWindow, width = 90, height = 20) #Run Payroll Window self.calculatePayButton = tkinter.Button(self.mainWindow, text = "Calculate Pay", bg = "white", width = 25) self.message = tkinter.StringVar() self.mainWindow.mainloop() def clearWindow(self): self.newsPanel.grid_forget() self.SearchButton.grid_forget() self.DataField.grid_forget() self.EditEmployeeButton.grid_forget() self.addEmployeeButton.grid_forget() self.calculatePayButton.grid_forget() self.employeeList.grid_forget() self.firstNameLabel.grid_forget() self.firstNameEntry.grid_forget() self.middleNameLabel.grid_forget() self.middleNameEntry.grid_forget() self.lastNameLabel.grid_forget() self.lastNameEntry.grid_forget() self.genderLabel.grid_forget() self.genderEntry.grid_forget() self.dateOfBirthLabel.grid_forget() self.dateOfBirthEntry.grid_forget() self.addressLabel.grid_forget() self.addressEntry.grid_forget() self.affiliationLabel.grid_forget() self.affiliationEntry.grid_forget() self.classificationLabel.grid_forget() self.classificationEntry.grid_forget() self.salaryLabel.grid_forget() self.salaryEntry.grid_forget() self.hourlyRateLabel.grid_forget() self.hourlyRateEntry.grid_forget() self.payrollList.grid_forget() def displayHomeWindow(self): self.clearWindow() self.newsPanel.grid(column = 1, row = 1, columnspan = 5, rowspan = 5) def displayEmployeeDetailsWindow(self): self.clearWindow() self.EditEmployeeButton.grid(column = 2, row = 6) self.addEmployeeButton.grid(column = 1, row = 6) self.SearchButton.grid(column =1, row = 2) self.DataField.grid(column = 2, row = 2,columnspan = 2) self.employeeList.grid(column =1,row = 3,columnspan = 2) self.firstNameLabel.grid(column = 1, row = 7) self.firstNameEntry.grid(column = 1, row = 8) self.middleNameLabel.grid(column =1, row = 9) self.middleNameEntry.grid(column = 1,row = 10) self.lastNameLabel.grid(column = 1, row = 11) self.lastNameEntry.grid(column = 1, row = 12) self.genderLabel.grid(column = 2, row = 7) self.genderEntry.grid(column = 2, row = 8) self.dateOfBirthLabel.grid(column = 2, row = 9) self.dateOfBirthEntry.grid(column = 2, row = 10) self.affiliationLabel.grid(column = 2, row = 11) self.affiliationEntry.grid(column = 2, row = 12) self.classificationLabel.grid(column = 3, row = 7) self.classificationEntry.grid(column = 3, row = 8) self.salaryLabel.grid(column = 3, row = 9) self.salaryEntry.grid(column = 3, row = 10) self.hourlyRateLabel.grid(column= 3, row = 11) self.hourlyRateEntry.grid(column = 3, row = 12) self.addressLabel.grid(column = 1, row = 13) self.addressEntry.grid(column = 2, row = 13) def addEmployee(self): self.firstNameContent = self.firstNameEntry.get() self.firstNameEntry.delete(0,END) self.middleNameContent = self.middleNameEntry.get() self.middleNameEntry.delete(0,END) self.lastNameContent = self.middleNameEntry.get() self.lastNameEntry.delete(0,END) self.genderContent = self.genderEntry.get() self.genderEntry.delete(0,END) self.dateOfBirthContent = self.dateOfBirthEntry.get() self.dateOfBirthEntry.delete(0,END) self.affiliationContent = self.affiliationEntry.get() self.affiliationEntry.delete(0,END) self.classificationContent = self.affiliationEntry.get() self.classificationEntry.delete(0,END) self.salaryContent = self.salaryEntry.get() self.salaryEntry.delete(0,END) self.hourlyContent = self.hourlyRateEntry.get() self.hourlyRateEntry.delete(0,END) self.addressContent = self.addressEntry.get() self.addressEntry.delete(1,END) employeeListItems = (self.firstNameContent, self.middleNameContent, self.lastNameContent, self.genderContent, self.dateOfBirthContent,self.affiliationContent,self.classificationContent,self.salaryContent,self.hourlyContent,self.addressContent) self.employeeList.insert(1,employeeListItems) def getContent(self): self.newList = [] number = 1 for content in self.cursorObject.fetchall(): self.payrollList.insert(number,content) number = number + 1 def displayRunPayrollWindow(self): self.clearWindow() self.calculatePayButton.grid(column = 1, row = 7) self.payrollList.grid(column = 1, row = 6, columnspan = 4)
class CableLabelGUI(Frame): def __init__(self): super().__init__() self.initUI() def initUI(self): self.dir_name = "" os.chdir(r"C:\Users\Csullivan\Documents\AutoCAD Publish") self.master.title("Cable Label Print Utility") Style().configure("TButton", padding=(3, 5, 3, 5), font='serif 10') self.columnconfigure(0, pad=3) self.rowconfigure(0, pad=3) grp = LabelFrame(self.master, text="Print to Brady printer from CSV or XML") grp.grid(row=0, column=0) grp.config(padx=50, pady=20) grp2 = LabelFrame(self.master, text="Print directly from XML") grp2.grid(row=1, column=0) grp2.config(padx=50, pady=20) self.lbls_csv = StringVar() self.lbls_csv.set(r".\sample.txt") self.lbls_xml = StringVar() self.lbls_xml.set(r".\sample.xml") # Choose file buttons btn_csv_file = Button(grp, text="Choose CSV File", command=self.choose_csv_file) btn_csv_file.grid(row=0, column=0) label_csv = Label(grp, textvariable=self.lbls_csv, width=40) label_csv.grid(row=0, column=1) btn_print_all = Button(grp, text="Print All", command=self.print_xml_files) btn_print_all.grid(row=1, column=0) #label_xml = Label(grp, textvariable = self.lbls_xml, width=40) #label_xml.grid(row=1, column=1) btn_xml_file = Button(grp2, text="Print XML File", command=self.print_xml_file) btn_xml_file.grid(row=0, column=0) self.lstbx_log = Listbox(grp, selectmode="extended") self.lstbx_log.grid(row=0, column=2) def choose_csv_file(self): filepath = filedialog.askopenfilename() fp_csv_sp = ntpath.split(filepath) filename = fp_csv_sp[1] self.dir_name = filename.split(".") self.dir_name = self.dir_name[0] self.lbls_csv.set(filename) #print(dir_name) if (not os.path.isdir(self.dir_name)): os.mkdir(self.dir_name) #print(filename) GenerateXMLinFives(self.dir_name, filename) self.lstbx_log.insert("end", "Saved to " + filepath) self.lstbx_log.insert("end", "Ready to print...") def print_xml_files(self): if (self.dir_name): files = os.listdir(self.dir_name) for f in files: SendToBP33(f, False) self.lstbx_log.insert("end", "Sent " + f + " to printer") time.sleep(7) self.lstbx_log.insert("end", "Done printing") def print_xml_file(self): filepath = filedialog.askopenfilename() SendToBP33(filepath, False)
class FeasDisp(ttk.Frame): """Widget for displaying all of the feasible states in the conflict.""" def __init__(self, master=None, conflict=None, *args): """Initialize the widget.""" ttk.Frame.__init__(self, master, padding=5) self.columnconfigure(1, weight=1) self.rowconfigure(2, weight=1) self.conflict = conflict self.dispFormat = StringVar(value='pattern') self.dispList = StringVar() self.feasList = [] self.fmts = { 'Pattern': 'YN-', 'List (YN)': 'YN', 'List (ordered and [decimal])': 'ord_dec' } cBoxOpts = ('Pattern', 'List (YN)', 'List (ordered and [decimal])') self.feasText = ttk.Label(self, text='Perceived States') self.feasText.grid(row=0, column=0, columnspan=3) self.cBox = ttk.Combobox(self, textvariable=self.dispFormat, values=cBoxOpts, state='readonly') self.cBoxLb = ttk.Label(self, text='Format:') self.feasLBx = Listbox(self, listvariable=self.dispList) self.scrl = ttk.Scrollbar(self, orient=VERTICAL, command=self.feasLBx.yview) # ########### self.cBoxLb.grid(column=0, row=1, sticky=NSEW, pady=3) self.cBox.grid(column=1, row=1, columnspan=2, sticky=NSEW, pady=3) self.feasLBx.grid(column=0, row=2, columnspan=2, sticky=NSEW) self.scrl.grid(column=2, row=2, sticky=NSEW) self.cBox.bind('<<ComboboxSelected>>', self.fmtSel) self.feasLBx.configure(yscrollcommand=self.scrl.set) self.dispFormat.set('Pattern') def fmtSel(self, *args): """Action on selection of a new format.""" self.refresh() def setFeas(self, feasList): """Change the list of feasible states to be displayed.""" self.feasList = feasList self.refresh() def refresh(self): """Update the list of perceived states displayed and the format.""" self.activeDM.calculatePerceived() fmt = self.fmts[self.dispFormat.get()] if fmt == "YN-": perc = self.activeDM.perceived.dash if fmt == "YN": perc = self.activeDM.perceived.yn if fmt == "ord_dec": perc = self.activeDM.perceived.ordDec self.dispList.set(tuple(perc))
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 HVPS: def __init__(self, master): self.master = master master.title("LoCoLab HVPS Console") self.ser = None LCOL = 0 RCOL = 4 # Critical parameters #self.CURRENTVOLTAGE = IntVar(master,value=0) #self.TARGETVOLTAGE = IntVar(master,value=0) #self.PWM = IntVar(master,value=0) self.CURRENTVOLTAGE = StringVar(master, value='0') self.TARGETVOLTAGE = StringVar(master, value='0') self.PWM = StringVar(master, value='30') self.IS_SERIAL_CONNECTED = False # Plotting parameters self.npoints = 240 self.current_line = [0 for x in range(self.npoints)] self.target_line = [0 for x in range(self.npoints)] # Plots =============================================================== self.f1 = plt.figure(figsize=PLOTRATIO, dpi=PLOTDPI) self.a1 = self.f1.add_subplot(111) self.a1.grid() self.a1.set_title("Voltage") self.canvas1 = FigureCanvasTkAgg(self.f1, master) self.canvas1.get_tk_widget().grid(sticky='W', row=0, rowspan=5, column=LCOL + 0, columnspan=RCOL) self.f2 = plt.figure(figsize=PLOTRATIO, dpi=PLOTDPI) self.a2 = self.f2.add_subplot(111) self.a2.grid() self.a2.set_title("PWM") self.canvas2 = FigureCanvasTkAgg(self.f2, master) self.canvas2.get_tk_widget().grid(sticky='W', row=6, rowspan=1, column=LCOL + 0, columnspan=RCOL) self.f3 = plt.figure(figsize=PLOTRATIO, dpi=PLOTDPI) self.a3 = self.f3.add_subplot(111) self.a3.grid() self.a3.set_title("Signal") self.canvas3 = FigureCanvasTkAgg(self.f3, master) self.canvas3.get_tk_widget().grid(sticky='W', row=6, rowspan=1, column=RCOL + 1, columnspan=7) self.a3_xlim = 0 self.a3_ylim = 0 # Labels ============================================================== self.currentlabel = Label(master, text="Current:", font=LABELFONT) self.currentlabel.grid(row=0, column=RCOL + 1) self.dynamic_currentlabel = Label(master, textvar=self.CURRENTVOLTAGE, font=LABELFONT) self.dynamic_currentlabel.grid(row=0, column=RCOL + 2, sticky='W') self.currentunitslabel = Label(master, text="kV") self.currentunitslabel.grid(row=0, column=RCOL + 3, sticky='W') self.targetlabel = Label(master, text="Target:", font=LABELFONT) self.targetlabel.grid(row=1, column=RCOL + 1) self.dynamic_targetlabel = Label(master, textvar=self.TARGETVOLTAGE, font=LABELFONT) self.dynamic_targetlabel.grid(row=1, column=RCOL + 2, sticky='W') self.targetunitslabel = Label(master, text="kV") self.targetunitslabel.grid(row=1, column=RCOL + 3, sticky='W') self.pwmlabel = Label(master, text="PWM:", font=LABELFONT) self.pwmlabel.grid(row=2, column=RCOL + 1) self.dynamic_pwmlabel = Label(master, textvar=self.PWM, font=LABELFONT) self.dynamic_pwmlabel.grid(row=2, column=RCOL + 2, sticky='W') self.pwmunitslabel = Label(master, text="/ 1023") self.pwmunitslabel.grid(row=2, column=RCOL + 3, sticky='W') # Target Voltage Input ================================================ self.targetvoltageentrystr = StringVar(master, value='0') self.targetvoltageentry = Entry(master, textvar=self.targetvoltageentrystr) self.targetvoltageentry.grid(row=1, column=RCOL + 4) self.targetvoltagesendbutton = Button(master, text="Send", command=self.SendVoltage) self.targetvoltagesendbutton.grid(row=1, column=RCOL + 5) # Signal ============================================================== # self.signallabel = Label(master,text="Signal:") # self.signallabel.grid(row=3,column=1) self.IS_SENDING_SIGNAL = False self.signalx = [] self.signaly = [] self.signallistbox = Listbox(master, height=2) self.signallistbox.insert(1, "Step") self.signallistbox.insert(2, "Stairstep") self.signallistbox.insert(3, "Sawtooth") self.signallistbox.grid(sticky='E', row=7, column=RCOL + 1, columnspan=2) self.amplitudelabel = Label(master, text="Amplitude:") self.amplitudelabel.grid(row=8, column=RCOL + 1) self.amplitudeentrystr = StringVar(master, value='0.5') self.amplitudeentry = Entry(master, textvar=self.amplitudeentrystr) self.amplitudeentry.grid(row=8, column=RCOL + 2, columnspan=2) self.amplitudeunitslabel = Label(master, text="kV") self.amplitudeunitslabel.grid(row=8, column=RCOL + 4) self.dwelltimelabel = Label(master, text="Dwell time:") self.dwelltimelabel.grid(row=9, column=RCOL + 1) self.dwelltimeentrystr = StringVar(master, value='30') self.dwelltimeentry = Entry(master, textvar=self.dwelltimeentrystr) self.dwelltimeentry.grid(row=9, column=RCOL + 2, columnspan=2) self.dwelltimeunitslabel = Label(master, text="sec") self.dwelltimeunitslabel.grid(row=9, column=RCOL + 4) self.nrepslabel = Label(master, text="# Reps:") self.nrepslabel.grid(row=10, column=RCOL + 1) self.nrepsspinbox = Spinbox(master, from_=0, to_=50) self.nrepsspinbox.grid(row=10, column=RCOL + 2, columnspan=2) self.updatesignalbutton = Button(master, text="Update", command=self.UpdateSignalButton) self.updatesignalbutton.grid(row=11, column=RCOL + 1) self.executesignalbutton = Button(master, text="Execute", command=self.ExecuteSignalButton) self.executesignalbutton.grid(row=11, column=RCOL + 2) # Serial port ========================================================= self.seriallabel = Label(master, text="Serial Port") self.seriallabel.grid(sticky='W', row=7, column=0) self.serialentrystr = StringVar(master, value='/dev/cu.wchusbserial1420') self.serialentry = Entry(master, textvar=self.serialentrystr) self.serialentry.grid(sticky='W', row=7, column=1) self.serialconnectbutton = Button(master, text="Connect", command=self.ConnectToSerial) self.serialconnectbutton.grid(sticky='W', row=7, column=2) self.baudratelabel = Label(master, text="Baud Rate") self.baudratelabel.grid(sticky='W', row=8, column=0) self.baudrateentrystr = StringVar(master, value='115200') self.baudrateentry = Entry(master, textvar=self.baudrateentrystr) self.baudrateentry.grid(sticky='W', row=8, column=1) # Data Logging ======================================================== self.loglabel = Label(master, text="Data Logging") self.loglabel.grid(sticky='W', row=9, column=0) self.logfnameentrystr = StringVar(master, value='SessionLog.txt') self.logfnameentry = Entry(master, textvar=self.logfnameentrystr) self.logfnameentry.grid(sticky='W', row=9, column=1) self.logging_variable = IntVar(master, value=0) self.logging_offbutton = Radiobutton(master, text="Off", variable=self.logging_variable, value=0, width=4) self.logging_offbutton.grid(row=9, column=2) self.logging_onbutton = Radiobutton(master, text="On", variable=self.logging_variable, value=1, width=4) self.logging_onbutton.grid(row=9, column=3) # Abort =============================================================== self.abortbutton = Button(master, text="ABORT", command=self.ABORT) self.abortbutton.grid(row=11, column=0) return def DoNothing(self): pass def SendVoltage(self, sendv=0): try: V = float(self.targetvoltageentrystr.get()) if sendv != 0: V = sendv self.TARGETVOLTAGE.set(str(V)) w_str = "%f\n" % (V) # Format to send voltage self.ser.write(w_str.encode()) except Exception as e: print("ERROR: %s" % (e)) return def ConnectToSerial(self): try: port = self.serialentrystr.get() baudrate = int(self.baudrateentrystr.get()) print("Trying to connect to %s at %d" % (port, baudrate)) self.ser = serial.Serial(port, baudrate) self.ser.flushInput() except ValueError: print("ERROR: Invalid serial parameter.") return -1 except: print("Error") return -1 print("Success.") self.IS_SERIAL_CONNECTED = True self.GetSerialValue() return def GetSerialValue(self): if not self.IS_SERIAL_CONNECTED: #self.master.after(50,self.GetSerialValue) return try: # Grab data rawdata = self.ser.readline().decode('utf8') # Parse data currentval = float(rawdata.split(' ')[0]) targetval = float(self.TARGETVOLTAGE.get()) self.CURRENTVOLTAGE.set(str(currentval)) if self.logging_variable.get() == 1: self.LogData([targetval, currentval]) # Append data, shift over lines self.current_line.append(currentval) self.current_line = self.current_line[1:self.npoints + 1] self.target_line.append(targetval) self.target_line = self.target_line[1:self.npoints + 1] if self.IS_SENDING_SIGNAL: if len(self.signaly) == 0: self.IS_SENDING_SIGNAL = False else: #print("Sending signal: %f, next is "%(self.signaly[0]),end="") #self.SendVoltage(self.signaly[0]) v = self.signaly[0] self.TARGETVOLTAGE.set("%f" % (v)) wstr = "%f\n" % (v) self.ser.write(wstr.encode()) self.signaly = self.signaly[1:] self.signalx = self.signalx[:-1] #print("%f"%(self.signaly[0])) self.a3.clear() self.a3.plot(self.signalx, self.signaly, color='tab:blue') self.a3.set_title("Signal") self.a3.set_xlim(0, self.a3_xlim) self.a3.set_ylim(0, self.a3_ylim) self.a3.grid() self.canvas3.draw() self.master.after_idle(self.PlotLine) except Exception as e: print(e) self.master.after(REFRESH_FREQ, self.GetSerialValue) return def PlotLine(self): #max_val = max(self.current_line) + 1e-5 # Include extra for padding? self.a1.clear() self.a1.plot(self.current_line, color='tab:blue', label='Actual') self.a1.plot(self.target_line, color='tab:green', linestyle=':', label='Target') self.a1.grid() self.a1.legend(loc=3) self.a1.set_ylim(-1.5, 1.5) self.canvas1.draw() #print("Beep") return def UpdateSignalButton(self): try: selected_signal = self.signallistbox.curselection()[0] except: print("No selection!") return #print(selected_signal) try: H = float(self.amplitudeentrystr.get()) W = float(self.dwelltimeentrystr.get()) n = int(self.nrepsspinbox.get()) except ValueError: print("ERROR: Invalid signal parameter.") return if selected_signal == 0: # Step case self.signalx, self.signaly = Step(H, W, n) elif selected_signal == 1: self.signalx, self.signaly = StairStep(H, W, n) elif selected_signal == 2: self.signalx, self.signaly = Sawtooth(H, W, n) # Plot to a3 self.a3_xlim = max(self.signalx) self.a3_ylim = max(self.signaly) * 1.2 self.a3.clear() self.a3.plot(self.signalx, self.signaly, color='tab:blue') self.a3.set_title("Signal") self.a3.set_xlim(0, self.a3_xlim) self.a3.set_ylim(0, self.a3_ylim) self.a3.grid() self.canvas3.draw() return def ExecuteSignalButton(self): self.IS_SENDING_SIGNAL = True self.targetvoltagesendbutton.state = DISABLED print("Beep") return def mainloop(self): self.master.mainloop() return def LogData(self, data): fname = self.logfnameentrystr.get() f = open(fname, 'a') writestr = '' for d in data: writestr += "%f," % (d) writestr = writestr[:-1] + '\n' f.write(writestr) f.close() return def OnUpdate(self): pass def OnExecute(self): pass def ABORT(self): self.IS_SERIAL_CONNECTED = False self.TARGETVOLTAGE.set('0') self.IS_SENDING_SIGNAL = False self.signalx = [] self.signaly = [] return
class GUI(object): '''Stellt die Oberflaeche dar. Alle steuerden Taetigkeiten werden (sollten) vom Controller Objekt uebernommen werden. ''' def __init__(self): ''' Constructor ''' self.root = Tk() self.root.title("DinnerLog") self.root.minsize(800, 600) self.root.grid_columnconfigure(0, weight=1) self.root.grid_rowconfigure(0, weight=1) self.root.grid_rowconfigure(1, weight=3) # Ein Frame für alles, das mit Zutaten zu tun hat self.fr_zutaten = Labelframe(self.root, borderwidth=2, relief=GROOVE, text="Zutaten") self.fr_zutaten.grid_columnconfigure(0, weight=1) self.fr_zutaten.grid_rowconfigure(0, weight=1) self.fr_zutaten.grid(row=0, column=0, sticky="NSWE") self.lb_zutaten = Listbox(self.fr_zutaten) sb_zutaten = Scrollbar(self.lb_zutaten, orient=VERTICAL) self.lb_zutaten.configure(yscrollcommand=sb_zutaten.set) sb_zutaten.config(command=self.lb_zutaten.yview) sb_zutaten.pack(side="right", fill="both") self.lb_zutaten.grid(row=0, column=0, sticky="NSEW") self._addNeueZutatFrame() # Ein Frame in den alles, das mit Mahlzeiten zu tun hat, kommt self.fr_mahlzeit = Labelframe(self.root, borderwidth=2, relief=GROOVE, text="Mahlzeiten") self.fr_mahlzeit.grid_columnconfigure(0, weight=1) self.fr_mahlzeit.grid_rowconfigure(0, weight=1) self.fr_mahlzeit.grid(row=1, column=0, sticky="NSWE") self._addNeueMahlzeitFrame() self.lb_mahlzeiten = Listbox(self.fr_mahlzeit, selectmode=SINGLE) sb_mahlzeiten = Scrollbar(self.lb_mahlzeiten, orient=VERTICAL) sb_mahlzeiten.configure(command=self.lb_mahlzeiten.yview) self.lb_mahlzeiten.configure(yscrollcommand=sb_mahlzeiten.set) sb_mahlzeiten.pack(side="right", fill="both") self.lb_mahlzeiten.grid(row=0, column=0, sticky="NSEW") fr_neu_ok = Frame(self.fr_mahlzeit) fr_neu_ok.grid(row=1, column=0, columnspan=2, sticky="E") self.btn_neu = Button(fr_neu_ok, text="Neu") self.btn_neu.pack(side="left") self.btn_mahlzeit_als_zt = Button(fr_neu_ok, text="Als Zutat") self.btn_mahlzeit_als_zt.pack(anchor=E, side="right") self.btn_insert = Button(fr_neu_ok, text="Hinzufuegen") self.btn_insert.pack(anchor=E, side="right") self.btn_update = Button(fr_neu_ok, text="Update") self.btn_update.pack(anchor=E, side="right") self.btn_delete = Button(fr_neu_ok, text="Loeschen") self.btn_delete.pack(anchor=E, side="right") # Ein Frame der Statistiken darstellt self.fr_stats = Labelframe(self.root, borderwidth=2, relief=GROOVE, text="Statistik") self.fr_stats.grid(row=3, column=0, sticky="NSWE") #self.cv_stats = Canvas(self.fr_stats, height=80, width=600) #self.cv_stats.create_line(2,5,598,5, fill="#bbb") def _addNeueMahlzeitFrame(self): self.fr_neue_mz = Frame(self.fr_mahlzeit) self.fr_neue_mz.grid_rowconfigure(2, weight=1) self.fr_neue_mz.grid(row=0, column=1, sticky="WSNE") lbl_name = Label(self.fr_neue_mz, text="Name:") lbl_name.grid(row=0, column=0, sticky="NW") self.en_name = Entry(self.fr_neue_mz) self.en_name.grid(row=0, column=1, columnspan=2, sticky="WNE") lbl_zutat = Label(self.fr_neue_mz, text="Zutaten:") lbl_zutat.grid(row=1, column=0, sticky="NW") self.lb_zutat = Listbox(self.fr_neue_mz) sb_zutat = Scrollbar(self.lb_zutat, orient=VERTICAL) self.lb_zutat.configure(yscrollcommand=sb_zutat.set) sb_zutat.configure(command=self.lb_zutat.yview) sb_zutat.pack(side="right", fill="both") self.lb_zutat.grid(row=2, column=0, columnspan=3, sticky="NWSE") self.var_zutat = StringVar(self.fr_neue_mz) self.opt_zutat = OptionMenu(self.fr_neue_mz, self.var_zutat, "Auswahl") self.opt_zutat.grid(row=3, column=0) self.en_menge = Entry(self.fr_neue_mz) self.en_menge.grid(row=3, column=1) self.btn_mahlzeit_hinzu = Button(self.fr_neue_mz, text="Hinzu") self.btn_mahlzeit_hinzu.grid(row=3, column=2, sticky="E") def _addNeueZutatFrame(self): fr_neue_zt = Frame(self.fr_zutaten) fr_neue_zt.grid(row=0, column=2,sticky="NWSE") lbl_name = Label(fr_neue_zt, text="Name:") lbl_name.grid(row=0, column=0, sticky="W") self.en_name_zt = Entry(fr_neue_zt) self.en_name_zt.grid(row=0, column=1, columnspan=2, sticky="WE") lbl_fett = Label(fr_neue_zt, text="Fett:") lbl_fett.grid(row=1, column=0, sticky="W") self.en_fett = Entry(fr_neue_zt) self.en_fett.grid(row=1, column=1, columnspan=2) lbl_eiweiss = Label(fr_neue_zt, text="Eiweiss:") lbl_eiweiss.grid(row=2, column=0, sticky="W") self.en_eiweiss = Entry(fr_neue_zt) self.en_eiweiss.grid(row=2, column=1, columnspan=2) lbl_kh = Label(fr_neue_zt, text="Kohlenhy.:") lbl_kh.grid(row=3, column=0, sticky="W") self.en_kh = Entry(fr_neue_zt) self.en_kh.grid(row=3, column=1, columnspan=2) self.btn_zutat_insert = Button(fr_neue_zt, text="Hinzu") self.btn_zutat_insert.grid(row=4, column=1, sticky="E") self.btn_zutat_update = Button(fr_neue_zt, text="Update") self.btn_zutat_update.grid(row=5, column=1, sticky="E") self.btn_zutat_delete = Button(fr_neue_zt, text="Loeschen") self.btn_zutat_delete.grid(row=6, column=1, sticky="E")
class TVW(Frame): def __init__(self, master, *args, **kwargs): Frame.__init__(self, master) ## Variables ## self.grid() self.master = master master.title("TVW") self.showList = readData(showLocation) if self.showList == '': self.showList = [] self.showData = readData(showInfoLocation) if self.showData == '': self.showData = {} self.auto_updater = True self.run_thread = True self.cur_show = '' self.auto_progress_text = StringVar() self.update_progress_text = StringVar() self.auto_update() self.forceUpdate() ## Specialty Progress Bar ## # I somewhat understand this, but pulled offline to make it work self.style = ttk.Style(master) # add label in the layout self.style.layout('text.Horizontal.TProgressbar', [('Horizontal.Progressbar.trough', { 'children': [('Horizontal.Progressbar.pbar', { 'side': 'left', 'sticky': 'ns' })], 'sticky': 'nswe' }), ('Horizontal.Progressbar.label', { 'sticky': '' })]) # set initial text #got arround using this to change the label of all status bars, while wanting to change each individually #oh well, it works self.style.configure('text.Horizontal.TProgressbar', text='') ## Widgets ## #Details self.details = Details(self) #Out Of Date Buttons, to be set per show self.ood_buttons = [] self.list_frame = Frame(self) #list Box# self.list_scrollbar = Scrollbar(self.list_frame, orient="vertical") self.show_lb = Listbox(self.list_frame, width=30, height=15, yscrollcommand=self.list_scrollbar.set) self.show_lb.bind('<<ListboxSelect>>', self.showSelect) self.list_scrollbar.config(command=self.show_lb.yview) #Add to List# self.add_entry = Entry(self.list_frame, text="Enter Show Name") self.add_button = Button(self.list_frame, text="+", command=self.newShow) self.delete_show = Button(self.list_frame, text="Delete This Show", command=self.deleteShow) #updates# self.update_frame = Frame(self, bg='#D0D0D0') self.update_align = Frame(self.update_frame, bg='#D0D0D0') self.update_button = Button(self.update_align, text='Refresh', command=self.forceUpdate) self.auto_progress = ttk.Progressbar( self.update_align, style='text.Horizontal.TProgressbar', variable=self.auto_progress_text, length=100, mode='determinate') self.update_progress = ttk.Progressbar( self.update_align, style='text.Horizontal.TProgressbar', variable=self.update_progress_text, length=100, mode='determinate') ## LAYOUT ## #details# self.details.grid(row=0, column=1, sticky=N + E + W, padx=5, pady=5) #show list# self.list_frame.grid(row=0, column=0, rowspan=2) self.show_lb.grid(row=0, column=0, sticky=W) self.list_scrollbar.grid(row=0, column=1, sticky=N + S) self.add_entry.grid(row=1, column=0, sticky=E + W, pady=2) self.add_button.grid(row=1, column=1, sticky=W) self.delete_show.grid(row=2, column=0, columnspan=2, sticky=E + W) #update# self.update_frame.grid(row=1, column=1, sticky=S + E + W) self.update_align.pack(anchor=E) self.update_button.grid(row=0, column=1, sticky=E) self.auto_progress.grid(row=0, column=0, sticky=E) # have this appear only when running update #self.update_progress.grid(row=1,column=1, sticky=E) ### Aditional Functions ### # get show selection from Listbox def showSelect(self, evt): select = self.show_lb.curselection() show = self.showList[int(select[0])] self.cur_show = show self.details.updateDetails() # remove an out of date episode. Be up to date. def removeOOD(self, ep): print("remove", ep) self.showData[self.cur_show]['Out-of-Date'].remove(ep) self.fillListBox() self.details.updateDetails() writeData(showInfoLocation, self.showData) # Add new name to list of shows, update showLocation file, Run scrubbing script for new show, rerun FillListBox def newShow(self): #show_name = simpledialog.askstring("Name of new show","Please input Show Name") show_name = self.add_entry.get() if show_name != '': self.update([show_name]) # progress bar in lower right. always repeats. When it completes, run update function def auto_update(self): def thread_auto_update(): try: while self.run_thread: x = 0 while (x <= update_timer and self.auto_updater): x += progress_interval time.sleep(progress_interval) self.auto_progress.step( 100 / (update_timer / progress_interval)) self.style.configure( 'text.Horizontal.TProgressbar', text='{:.0f} Seconds'.format(update_timer - x)) if self.run_thread != False: self.update(self.showList) self.auto_updater = True else: print('Ending Thread') except: print( "Error in thread. Likely program ended while it was running" ) threading.Thread(target=thread_auto_update).start() # ends the current thread on auto_update, immediately forcing an update. Will reassign and restart in auto_update def forceUpdate(self): self.auto_updater = False def killUpdate(self): self.auto_updater = False self.run_thread = False # run all steps to update data. Scrub info from web, update list/new show times, ect def update(self, show_list): # Setup Variables self.add_button['state'] = 'disabled' self.update_button['state'] = 'disabled' self.update_progress.grid(row=0, column=0, sticky=W) progress = (100 / (1 + len(show_list))) self.update_progress["value"] = progress self.style.configure('text.Horizontal.TProgressbar', text="Updating") temp_show_data = {} #run Update on List of Shows for show in show_list: # check if program has closed if self.run_thread != True: break #Get data for Each Show, check if 404 or missing in list self.style.configure('text.Horizontal.TProgressbar', text=show) showInfo = updateData([show]) if showInfo == "404": print("Server Error on '", show, "', getting 404") else: temp_show_data[show] = showInfo[show] if show not in self.showList: self.showList.append(show) writeData(showLocation, self.showList) self.update_progress.step(progress) #Writing data and updating List #self.style.configure('text.Horizontal.TProgressbar', text='Updating List') self.showData = temp_show_data writeData(showInfoLocation, self.showData) self.fillListBox() self.update_progress.step(progress) #Update is complete, user can edit things again self.add_button['state'] = 'normal' self.update_button['state'] = 'normal' self.update_progress.grid_forget() # fill in the list box elements, along with Out of Date Episode Count def fillListBox(self): #### while updating list, check for out of date episodes, and include number for size next to name #### self.show_lb.delete(0, 'end') showCount = 1 state = 'none' for show in self.showList: clip = '' clip += show try: ood = len(self.showData[show]['Out-of-Date']) if ood > 0: clip += ' (' + str(ood) + ')' state = 'ood' except: print('Error Getting Out-of-Date on ' + show) self.show_lb.insert(showCount, clip) if state != 'none': self.show_lb.itemconfig(showCount - 1, foreground="red") showCount += 1 state = 'none' #delete show from all logs. Remove from show names and from info def deleteShow(self): try: self.showList.remove(self.cur_show) del self.showData[self.cur_show] writeData(showLocation, self.showList) writeData(showInfoLocation, self.showData) except: print("No Show Specified. Cannot delete.") self.fillListBox()
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)
class App(object): def __init__(self, master): self.master = master self.network = network.ChatClient(self) self.conf = Configuration() conf_values = self.conf.get_values() self.create_window(master, conf_values) self.debug = False def config_window(self): conf_values = self.conf.ask_config(self.master) self.username.set(conf_values['username']) self.server.set(conf_values['server']) self.port.set(conf_values['port']) image = Image.open(conf_values['icon']).resize((40, 40), Image.ANTIALIAS) self.image = ImageTk.PhotoImage(image) self.lbl_image.configure(image=self.image) def open_connection(self): server = self.server.get() port = self.port.get() username = self.username.get() self.network.open_connection(server, int(port), username) self.disable_connect_button() self.disable_conf_button() self.disable_conf_info() self.enable_message_textbox() def close_connection(self): self.clear_user_list() self.enable_connect_button() self.enable_conf_button() self.enable_conf_info() self.disable_message_textbox() self.disable_features() def send_message(self, dummy=''): '''The dummy parameter ignores the parameter that automatically is added when the RETURN is pressed to send a message.''' username = self.network.username msg = self.txt_msg.get() self.txt_msg.delete(0, 'end') if not msg.strip(): return self.network.send_message(msg) self.write_message(username, msg, True) def write_message(self, sender, message, own=False): sender_format = 'username' if own else 'sender' self.bt_send.config(state=DISABLED) now = datetime.now() timestamp = now.strftime('%H:%M:%S') self.txt_chat.config(state=NORMAL) self.txt_chat.insert(END, ' ' + str(sender) + '\n', sender_format) self.txt_chat.insert(END, message + ' \n', 'message') self.txt_chat.insert(END, timestamp + ' \n', 'timestamp') self.txt_chat.insert(END, '\n\n', 'newline') self.txt_chat.see(END) self.txt_chat.config(state=DISABLED) self.txt_chat.focus() def write_own_file(self, username, file_name): now = datetime.now() format = now.strftime('%H:%M:%S') self.txt_chat.config(state=NORMAL) self.txt_chat.insert(END, ' ' + username + '\n', 'username') self.txt_chat.insert(END, 'File sent: ' + file_name + '\n', 'file') self.txt_chat.insert(END, format + ' \n', 'timestamp') self.txt_chat.insert(END, '\n\n', 'newline') self.txt_chat.see(END) self.txt_chat.config(state=DISABLED) def write_file(self, sender, file_name, code): now = datetime.now() format = now.strftime('%H:%M:%S') self.txt_chat.config(state=NORMAL) self.txt_chat.insert(END, ' ' + sender + '\n', 'sender') button = Button(self.txt_chat, text='Download', cursor='hand2') button.configure( command=(lambda b=button, c=code: self.ask_file(b, c))) button.config(relief=FLAT, bg='gray13', fg='white', borderwidth=1, highlightthickness=0) self.txt_chat.insert(END, ' ' + file_name + ' ', 'file') self.txt_chat.window_create(INSERT, align=CENTER, window=button) self.txt_chat.insert(END, ' \n', 'message') self.txt_chat.insert(END, format + ' \n', 'timestamp') self.txt_chat.insert(END, '\n\n', 'newline') self.txt_chat.see(END) self.txt_chat.config(state=DISABLED) def ask_file(self, button, code): self.network.ask_file(code) def file_received(self, data): with open(self.file_name, 'wb') as fh: fh.write(data) def enable_send(self, event): self.bt_send.config(state=ACTIVE) def disable_send(self, event): self.bt_send.config(state=DISABLED) def add_user_to_list(self, username): self.lb_users.insert(END, ' ' + username) def clear_user_list(self): self.lb_users.delete(0, 'end') def enable_features(self, features): color = 'green' if features['FILE'] else 'red' self.lbl_file['text'] = 'FILE' self.lbl_file.config(fg=color) if features['FILE']: self.bt_file.config(state=NORMAL) color = 'green' if features['CEN'] else 'red' self.lbl_cen['text'] = 'CEN' self.lbl_cen.config(fg=color) color = 'green' if features['NOP'] else 'red' self.lbl_nop['text'] = 'NOP' self.lbl_nop.config(fg=color) color = 'green' if features['TLS'] else 'red' self.lbl_tls['text'] = 'TLS' self.lbl_tls.config(fg=color) if features['TLS']: self.lbl_tls.bind('<Button-1>', self.request_tls) def request_tls(self, event): self.network.ask_tls() def send_file(self): file_name = filedialog.askopenfilename(title='Select file') if file_name: self.network.send_file(file_name) def sizeof_fmt(self, num): for unit in ['B', 'KiB', 'MiB', 'GiB']: if num < 1024.0: return "{:.2f} {}".format(num, unit) num /= 1024.0 return "{:.2f} {}" % (num, 'TiB') def get_file_confirmation(self, num_bytes): threshold = 2**20 # 1 MiB if num_bytes > threshold: size = self.sizeof_fmt(num_bytes) question = 'The file size is {}. Are you sure you want to ' question += 'download it?' confirmed = messagebox.askyesno('Download confirmation', question.format(size)) if num_bytes <= threshold or confirmed: file_name = filedialog.asksaveasfilename(title='Select file') if file_name: self.file_name = file_name return True return False def set_tls(self): self.lbl_tls.config(fg='yellow') self.lbl_tls.unbind('<Button-1>') def disable_features(self): self.lbl_file.config(bg='black', fg='black') self.lbl_cen.config(bg='black', fg='black') self.lbl_nop.config(bg='black', fg='black') self.lbl_tls.config(bg='black', fg='black') def set_nop(self): self.lbl_nop.config(fg='yellow') self.master.after(2000, self.unset_nop) def unset_nop(self): self.lbl_nop.config(fg='green') def print_debug(self, info): self.debug_info.set(info) if self.debug: self.lbl_debug.config(fg='green') self.master.after(2000, self.reset_debug_color) def print_debug_info(self, info): original = self.debug_info.get() self.debug_info.set(original + ' [' + info + ']') def print_info(self, info): self.info.set(info) self.master.after(2000, self.delete_info) def delete_info(self): self.info.set('') def reset_debug_color(self): self.lbl_debug.config(fg='white') def toggle_debug(self): if self.debug: self.lbl_debug.config(background='black', fg='black') else: self.lbl_debug.config(background='gray13', fg='white') self.debug = not self.debug def close(self): self.network.finish() def disable_conf_info(self): self.lbl_username.config(fg='green') self.txt_username.config(state=DISABLED) self.lbl_server.config(fg='green') self.txt_server.config(state=DISABLED) self.lbl_port.config(fg='green') self.txt_port.config(state=DISABLED) def enable_conf_info(self): self.lbl_username.config(fg='red') self.txt_username.config(state=NORMAL) self.lbl_server.config(fg='red') self.txt_server.config(state=NORMAL) self.lbl_port.config(fg='red') self.txt_port.config(state=NORMAL) def disable_connect_button(self): self.bt_connect.config(state=DISABLED) def enable_connect_button(self): self.bt_connect.config(state=NORMAL) def disable_conf_button(self): self.bt_config.config(state=DISABLED) def enable_conf_button(self): self.bt_config.config(state=NORMAL) def disable_message_textbox(self): self.txt_msg.config(state=DISABLED) def enable_message_textbox(self): self.txt_msg.config(state=NORMAL) def key_pressed(self, event): msg = self.txt_msg.get() # The pressed key is not appended to msg yet, # but can be found in event.char. # If a control key is pressed event.char is empty. # '\x08' is the backspace character. if len(msg) == 0 and event.char and event.char != '\x08': self.network.send_typing() def create_window(self, master, conf): master.geometry('700x500') frame = Frame(master) frame.config(bg='black') master.title('SZA-SAR') frame.pack(fill=BOTH, expand=True) fr_config = Frame(frame, bg='black', borderwidth=1, highlightbackground='white', relief=FLAT) fr_config.grid(row=0, column=0, padx=5, pady=1, sticky=W + E) image = Image.open(conf['icon']).resize((40, 40), Image.ANTIALIAS) self.image = ImageTk.PhotoImage(image) self.lbl_image = Label(fr_config, image=self.image) self.lbl_image.grid(row=0, column=0, rowspan=3, padx=5, pady=5, sticky=W) self.username = StringVar() self.server = StringVar() self.port = StringVar() self.lbl_username = Label(fr_config, text='User', bg='black', fg='red') self.lbl_username.grid(row=0, column=1, padx=5, pady=1, sticky=W) self.lbl_server = Label(fr_config, text='Server', bg='black', fg='red') self.lbl_server.grid(row=1, column=1, padx=5, pady=1, sticky=W) self.lbl_port = Label(fr_config, text='Port', bg='black', fg='red') self.lbl_port.grid(row=2, column=1, padx=5, pady=1, sticky=W) self.txt_username = Entry(fr_config, textvariable=self.username, bg='black', fg='red', width=10) self.txt_username.grid(row=0, column=2, padx=5, pady=1, sticky=W) self.txt_server = Entry(fr_config, textvariable=self.server, bg='black', fg='red', width=10) self.txt_server.grid(row=1, column=2, padx=5, pady=1, sticky=W) self.txt_port = Entry(fr_config, textvariable=self.port, bg='black', fg='red', width=10) self.txt_port.grid(row=2, column=2, padx=5, pady=1, sticky=W) self.username.set(conf['username']) self.server.set(conf['server']) self.port.set(conf['port']) frame.columnconfigure(1, weight=1) frame.rowconfigure(1, weight=1) fr_features = Frame(frame) fr_features.config(bg='black') fr_features.grid(row=4, column=0, columnspan=1, sticky=W + E, pady=2, padx=5) self.lbl_file = Label(fr_features, font='Helvetica 9 bold') self.lbl_cen = Label(fr_features, font='Helvetica 9 bold') self.lbl_nop = Label(fr_features, font='Helvetica 9 bold') self.lbl_tls = Label(fr_features, font='Helvetica 9 bold') self.lbl_file.grid(row=0, column=0, columnspan=1, sticky=W + E, pady=2, padx=5) self.lbl_file.config(bg='black', fg='white') self.lbl_cen.grid(row=0, column=1, columnspan=1, sticky=W + E, pady=2, padx=5) self.lbl_cen.config(bg='black', fg='white') self.lbl_nop.grid(row=0, column=2, columnspan=1, sticky=W + E, pady=2, padx=5) self.lbl_nop.config(bg='black', fg='white') self.lbl_tls.grid(row=0, column=3, columnspan=1, sticky=W + E, pady=2, padx=5) self.lbl_tls.config(bg='black', fg='white') fr_info = Frame(frame, bg='black', borderwidth=1, relief=FLAT) fr_info.grid(row=0, column=1, columnspan=2, padx=5, pady=1, sticky=W + E) self.info = StringVar() self.lbl_info = Label(fr_info, textvariable=self.info, width=80, anchor='w') self.lbl_info.grid(row=0, column=0, pady=2, padx=5) self.lbl_info.config(background='gray13', fg='white') self.debug_info = StringVar() self.lbl_debug = Label(fr_info, textvariable=self.debug_info, width=80, anchor='w') self.lbl_debug.grid(row=1, column=0, sticky=W + E, pady=2, padx=5) self.lbl_debug.config(background='black', fg='black') fr_buttons = Frame(frame, bg='black', borderwidth=1, background='black', relief=FLAT) fr_buttons.grid(row=0, column=3, columnspan=1, padx=5, pady=1, sticky=W + E) self.bt_connect = Button(fr_buttons, text='Connect', width=5, command=self.open_connection) self.bt_connect.grid(row=0, column=0, sticky=E, pady=2, padx=5) self.bt_connect.config(relief=FLAT, bg='gray13', fg='white', borderwidth=0, highlightthickness=0) self.bt_config = Button(fr_buttons, text='Conf', width=5, command=self.config_window) self.bt_config.grid(row=1, column=0, sticky=W + E, pady=2, padx=5) self.bt_config.config(relief=FLAT, bg='gray13', fg='white', borderwidth=0, highlightthickness=0) self.bt_debug = Button(fr_buttons, text='Debug', width=5, command=self.toggle_debug) self.bt_debug.grid(row=0, column=1, sticky=E, pady=2, padx=0) self.bt_debug.config(relief=FLAT, bg='gray13', activeforeground='white', fg='white', borderwidth=0, highlightthickness=0) self.bt_close = Button(fr_buttons, text='Close', width=5, command=self.close) self.bt_close.grid(row=1, column=1, sticky=W + E, pady=2, padx=0) self.bt_close.config(relief=FLAT, bg='gray13', fg='white', borderwidth=0, highlightthickness=0) self.lb_users = Listbox(frame) self.lb_users.grid(row=1, column=0, rowspan=3, pady=5, padx=5, sticky=S + N + E + W) self.lb_users.config(bg='gray18', borderwidth=1, highlightbackground='gray15', highlightthickness=1, fg='white', relief='solid') self.txt_chat = scrolledtext.ScrolledText(frame) self.txt_chat.grid(row=1, column=1, columnspan=3, rowspan=3, pady=5, padx=5, sticky=E + W + S + N) self.txt_chat.config(bg='gray18', borderwidth=0, highlightbackground='gray15', highlightthickness=1, relief='solid', padx=10, pady=5, font=('', 10)) self.txt_chat.vbar.config(troughcolor='black', bg='gray18') self.txt_chat.tag_config('sender', background='gray30', foreground='brown1', justify=RIGHT, font=('Bold', 10)) self.txt_chat.tag_config('username', background='gray30', foreground='olive drab', justify=LEFT, font=('Bold', 10)) self.txt_chat.tag_config('timestamp', background='gray30', foreground='black', justify=RIGHT, font=('Bold', 8)) self.txt_chat.tag_config('message', background='gray30', foreground='white', justify=RIGHT, font=('Bold', 10)) self.txt_chat.tag_config('file', background='red4', foreground='white', justify=RIGHT, font=('Bold', 10)) self.txt_chat.tag_config('newline', background='gray18', foreground='gray18', justify=RIGHT, font=('Bold', 4)) self.txt_chat.config(state=DISABLED) self.txt_msg = Entry(frame) self.txt_msg.grid(row=4, column=1, rowspan=1, columnspan=1, sticky=E + W + S + N, padx=5, pady=2) self.txt_msg.config(bg='gray13', fg='white', borderwidth=0, highlightthickness=0, insertbackground='white', state=DISABLED) self.txt_msg.bind('<Key>', self.key_pressed) self.txt_msg.bind('<FocusIn>', self.enable_send) self.txt_msg.bind('<FocusOut>', self.disable_send) self.txt_msg.bind('<Return>', self.send_message) fr_buttons_send = Frame(frame, bg='black', borderwidth=1, background='black', relief=FLAT) fr_buttons_send.grid(row=4, column=2, columnspan=2, padx=5, pady=1, sticky=W + E) self.bt_send = Button(fr_buttons_send, text='Send', width=5, command=self.send_message) self.bt_send.grid(row=0, column=0, sticky=E + W, pady=0, padx=5) self.bt_send.config(relief=FLAT, bg='gray13', fg='white', borderwidth=0, highlightthickness=0, state=DISABLED) self.bt_file = Button(fr_buttons_send, text='File', width=5, command=self.send_file) self.bt_file.grid(row=0, column=1, sticky=E + W, pady=0, padx=0) self.bt_file.config(relief=FLAT, bg='gray13', fg='white', borderwidth=0, highlightthickness=0, state=DISABLED) master.protocol('WM_DELETE_WINDOW', self.close)
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 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 BookManagerUi(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.db = dao('blist') #데이터베이스 관리 클래스 생성 def initUI(self): self.parent.title("Book Manager") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.columnconfigure(0, pad=3) self.columnconfigure(1, pad=3) self.columnconfigure(2, pad=3) self.rowconfigure(0, pad=3) self.rowconfigure(1, pad=3) self.rowconfigure(2, pad=3) self.rowconfigure(3, pad=3) self.rowconfigure(4, pad=3) self.rowconfigure(5, pad=3) self.rowconfigure(6, pad=3) self.input_bname='' self.input_aname='' self.input_price=0 self.delete='' lb_bookname = Label(self, text="bookname:") lb_bookname.grid(row=0, column =0 ,sticky=W, pady=4, padx=5) self.entry_bookname = Entry(self) self.entry_bookname.grid(row=0, column = 1 ) lb_author = Label(self, text="author:") lb_author.grid(row=0, column =2,sticky=W, pady=4, padx=5) self.entry_author = Entry(self) self.entry_author.grid(row=0, column = 3 ) lb_price = Label(self, text="price:") lb_price.grid(row=0, column =4 ,sticky=W, pady=4, padx=5) self.entry_price = Entry(self) self.entry_price.grid(row=0, column = 5 ,padx=15) abtn = Button(self, text="Add", command=lambda:self.clicked_add()) abtn.grid(row=0, column=6) sbtn = Button(self, text="Serach", command = lambda:self.clicked_search()) sbtn.grid(row=1, column=6, pady=4) dbtn = Button(self, text="Delete", command = lambda:self.clicked_delete()) dbtn.grid(row=2, column=6, pady=4) self.lb = Listbox(self) self.lb.grid(row=3,column = 0, columnspan = 6,rowspan= 4, sticky = E+W+S+N) self.lb.bind("<<ListboxSelect>>", self.onSelect) #삭제를 위한 select부분 def onSelect(self,val): sender = val.widget idx = sender.curselection() value = sender.get(idx) self.delete = value # 데이터 추가 버튼 def clicked_add(self): bname =self.entry_bookname.get() aname = self.entry_author.get() price = self.entry_price.get() self.lb.delete(0,END) # 입력받을 데이터가 모자란지 검사 if(len(bname) >0 and len(aname)>0 and len(price)>0 ): #가격에 문자를 입력했을 경우 처리 try: priceI = eval(price) except: self.lb.insert(END,"you input wrong price. it must be integer") #사용자가 입력한 내용중 중복된 책이름이 있을 경우(저자는 책이 여러가지일 수 있으니 제외) rec = self.db.excute_select(bname,'') if ( len(rec) >0): self.lb.insert(END,bname +" is already in the database") else: self.db.insert_data(bname,aname,priceI) # 모든 조건 만족시 데이터 입력 수행 r =self.db.excute_select(bname,aname) for rs in r: self.lb.insert(END,str(rs)) else: s = StringVar() self.entry_price.config(textvariable = s) self.lb.insert(END,"you have to input more values") #검색버튼 def clicked_search(self): bname =self.entry_bookname.get() aname = self.entry_author.get() self.lb.delete(0,END) #책이름 또는 저자이름 둘중 하나만입력 되어도 검색 가능하도록 if(len(bname)>0 or len(aname)>0 ): rec = self.db.excute_select(bname,aname) for r in rec: self.lb.insert(END,str(r)) else: self.lb.insert(END,"you have to input more values(bookname or author") #삭제 버튼 def clicked_delete(self): self.lb.delete(0,END) q = self.db.excute_delete(self.delete) self.lb.insert(END,q+' is delete from database')
class ListboxVidget(Vidget, Eventor): """ ListboxVidget contains a Listbox widget. It adds the following abilities: - Store items of any type, unlike Listbox widget that only stores texts. - Remember selected item even if the listbox widget lost focus. - Notify pre-change and post-change events. """ # Error raised when trying to change the listbox while a change is going on class CircularCallError(ValueError): pass # Error raised when trying to change the listbox while it is disabled class DisabledError(ValueError): pass # Event notified when the listbox's items are to be changed ITEMS_CHANGE_SOON = 'ITEMS_CHANGE_SOON' # Event notified when the listbox's items are changed ITEMS_CHANGE_DONE = 'ITEMS_CHANGE_DONE' # Event notified when the listbox's active item is to be changed ITEMCUR_CHANGE_SOON = 'ITEMCUR_CHANGE_SOON' # Event notified when the listbox's active item is changed ITEMCUR_CHANGE_DONE = 'ITEMCUR_CHANGE_DONE' # Events list EVENTS = ( ITEMS_CHANGE_SOON, ITEMS_CHANGE_DONE, ITEMCUR_CHANGE_SOON, ITEMCUR_CHANGE_DONE, ) def __init__( self, items=None, item_to_text=None, normal_bg='', normal_fg='', active_bg='sky blue', active_fg='white', selected_bg='steel blue', selected_fg='white', master=None, ): """ Initialize object. @param items: Items list. @param item_to_text: Item-to-text function. Default is `str`. @param normal_bg: Unselected item background color. @param normal_fg: Unselected item foreground color. @param active_bg: Active item background color. `Active` means the item is selected (in general meaning) but the listbox has no focus. @param active_fg: Active item foreground color. `Active` means the item is selected (in general meaning) but the listbox has no focus. @param selected_bg: Selected item background color. `Selected` means the item is selected (in general meaning) and the listbox has focus. @param selected_fg: Selected item foreground color. `Selected` means the item is selected (in general meaning) and the listbox has focus. @param master: Master widget. @return: None. """ # Initialize Vidget. # Create main frame widget. Vidget.__init__( self, master=master, ) # Initialize Eventor Eventor.__init__(self) # If items list is given if items is not None: # If items list is not list if not isinstance(items, list): # Raise error raise TypeError(items) # If items list is list. # If items list is not given, or items list is given and is list # Items list self._items = items if items is not None else [] # Item-to-text function. Default is `str`. self._item_to_text = item_to_text if item_to_text is not None else str # Unselected item background color self._normal_fg = normal_fg # Unselected item foreground color self._normal_bg = normal_bg # Active item background color self._active_fg = active_fg # Active item foreground color self._active_bg = active_bg # Selected item background color self._selected_fg = selected_fg # Selected item foreground color self._selected_bg = selected_bg # Whether the listbox is changing self._is_changing = False # Active index. `-1` means void, i.e. no item is active. self._indexcur = -1 # Whether active index is being reset to same value self._is_resetting = False # Create listbox widget self._listbox = Listbox( master=self.widget(), relief='groove', activestyle='none', highlightthickness=0, # Active index cache only supports single-selection mode for now. # See 2N6OR. selectmode='single', ) # Set the listbox widget as config target self.config_target_set(self._listbox) # Create x-axis scrollbar self._scrollbar_xview = _HiddenScrollbar( self.widget(), orient=HORIZONTAL, ) # Create y-axis scrollbar self._scrollbar_yview = _HiddenScrollbar( self.widget(), orient=VERTICAL, ) # Mount scrollbars self._listbox.config(xscrollcommand=self._scrollbar_xview.set) self._listbox.config(yscrollcommand=self._scrollbar_yview.set) self._scrollbar_xview.config(command=self._listbox.xview) self._scrollbar_yview.config(command=self._listbox.yview) # Bind single-click event handler self._listbox.bind('<Button-1>', self._on_single_click) # Bind double-click event handler self._listbox.bind('<Double-Button-1>', self._on_double_click) # Update listbox widget self._listbox_widget_update(keep_active=False) # Update widget self._widget_update() def _widget_update(self): """ Update widget. @return: None. """ # Row 0 for listbox and y-axis scrollbar self.widget().rowconfigure(0, weight=1) # Row 1 for x-axis scrollbar self.widget().rowconfigure(1, weight=0) # Column 0 for listbox and x-axis scrollbar self.widget().columnconfigure(0, weight=1) # Column 1 for y-axis scrollbar self.widget().columnconfigure(1, weight=0) # Lay out listbox self._listbox.grid(row=0, column=0, sticky='NSEW') # Lay out x-axis scrollbar self._scrollbar_xview.grid(row=1, column=0, sticky='EW') # Lay out y-axis scrollbar self._scrollbar_yview.grid(row=0, column=1, sticky='NS') def is_enabled(self): """ Test whether the listbox is enabled. @return: Boolean. """ # Return whether the listbox is enabled return self._listbox.config('state')[4] != DISABLED def is_changing(self): """ Test whether the listbox is changing. @return: Boolean. """ # Return whether the listbox is changing return self._is_changing def is_resetting(self): """ Test whether the listbox is setting active index to the same value. @return: Boolean. """ # Return whether the listbox is setting active index to the same value return self._is_resetting def size(self): """ Get number of items. @return: Number of items. """ # Return number of items return len(self._items) def items(self): """ Get items list. Notice do not change the list outside. @return: Items list. """ # Return items list return self._items def items_set( self, items, notify=True, keep_active=False, ): """ Set items list. Notice do not change the list outside. @param items: Items list. @param notify: Whether notify pre-change and post-change events. @param keep_active: Whether keep or clear active index. @return: None. """ # If the items is not list if not isinstance(items, list): # Raise error raise TypeError(items) # If the items is list. # If the listbox is disabled if not self.is_enabled(): # Raise error raise ListboxVidget.DisabledError() # If the listbox is not disabled. # If the listbox is changing if self._is_changing: # Raise error raise ListboxVidget.CircularCallError() # If the listbox is not changing. # Set changing flag on self._is_changing = True # If notify events if notify: # Notify pre-change event self.handler_notify(self.ITEMS_CHANGE_SOON) # Store the new items self._items = items # Update listbox widget self._listbox_widget_update( keep_active=keep_active ) # If notify events if notify: # Notify post-change event self.handler_notify(self.ITEMS_CHANGE_DONE) # Set changing flag off self._is_changing = False def index_is_valid(self, index): """ Test whether given index is valid. Notice -1 is not valid. @param index: Index to test. @return: Boolean. """ # Test whether given index is valid return 0 <= index and index < self.size() def index_is_valid_or_void(self, index): """ Test whether given index is valid or is -1. @param index: Index to test. @return: Boolean. """ # Test whether given index is valid or is -1 return index == -1 or self.index_is_valid(index) def index_first(self): """ Get the first item's index. @return: First item's index, or -1 if the listbox is empty. """ # Return the first item's index return 0 if self.size() > 0 else -1 def index_last(self): """ Get the last item's index. @return: Last item's index, or -1 if the listbox is empty. """ # Return the last item's index return self.size() - 1 def indexcur(self, internal=False, raise_error=False): """ Get the active index. @param internal: See 2N6OR. @return: The active index. If no active active, either return -1, or raise IndexError if `raise_error` is True. """ # Get active indexes indexcurs = self._indexcurs(internal=internal) # If have active indexes if indexcurs: # Return the first active index return indexcurs[0] # If no active indexes else: # If raise error if raise_error: # Raise error raise IndexError(-1) # If not raise error else: # Return -1 return -1 def _indexcurs(self, internal=False): """ Get active indexes list. 2N6OR @param internal: Whether use listbox widget's selected indexes, instead of cached active index. Notice listbox widget has no selected indexes if it has no focus. Notice using cached active index only supports single-selection mode, which means the result list has at most one index. @return: Active indexes list. """ # If use listbox widget's selected indexes if internal: # Return listbox widget's selected indexes list return [int(x) for x in self._listbox.curselection()] # If not use listbox widget's selected indexes else: # If cached active index is valid if self.index_is_valid(self._indexcur): # Return a list with the cached active index return [self._indexcur] # If cached active index is not valid else: # Return empty list return [] def indexcur_set( self, index, focus=False, notify=True, notify_arg=None, ): """ Set active index. @param index: The index to set. @param focus: Whether set focus on the listbox widget. @param notify: Whether notify pre-change and post-change events. @param notify_arg: Event argument. @return: None. """ # If the index is not valid or -1 if not self.index_is_valid_or_void(index): # Raise error raise IndexError(index) # If the index is valid or is -1. # If the listbox is not enabled if not self.is_enabled(): # Raise error raise ListboxVidget.DisabledError() # If the listbox is enabled. # If the listbox is changing if self._is_changing: # Raise error raise ListboxVidget.CircularCallError() # If the listbox is not changing. # Set changing flag on self._is_changing = True # Get old active index old_indexcur = self._indexcur # Set resetting flag on if new and old indexes are equal self._is_resetting = (index == old_indexcur) # If notify events if notify: # Notify pre-change event self.handler_notify(self.ITEMCUR_CHANGE_SOON, notify_arg) # If old active index is valid if self.index_is_valid(old_indexcur): # Set old active item's background color to normal color self._listbox.itemconfig(old_indexcur, background=self._normal_bg) # Set old active item's foreground color to normal color self._listbox.itemconfig(old_indexcur, foreground=self._normal_fg) # Cache new active index self._indexcur = index # Clear listbox widget's selection self._listbox.selection_clear(0, END) # Set listbox widget's selection self._listbox.selection_set(index) # Set listbox widget's activated index self._listbox.activate(index) # If new active index is valid if index != -1: # Set new active item's background color to active color self._listbox.itemconfig(index, background=self._active_bg) # Set new active item's foreground color to active color self._listbox.itemconfig(index, foreground=self._active_fg) # If set focus if focus: # Set focus on the listbox widget self._listbox.focus_set() # If new active index is valid if index != -1: # Make the active item visible self._listbox.see(index) # If notify events if notify: # Notify post-change event self.handler_notify(self.ITEMCUR_CHANGE_DONE, notify_arg) # Set resetting flag off self._is_resetting = False # Set changing flag off self._is_changing = False def indexcur_set_by_event( self, event, focus=False, notify=True, notify_arg=None, ): """ Set active index using a Tkinter event object that contains coordinates of the active item. @param event: Tkinter event object. @param focus: Whether set focus on the listbox widget. @param notify: Whether notify pre-change and post-change events. @param notify_arg: Event argument. @return: None. """ # Get the event's y co-ordinate's nearest listbox item index index = self._listbox.nearest(event.y) # If the index is not valid if not self.index_is_valid_or_void(index): # Ignore the event return # If the index is valid else: # Set the index as active index self.indexcur_set( index=index, focus=focus, notify=notify, notify_arg=notify_arg, ) def item(self, index): """ Get item at given index. @return: Item at given index, or IndexError if the index is not valid. """ return self.items()[index] def itemcur(self, internal=False, raise_error=False): """ Get the active item. @param internal: See 2N6OR. @param raise_error: Whether raise error if no active item. @return: The active item. If no active item, if `raise_error` is True, raise IndexError, otherwise return None. """ # Get active index. # May raise IndexError if `raise_error` is True. indexcur = self.indexcur( internal=internal, raise_error=raise_error, ) # If no active index if indexcur == -1: # Return None return None # If have active index else: # Return the active item return self.items()[indexcur] def item_insert( self, item, index=None, notify=True, keep_active=True, ): """ Insert item at given index. @param item: Item to insert. @param index: Index to insert. `None` means active index, and if no active index, insert at the end. @param notify: Whether notify pre-change and post-change events. @param keep_active: Whether keep or clear active index. @return: None. """ # If notify events if notify: # Notify pre-change events self.handler_notify(self.ITEMCUR_CHANGE_SOON) self.handler_notify(self.ITEMS_CHANGE_SOON) # Get old active index active_index = self.indexcur() # If the index is None, # it means use active index. if index is None: # Use active index. # `-1` works and means appending. index = active_index # Insert the item to the items list self._items.insert(index, item) # If old active index is valid if active_index != -1: # If old active index is GE the inserted index if active_index >= index: # Shift active index by one active_index += 1 # If old active index is not GE the inserted index, use it as-is. # Set new active index self.indexcur_set(index=active_index, notify=False) # Update listbox widget self._listbox_widget_update( keep_active=keep_active ) # If notify events if notify: # Notify post-change events self.handler_notify(self.ITEMS_CHANGE_DONE) self.handler_notify(self.ITEMCUR_CHANGE_DONE) def item_remove( self, index, notify=True, keep_active=True, ): """ Remove item at given index. @param index: Index to remove. @param notify: Whether notify pre-change and post-change events. @param keep_active: Whether keep or clear active index. @return: None. """ # If the index is not valid if not self.index_is_valid(index): # Raise error raise ValueError(index) # If the index is valid. # If notify events if notify: # Notify pre-change events self.handler_notify(self.ITEMCUR_CHANGE_SOON) self.handler_notify(self.ITEMS_CHANGE_SOON) # Get old active index active_index = self.indexcur() # Remove item at the index del self._items[index] # If old active index is valid if active_index != -1: # Get the last index index_last = self.index_last() # If old active index is GT the last index if active_index > index_last: # Use the last index as new active index active_index = index_last # If old active index is not GT the last index, use it as-is. # Set new active index self.indexcur_set(index=active_index, notify=False) # Update listbox widget self._listbox_widget_update( keep_active=keep_active ) # If notify events if notify: # Notify post-change events self.handler_notify(self.ITEMS_CHANGE_DONE) self.handler_notify(self.ITEMCUR_CHANGE_DONE) def handler_add( self, event, handler, need_arg=False, ): """ Add event handler for an event. If the event is ListboxVidget event, add the event handler to Eventor. If the event is not ListboxVidget event, add the event handler to listbox widget. Notice this method overrides `Eventor.handler_add` in order to add non-ListboxVidget event handler to listbox widget. @param event: Event name. @param handler: Event handler. @param need_arg: Whether the event handler needs event argument. @return: None. """ # If the event is ListboxVidget event if event in self.EVENTS: # Add the event handler to Eventor return Eventor.handler_add( self, event=event, handler=handler, need_arg=need_arg, ) # If the event is not ListboxVidget event, # it is assumed to be Tkinter widget event. else: # Add the event handler to listbox widget return self.bind( event=event, handler=handler, ) def bind( self, event, handler, ): """ Add event handler to listbox widget. ListboxVidget internally uses `<Button-1>` and `<Double-Button-1>` to capture active index changes. So if the given event is `<Button-1>` or `<Double-Button-1>`, the given handler will be wrapped. @param event: Event name. @param handler: Event handler. @return: None. """ # If the event is not `<Button-1>` or `<Double-Button-1>` if event not in ['<Button-1>', '<Double-Button-1>']: # Add the event handler to listbox widget self._listbox.bind(event, handler) # If the event is `<Button-1>` or `<Double-Button-1>` else: # Create event handler wrapper def handler_wrapper(e): """ Event handler wrapper that sets new active index and then calls the wrapped event handler. Setting new active index is needed because when this handler is called by Tkinter, the active index of the listbox is still old. @param e: Tkinter event object. @return: None. """ # Set new active index self.indexcur_set_by_event(e, notify=True) # Call the wrapped event handler handler(e) # Add the event handler wrapper to the listbox widget self._listbox.bind(event, handler_wrapper) def _on_single_click(self, event): """ `<Button-1>` event handler that updates active index. @param event: Tkinter event object. @return: None. """ # Updates active index self.indexcur_set_by_event(event, notify=True) def _on_double_click(self, event): """ `<Double-Button-1>` event handler that updates active index. @param event: Tkinter event object. @return: None. """ # Updates active index self.indexcur_set_by_event(event, notify=True) def _listbox_widget_update( self, keep_active, ): """ Update listbox widget's items and selection. @param keep_active: Whether keep or clear active index. @return: None. """ # Remove old items from listbox widget self._listbox.delete(0, END) # Insert new items into listbox widget. # For each ListboxVidget items. for index, item in enumerate(self.items()): # Get item text item_text = self._item_to_text(item) # Insert the item text into listbox widget self._listbox.insert(index, item_text) # Set the item's normal background color self._listbox.itemconfig(index, background=self._normal_bg) # Set the item's normal foreground color self._listbox.itemconfig(index, foreground=self._normal_fg) # Set the item's selected background color self._listbox.itemconfig(index, selectbackground=self._selected_bg) # Set the item's selected foreground color self._listbox.itemconfig(index, selectforeground=self._selected_fg) # If keep active index if keep_active: # Use old active index indexcur = self._indexcur # If not keep active index else: # Set active index to -1 indexcur = self._indexcur = -1 # Clear old selection self._listbox.selection_clear(0, END) # Set new selection. # `-1` works. self._listbox.selection_set(indexcur) # Set new active index. # `-1` works. self._listbox.activate(indexcur) # If new active index is valid if indexcur != -1: # Set active background color self._listbox.itemconfig(indexcur, background=self._active_bg) # Set active foreground color self._listbox.itemconfig(indexcur, foreground=self._active_fg) # Make the active item visible self._listbox.see(indexcur)
get_number_of_likes.insert("end", '799') ask_number_of_likes.grid(row=4, column=0) get_number_of_likes.grid(row=4, column=1) save_seeder_button = Button(main_window_of_gui, text="Ajouter\n compte-source", width=15, height=3, command=save_seeder_account) save_seeder_button.grid(row=3, column=2, rowspan=2) like_button = Button(main_window_of_gui, text="Commencer !", width=15, height=3, command=like_gathered_users) like_button.grid(row=6, column=2) text_box = Listbox(main_window_of_gui, height=8) text_box.grid(column=0, row=7, columnspan=6, sticky=(N, W, E, S)) main_window_of_gui.grid_columnconfigure(0, weight=1) main_window_of_gui.grid_rowconfigure(7, weight=1) my_scrollbar = Scrollbar(main_window_of_gui, orient=VERTICAL, command=text_box.yview) my_scrollbar.grid(column=5, row=7, sticky=(N, S)) text_box['yscrollcommand'] = my_scrollbar.set main_window_of_gui.mainloop() driver.close()
class CopyToMoveTo: """ Minimalist file manager intended to be used independently or alongside Windows Explorer """ def __init__(self, root): """ Setup window geometry, init settings, define widgets + layout """ self.master = root self.master.title("CopyTo-MoveTo") self.master.iconbitmap(f"{dirname(__file__)}/icon.ico") if system() != "Windows": self.master.withdraw() messagebox.showwarning( "Incompatible platform", "CopyTo-MoveTo currently supports Windows platforms only.") raise SystemExit #Settings: self.settings_show_hidden = BooleanVar() self.settings_include_files = BooleanVar(value=True) self.settings_ask_overwrite = BooleanVar() self.settings_ask_overwrite.trace("w", self.settings_exclusives) self.settings_rename_dupes = BooleanVar(value=True) self.settings_rename_dupes.trace("w", self.settings_exclusives) self.settings_multiselect = BooleanVar(value=True) self.settings_select_dirs = BooleanVar(value=True) self.settings_select_dirs.trace("w", self.settings_mutuals) self.settings_select_files = BooleanVar(value=True) self.settings_select_files.trace("w", self.settings_mutuals) self.settings_geometry = None self.appdata_dir = getenv("APPDATA") + "/CopyTo-MoveTo" self.appdata_path = self.appdata_dir + "/settings.json" self.settings = self.init_settings() if self.settings: self.settings_geometry = self.settings["geometry"] self.settings_show_hidden.set(self.settings["show_hidden"]) self.settings_include_files.set(self.settings["include_files"]) self.settings_ask_overwrite.set(self.settings["ask_overwrite"]) self.settings_rename_dupes.set(self.settings["rename_dupes"]) self.settings_multiselect.set(self.settings["multiselect"]) self.settings_select_dirs.set(self.settings["select_dirs"]) self.settings_select_files.set(self.settings["select_files"]) self.dialog_showing = BooleanVar() self.help_showing = BooleanVar() self.about_showing = BooleanVar() self.master.protocol("WM_DELETE_WINDOW", self.master_close) self.master.bind("<Control-w>", self.master_close) #Geometry: self.master.minsize(width=450, height=200) if self.settings_geometry: self.master.geometry(self.settings_geometry) self.master.update() else: self.master.geometry("600x400") self.master.update_idletasks() (width_offset, height_offset) = Ufd.get_offset(self.master) self.master.geometry(f"+{width_offset}+{height_offset}") self.master.update_idletasks() # Menu: self.main_menu = Menu(self.master) self.master.config(menu=self.main_menu) self.file_menu = Menu(self.main_menu, tearoff=0) self.settings_menu = Menu(self.main_menu, tearoff=0) self.main_menu.add_cascade(label="File", menu=self.file_menu) self.main_menu.add_cascade(label="Settings", menu=self.settings_menu) self.file_menu.add_command(label="Open Source(s)", accelerator="Ctrl+O", command=lambda: self.show_ufd(source=True)) self.master.bind("<Control-o>", lambda event: self.show_ufd(source=True)) self.file_menu.add_command(label="Open Destination(s)", accelerator="Ctrl+K+O", command=lambda: self.show_ufd(source=False)) self.master.bind("<Control-k>o", lambda event: self.show_ufd(source=False)) self.file_menu.add_separator() self.file_menu.add_command(label="Help / Commands", command=self.show_help) self.file_menu.add_command(label="About", command=self.show_about) #Settings menu: self.settings_menu.add_checkbutton(label="Show Hidden Files & Folders", variable=self.settings_show_hidden, onvalue=True, offvalue=False) self.settings_menu.add_checkbutton( label="Include Files in Tree", variable=self.settings_include_files, onvalue=True, offvalue=False) self.settings_menu.add_separator() self.settings_menu.add_checkbutton( label="Ask Overwrite", variable=self.settings_ask_overwrite, onvalue=True, offvalue=False) self.settings_menu.add_checkbutton(label="Rename Duplicates", variable=self.settings_rename_dupes, onvalue=True, offvalue=False) self.settings_menu.add_separator() self.settings_menu.add_checkbutton(label="Multiselect", variable=self.settings_multiselect, onvalue=True, offvalue=False) self.settings_menu.add_checkbutton(label="Select Folders", variable=self.settings_select_dirs, onvalue=True, offvalue=False) self.settings_menu.add_checkbutton(label="Select Files", variable=self.settings_select_files, onvalue=True, offvalue=False) self.main_menu.add_separator() #Menu commands: self.main_menu.add_command(label="Swap Selected", command=self.swap_selected) self.master.bind("<Control-s>", lambda event: self.swap_selected()) self.main_menu.add_command(label="Clear Selected", command=self.clear_selected) self.master.bind("<Control-x>", lambda event: self.clear_selected()) self.main_menu.add_command(label="Clear All", command=self.clear_all) self.master.bind("<Control-Shift-X>", lambda event: self.clear_all()) self.main_menu.add_separator() self.main_menu.add_command(label="COPY", command=lambda: self._submit(copy=True)) self.master.bind("<Control-Shift-Return>", lambda event: self._submit(copy=True)) self.main_menu.add_command(label="MOVE", command=lambda: self._submit(copy=False)) self.master.bind("<Control-Return>", lambda event: self._submit(copy=False)) # Body: self.paneview = PanedWindow(self.master, sashwidth=7, bg="#cccccc", bd=0, orient="vertical") self.top_pane = PanedWindow(self.paneview) self.bottom_pane = PanedWindow(self.paneview) self.paneview.add(self.top_pane) self.paneview.add(self.bottom_pane) self.label_source = Label(self.top_pane, text="Source(s):") self.label_dest = Label(self.bottom_pane, text="Destination(s):") self.y_scrollbar_source = Scrollbar(self.top_pane, orient="vertical") self.x_scrollbar_source = Scrollbar(self.top_pane, orient="horizontal") self.y_scrollbar_dest = Scrollbar(self.bottom_pane, orient="vertical") self.x_scrollbar_dest = Scrollbar(self.bottom_pane, orient="horizontal") self.list_box_source = Listbox( self.top_pane, selectmode="extended", yscrollcommand=self.y_scrollbar_source.set, xscrollcommand=self.x_scrollbar_source.set) self.list_box_dest = Listbox(self.bottom_pane, selectmode="extended", yscrollcommand=self.y_scrollbar_dest.set, xscrollcommand=self.x_scrollbar_dest.set) self.x_scrollbar_source.config(command=self.list_box_source.xview) self.y_scrollbar_source.config(command=self.list_box_source.yview) self.x_scrollbar_dest.config(command=self.list_box_dest.xview) self.y_scrollbar_dest.config(command=self.list_box_dest.yview) # Layout: self.master.rowconfigure(0, weight=1) self.master.columnconfigure(0, weight=1) self.top_pane.rowconfigure(1, weight=1) self.top_pane.columnconfigure(0, weight=1) self.bottom_pane.rowconfigure(1, weight=1) self.bottom_pane.columnconfigure(0, weight=1) self.paneview.paneconfigure(self.top_pane, minsize=100) self.paneview.paneconfigure(self.bottom_pane, minsize=100) self.paneview.grid(row=0, column=0, sticky="nsew") self.label_source.grid(row=0, column=0, sticky="w") self.list_box_source.grid(row=1, column=0, sticky="nsew") self.y_scrollbar_source.grid(row=1, column=1, sticky="ns") self.x_scrollbar_source.grid(row=2, column=0, sticky="ew") self.label_dest.grid(row=0, column=0, sticky="w", columnspan=2) self.list_box_dest.grid(row=1, column=0, sticky="nsew") self.y_scrollbar_dest.grid(row=1, column=1, sticky="ns") self.x_scrollbar_dest.grid(row=2, column=0, sticky="ew") def __str__(self): """Return own address""" return f"CopyTo-MoveTo @ {hex(id(self))}" def init_settings(self): """Called on startup, loads, parses, and returns json settings.""" if exists(self.appdata_path): with open(self.appdata_path, "r") as settings_file: settings_json = settings_file.read() settings = loads(settings_json) return settings else: return None def settings_exclusives(self, *args): """ Callback assigned to settings that are mutually exclusive, to prevent logical/runtime errors or unexpected behavior. """ if args[0] == "PY_VAR2": if self.settings_ask_overwrite.get() == 1: self.settings_rename_dupes.set(0) return elif args[0] == "PY_VAR3": if self.settings_rename_dupes.get() == 1: self.settings_ask_overwrite.set(0) return def settings_mutuals(self, *args): """ Prevent select folders & select files from being disabled concurrently If both are unselected, reselect the one we didn't just deselect on. """ if self.settings_select_dirs.get() == 0 \ and self.settings_select_files.get() == 0: if args[0] == "PY_VAR5": self.settings_select_files.set(1) elif args[0] == "PY_VAR6": self.settings_select_dirs.set(1) def master_close(self, event=None): """ Similar to utils.toplevel_close(). writes settings to the disk as json. """ settings = { "geometry": self.master.geometry(), "show_hidden": self.settings_show_hidden.get(), "include_files": self.settings_include_files.get(), "ask_overwrite": self.settings_ask_overwrite.get(), "rename_dupes": self.settings_rename_dupes.get(), "multiselect": self.settings_multiselect.get(), "select_dirs": self.settings_select_dirs.get(), "select_files": self.settings_select_files.get(), } settings_json = dumps(settings) if not exists(self.appdata_dir): mkdir(self.appdata_dir) with open(self.appdata_path, "w+") as settings_file: settings_file.write(settings_json) if self.dialog_showing.get() == 1: self.ufd.cancel() self.master.destroy() def toplevel_close(self, dialog, boolean): """ This callback flips the value for a given toplevel_showing boolean to false, before disposing of the toplevel. """ boolean.set(0) dialog.destroy() def swap_selected(self): """Swap list entries between source & destination""" source_selection = list(self.list_box_source.curselection()) dest_selection = list(self.list_box_dest.curselection()) for i in reversed(source_selection): item = self.list_box_source.get(i) self.list_box_source.delete(i) self.list_box_dest.insert("0", item) for i in reversed(dest_selection): item = self.list_box_dest.get(i) self.list_box_dest.delete(i) self.list_box_source.insert("0", item) def clear_selected(self): """Removes selected (highlighted) item(s) from a given listbox""" source_selection = list(self.list_box_source.curselection()) dest_selection = list(self.list_box_dest.curselection()) if source_selection: for i in reversed(source_selection): self.list_box_source.delete(i) self.list_box_source.selection_set(source_selection[0]) if dest_selection: for i in reversed(dest_selection): self.list_box_dest.delete(i) self.list_box_dest.selection_set(dest_selection[0]) def clear_all(self): """Clears both listboxes in the main UI, resetting the form.""" self.list_box_source.delete(0, "end") self.list_box_dest.delete(0, "end") def handled(fn): """Filesystem operations are wrapped here for error handling""" @wraps(fn) def inner(self, *args, **kwargs): try: fn(self, *args, **kwargs) return True except (PermissionError, FileNotFoundError) as err: self.skipped_err.append(f"{err.args[1]}:\n" + (" => ".join(args))) return False return inner @handled def _copy(self, path, destination): """Wrapper for shutil.copy2() || shutil.copytree()""" if isfile(path): copy2(path, destination) else: copytree(path, destination) @handled def _move(self, path, destination): """Wrapper for shutil.move()""" move(path, destination) @handled def _delete(self, path): """Wrapper for os.remove() || shutil.rmtree()""" if isfile(path): remove(path) elif isdir(path): rmtree(path) def disabled_ui(fn): """Menubar is disabled during operations""" @wraps(fn) def inner(self, *args, **kwargs): self.main_menu.entryconfig("File", state="disabled") self.main_menu.entryconfig("Settings", state="disabled") self.main_menu.entryconfig("Clear Selected", state="disabled") self.main_menu.entryconfig("Clear All", state="disabled") self.main_menu.entryconfig("COPY", state="disabled") self.main_menu.entryconfig("MOVE", state="disabled") fn(self, *args, **kwargs) self.main_menu.entryconfig("File", state="normal") self.main_menu.entryconfig("Settings", state="normal") self.main_menu.entryconfig("Clear Selected", state="normal") self.main_menu.entryconfig("Clear All", state="normal") self.main_menu.entryconfig("COPY", state="normal") self.main_menu.entryconfig("MOVE", state="normal") return inner def _submit(self, copy): """Thread/wrapper for submit() so we don't block the UI during operations""" self.thread = Thread(target=self.submit, args=(copy, ), daemon=True) self.thread.start() @disabled_ui def submit(self, copy): """ Move or copy each item in the origin list to the path in the destination list. Supports no more than one destination directory where copy == False. Ask Overwrite and Rename Dupes will alter the way we handle existing data standing in the way. By default, duplicates are renamed with an index. A messagebox can complain to the user if shutil raises a PermissionError, and the operation is skipped. """ if (self.list_box_dest.size() > 1) and not copy: messagebox.showwarning( "Invalid Operation", "Move operation only supports a single destination directory.") return sources = self.list_box_source.get(0, "end") destinations = self.list_box_dest.get(0, "end") self.skipped_err = [] for j, destination in enumerate(destinations): if isfile(destination): self.skipped_err.append(f"Invalid destination: {destination}") continue for i, source in enumerate(sources): self.progress(i, j) (_, filename) = split(source) future_destination = join(destination + sep, filename) if exists(future_destination): if not self.settings_ask_overwrite.get() \ and not self.settings_rename_dupes.get(): if not self._delete(future_destination): continue if self.settings_ask_overwrite.get(): if self.ask_overwrite(future_destination): if not self._delete(future_destination): continue else: continue if self.settings_rename_dupes.get(): future_destination = self.name_dupe(future_destination) if copy: if not self._copy(source, future_destination): continue else: if not self._move(source, future_destination): continue self.list_box_source.delete(0, "end") self.list_box_dest.delete(0, "end") if self.skipped_err: messagebox.showerror(title="Error(s)", message="\n\n".join(self.skipped_err)) @staticmethod def name_dupe(path): """ Renames the file or directory until it doesn't exist in the destination with that name anymore, by appending the filename with an index wrapped in parenthesis. (Windows platforms) file.txt => file (1).txt => file (2).txt """ if system() != "Windows": raise OSError("For use with Windows filesystems.") path_ = path (root, filename) = split(path_) if isdir(path_): title = filename ext = None else: (title, ext) = splitext(filename) filecount = 0 while exists(path_): filecount += 1 new_title = title + " (" + str(filecount) + ")" if ext: new_title = new_title + ext path_ = join(root, new_title) return path_ def ask_overwrite(self, future_destination): """Messagebox result returned as truth value""" return messagebox.askyesno( title="Path Conflict", message=f"Overwrite:\n\n{future_destination}?\n\n" \ f"YES - Overwrite\nNO - Skip" ) def progress(self, i, j): """ Visualize operands in GUI during operations i = current source operand index j = current destination operand index """ for y, _ in enumerate(self.list_box_source.get(0, "end")): if y != i: self.list_box_source.itemconfigure(y, bg="#FFFFFF", fg="#000000") else: self.list_box_source.itemconfigure(y, bg="#cccccc", fg="#000000") for x, _ in enumerate(self.list_box_dest.get(0, "end")): if x != j: self.list_box_dest.itemconfigure(x, bg="#FFFFFF", fg="#000000") else: self.list_box_dest.itemconfigure(x, bg="#cccccc", fg="#000000") self.master.update() #Toplevels: def show_about(self): """ Displays a static dialog that doesn't allow additional instances of itself to be created while showing. """ if self.about_showing.get() == 0: self.about_showing.set(1) try: with open(f"{dirname(__file__)}/about.txt", "r") as aboutfile: about_info = aboutfile.read() except FileNotFoundError: messagebox.showerror("Error", "File not found") self.about_showing.set(0) return else: self.about = Toplevel() self.about.title("About") self.about.iconbitmap(f"{dirname(__file__)}/icon.ico") self.about.geometry("600x400") self.about.resizable(0, 0) self.about.update_idletasks() (width_offset, height_offset) = Ufd.get_offset(self.about) self.about.geometry(f"+{width_offset-75}+{height_offset-75}") self.about.update_idletasks() self.about_message = Label( self.about, text=about_info, justify="left", wraplength=(self.about.winfo_width() - 25)) self.about_message.grid(sticky="nsew") self.about.protocol( "WM_DELETE_WINDOW", lambda: self.toplevel_close( self.about, self.about_showing)) def show_help(self): """ Displays a scrollable dialog that doesn't allow additional instances of itself to be created while showing. """ if self.help_showing.get() == 0: self.help_showing.set(1) try: with open(f"{dirname(__file__)}/help.txt", "r") as helpfile: help_info = helpfile.read() except FileNotFoundError: messagebox.showerror("Error", "File not found") self.help_showing.set(0) return else: self.help_window = Toplevel() self.help_window.title("Help") self.help_window.iconbitmap(f"{dirname(__file__)}/icon.ico") self.help_window.geometry("500x300") self.help_window.update_idletasks() (width_offset, height_offset) = Ufd.get_offset(self.help_window) self.help_window.geometry( f"+{width_offset+75}+{height_offset-75}") self.help_window.update_idletasks() self.message_y_scrollbar = Scrollbar(self.help_window, orient="vertical") self.help_text = Text( self.help_window, wrap="word", yscrollcommand=self.message_y_scrollbar.set) self.help_window.rowconfigure(0, weight=1) self.help_window.columnconfigure(0, weight=1) self.help_text.grid(row=0, column=0, sticky="nsew") self.message_y_scrollbar.grid(row=0, column=1, sticky="nse") self.message_y_scrollbar.config(command=self.help_text.yview) self.help_text.insert("end", help_info) self.help_text.config(state="disabled") self.help_window.protocol( "WM_DELETE_WINDOW", lambda: self.toplevel_close( self.help_window, self.help_showing)) def show_ufd(self, source=True): """ Display Ufd w/ appropriate kwargs => Populate GUI w/ result""" if self.dialog_showing.get() == 0: self.dialog_showing.set(1) self.ufd = Ufd(title="Add Items", show_hidden=self.settings_show_hidden.get(), include_files=self.settings_include_files.get(), multiselect=self.settings_multiselect.get(), select_dirs=self.settings_select_dirs.get(), select_files=self.settings_select_files.get(), unix_delimiter=False, stdout=False) for result in self.ufd(): if source: self.list_box_source.insert("end", result) else: self.list_box_dest.insert("end", result) self.dialog_showing.set(0)
class InstanceEditor(Toplevel): def __init__(self): Toplevel.__init__(self) self.focus_set() self.grab_set() self.result = None self.module_data = None self.mod_applis = None self.title(ugettext("Instance editor")) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.ntbk = ttk.Notebook(self) self.ntbk.grid(row=0, column=0, columnspan=1, sticky=(N, S, E, W)) self.frm_general = Frame(self.ntbk, width=350, height=150) self.frm_general.grid_columnconfigure(0, weight=0) self.frm_general.grid_columnconfigure(1, weight=1) self._general_tabs() self.ntbk.add(self.frm_general, text=ugettext('General')) self.frm_database = Frame(self.ntbk, width=350, height=150) self.frm_database.grid_columnconfigure(0, weight=0) self.frm_database.grid_columnconfigure(1, weight=1) self._database_tabs() self.ntbk.add(self.frm_database, text=ugettext('Database')) btnframe = Frame(self, bd=1) btnframe.grid(row=1, column=0, columnspan=1) Button(btnframe, text=ugettext("OK"), width=10, command=self.apply).grid( row=0, column=0, sticky=(N, S, E)) Button(btnframe, text=ugettext("Cancel"), width=10, command=self.destroy).grid( row=0, column=1, sticky=(N, S, W)) def _database_tabs(self): Label(self.frm_database, text=ugettext("Type")).grid( row=0, column=0, sticky=(N, W), padx=5, pady=3) self.typedb = ttk.Combobox( self.frm_database, textvariable=StringVar(), state=READLONY) self.typedb.bind("<<ComboboxSelected>>", self.typedb_selection) self.typedb.grid(row=0, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_database, text=ugettext("Name")).grid( row=1, column=0, sticky=(N, W), padx=5, pady=3) self.namedb = Entry(self.frm_database) self.namedb.grid(row=1, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_database, text=ugettext("User")).grid( row=2, column=0, sticky=(N, W), padx=5, pady=3) self.userdb = Entry(self.frm_database) self.userdb.grid(row=2, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_database, text=ugettext("Password")).grid( row=3, column=0, sticky=(N, W), padx=5, pady=3) self.pwddb = Entry(self.frm_database) self.pwddb.grid(row=3, column=1, sticky=(N, S, E, W), padx=5, pady=3) def _general_tabs(self): Label(self.frm_general, text=ugettext("Name")).grid( row=0, column=0, sticky=(N, W), padx=5, pady=3) self.name = Entry(self.frm_general) self.name.grid(row=0, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_general, text=ugettext("Appli")).grid( row=1, column=0, sticky=(N, W), padx=5, pady=3) self.applis = ttk.Combobox( self.frm_general, textvariable=StringVar(), state=READLONY) self.applis.bind("<<ComboboxSelected>>", self.appli_selection) self.applis.grid(row=1, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_general, text=ugettext("Modules")).grid( row=2, column=0, sticky=(N, W), padx=5, pady=3) self.modules = Listbox(self.frm_general, selectmode=EXTENDED) self.modules.configure(exportselection=False) self.modules.grid(row=2, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_general, text=ugettext("Language")).grid( row=3, column=0, sticky=(N, W), padx=5, pady=3) self.language = ttk.Combobox( self.frm_general, textvariable=StringVar(), state=READLONY) self.language.grid( row=3, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_general, text=ugettext("CORE-connectmode") ).grid(row=4, column=0, sticky=(N, W), padx=5, pady=3) self.mode = ttk.Combobox( self.frm_general, textvariable=StringVar(), state=READLONY) self.mode.bind("<<ComboboxSelected>>", self.mode_selection) self.mode.grid(row=4, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_general, text=ugettext("Password")).grid( row=5, column=0, sticky=(N, W), padx=5, pady=3) self.password = Entry(self.frm_general, show="*") self.password.grid( row=5, column=1, sticky=(N, S, E, W), padx=5, pady=3) def typedb_selection(self, event): visible = list(self.typedb[VALUES]).index(self.typedb.get()) != 0 for child_cmp in self.frm_database.winfo_children()[2:]: if visible: child_cmp.config(state=NORMAL) else: child_cmp.config(state=DISABLED) def appli_selection(self, event): if self.applis.get() != '': appli_id = list(self.applis[VALUES]).index(self.applis.get()) luct_glo = LucteriosGlobal() current_inst_names = luct_glo.listing() appli_root_name = self.mod_applis[appli_id][0].split('.')[-1] default_name_idx = 1 while appli_root_name + six.text_type(default_name_idx) in current_inst_names: default_name_idx += 1 self.name.delete(0, END) self.name.insert( 0, appli_root_name + six.text_type(default_name_idx)) mod_depended = self.mod_applis[appli_id][2] self.modules.select_clear(0, self.modules.size()) for mod_idx in range(len(self.module_data)): current_mod = self.module_data[mod_idx] if current_mod in mod_depended: self.modules.selection_set(mod_idx) def mode_selection(self, event): visible = list(self.mode[VALUES]).index(self.mode.get()) != 2 for child_cmp in self.frm_general.winfo_children()[-2:]: if visible: child_cmp.config(state=NORMAL) else: child_cmp.config(state=DISABLED) def apply(self): from lucterios.framework.settings import DEFAULT_LANGUAGES, get_locale_lang if self.name.get() == '': showerror(ugettext("Instance editor"), ugettext("Name empty!")) return if self.applis.get() == '': showerror(ugettext("Instance editor"), ugettext("No application!")) return db_param = "%s:name=%s,user=%s,password=%s" % ( self.typedb.get(), self.namedb.get(), self.userdb.get(), self.pwddb.get()) security = "MODE=%s" % list( self.mode[VALUES]).index(self.mode.get()) if self.password.get() != '': security += ",PASSWORD=%s" % self.password.get() module_list = [ self.module_data[int(item)] for item in self.modules.curselection()] appli_id = list(self.applis[VALUES]).index(self.applis.get()) current_lang = get_locale_lang() for lang in DEFAULT_LANGUAGES: if lang[1] == self.language.get(): current_lang = lang[0] self.result = (self.name.get(), self.mod_applis[appli_id][ 0], ",".join(module_list), security, db_param, current_lang) self.destroy() def _load_current_data(self, instance_name): from lucterios.framework.settings import DEFAULT_LANGUAGES, get_locale_lang lct_inst = LucteriosInstance(instance_name) lct_inst.read() self.name.delete(0, END) self.name.insert(0, lct_inst.name) self.name.config(state=DISABLED) applis_id = 0 for appli_iter in range(len(self.mod_applis)): if self.mod_applis[appli_iter][0] == lct_inst.appli_name: applis_id = appli_iter break self.applis.current(applis_id) if lct_inst.extra['']['mode'] is not None: self.mode.current(lct_inst.extra['']['mode'][0]) else: self.mode.current(2) self.mode_selection(None) typedb_index = 0 for typedb_idx in range(len(self.typedb[VALUES])): if self.typedb[VALUES][typedb_idx].lower() == lct_inst.database[0].lower(): typedb_index = typedb_idx break self.typedb.current(typedb_index) self.typedb.config(state=DISABLED) self.typedb_selection(None) self.namedb.delete(0, END) if 'name' in lct_inst.database[1].keys(): self.namedb.insert(0, lct_inst.database[1]['name']) self.userdb.delete(0, END) if 'user' in lct_inst.database[1].keys(): self.userdb.insert(0, lct_inst.database[1]['user']) self.pwddb.delete(0, END) if 'password' in lct_inst.database[1].keys(): self.pwddb.insert(0, lct_inst.database[1]['password']) self.modules.select_clear(0, self.modules.size()) for mod_idx in range(len(self.module_data)): current_mod = self.module_data[mod_idx] if current_mod in lct_inst.modules: self.modules.select_set(mod_idx) current_lang = get_locale_lang() if 'LANGUAGE_CODE' in lct_inst.extra.keys(): current_lang = lct_inst.extra['LANGUAGE_CODE'] for lang in DEFAULT_LANGUAGES: if lang[0] == current_lang: self.language.current(self.language[VALUES].index(lang[1])) def execute(self, instance_name=None): from lucterios.framework.settings import DEFAULT_LANGUAGES, get_locale_lang self.mode[VALUES] = [ugettext( "CORE-connectmode.0"), ugettext("CORE-connectmode.1"), ugettext("CORE-connectmode.2")] self.language[VALUES] = [lang[1] for lang in DEFAULT_LANGUAGES] self.typedb[VALUES] = ["SQLite", "MySQL", "PostgreSQL"] lct_glob = LucteriosGlobal() _, self.mod_applis, mod_modules = lct_glob.installed() self.mod_applis.sort(key=lambda item: get_module_title(item[0])) self.modules.delete(0, END) self.module_data = [] module_list = [] for mod_module_item in mod_modules: module_list.append( (get_module_title(mod_module_item[0]), mod_module_item[0])) module_list.sort(key=lambda module: module[0]) for module_title, module_name in module_list: self.modules.insert(END, module_title) self.module_data.append(module_name) appli_list = [] for mod_appli_item in self.mod_applis: appli_list.append(get_module_title(mod_appli_item[0])) self.applis[VALUES] = appli_list if instance_name is not None: self._load_current_data(instance_name) else: self.typedb.current(0) self.mode.current(2) if len(appli_list) > 0: self.applis.current(0) self.appli_selection(None) self.mode_selection(None) self.typedb_selection(None) for lang in DEFAULT_LANGUAGES: if lang[0] == get_locale_lang(): self.language.current(self.language[VALUES].index(lang[1])) center(self)
analyst = StringVar() e2 = Entry(window, width=20, textvariable=analyst) e2.grid(row=1, column=1) notes = StringVar() e3 = Entry(window, width=20, textvariable=notes) e3.grid(row=2, column=1) pid_aid = StringVar() e4 = Entry(window, width=20, textvariable=pid_aid) e4.grid(row=3, column=1) #, height=6, width=36 list1 = Listbox(window, height=6, width=50) list1.grid(row=4, column=0, rowspan=6, columnspan=2) sb1 = Scrollbar(window) sb1.grid(row=2, column=2, rowspan=6) list1.configure(yscrollcommand=sb1.set) sb1.configure(command=list1.yview) #this bind is for deleting what the user selected vs entering data #we will need to bind a selection to a method called get_selected_row list1.bind('<<ListboxSelect>>', get_selected_row) b1 = Button(window, text="View All", width=12, command=view_command) b1.grid(row=2, column=3) b2 = Button(window, text="Search Entry", width=12, command=search_command)
def __init__(self, master, columns, column_weights=None, cnf={}, **kw): """ Construct a new multi-column listbox widget. :param master: The widget that should contain the new multi-column listbox. :param columns: Specifies what columns should be included in the new multi-column listbox. If ``columns`` is an integer, the it is the number of columns to include. If it is a list, then its length indicates the number of columns to include; and each element of the list will be used as a label for the corresponding column. :param cnf, kw: Configuration parameters for this widget. Use ``label_*`` to configure all labels; and ``listbox_*`` to configure all listboxes. E.g.: >>> mlb = MultiListbox(master, 5, label_foreground='red') """ # If columns was specified as an int, convert it to a list. if isinstance(columns, int): columns = list(range(columns)) include_labels = False else: include_labels = True if len(columns) == 0: raise ValueError("Expected at least one column") # Instance variables self._column_names = tuple(columns) self._listboxes = [] self._labels = [] # Pick a default value for column_weights, if none was specified. if column_weights is None: column_weights = [1] * len(columns) elif len(column_weights) != len(columns): raise ValueError('Expected one column_weight for each column') self._column_weights = column_weights # Configure our widgets. Frame.__init__(self, master, **self.FRAME_CONFIG) self.grid_rowconfigure(1, weight=1) for i, label in enumerate(self._column_names): self.grid_columnconfigure(i, weight=column_weights[i]) # Create a label for the column if include_labels: l = Label(self, text=label, **self.LABEL_CONFIG) self._labels.append(l) l.grid(column=i, row=0, sticky='news', padx=0, pady=0) l.column_index = i # Create a listbox for the column lb = Listbox(self, **self.LISTBOX_CONFIG) self._listboxes.append(lb) lb.grid(column=i, row=1, sticky='news', padx=0, pady=0) lb.column_index = i # Clicking or dragging selects: lb.bind('<Button-1>', self._select) lb.bind('<B1-Motion>', self._select) # Scroll whell scrolls: lb.bind('<Button-4>', lambda e: self._scroll(-1)) lb.bind('<Button-5>', lambda e: self._scroll(+1)) lb.bind('<MouseWheel>', lambda e: self._scroll(e.delta)) # Button 2 can be used to scan: lb.bind('<Button-2>', lambda e: self.scan_mark(e.x, e.y)) lb.bind('<B2-Motion>', lambda e: self.scan_dragto(e.x, e.y)) # Dragging outside the window has no effect (diable # the default listbox behavior, which scrolls): lb.bind('<B1-Leave>', lambda e: 'break') # Columns can be resized by dragging them: l.bind('<Button-1>', self._resize_column) # Columns can be resized by dragging them. (This binding is # used if they click on the grid between columns:) self.bind('<Button-1>', self._resize_column) # Set up key bindings for the widget: self.bind('<Up>', lambda e: self.select(delta=-1)) self.bind('<Down>', lambda e: self.select(delta=1)) self.bind('<Prior>', lambda e: self.select(delta=-self._pagesize())) self.bind('<Next>', lambda e: self.select(delta=self._pagesize())) # Configuration customizations self.configure(cnf, **kw)
class autoPage(Frame): def __init__(self, parent, controller, name='autoPage'): Frame.__init__(self, parent) self.animeInfo = None self.cfgFileObject = None self.directoryPath = '' self.fileNames = [] self.seasonList = None self.seasonDict = {} self.listSeasonBoxSelected = '' self.controller = controller self.EPSCONTINUOUS = BooleanVar() self.linkLabel = Label(self, text='Forneça o link da obra', font=('Calibri', 10, 'italic'), width=45) self.linkLabel.grid(row=0, column=0, columnspan=2, padx=1) self.masterFrame = ttk.Frame(self) self.masterFrame.grid(row=1, column=0, columnspan=2, sticky='nesw') self.entryTextLink = StringVar() self.entryLink = ttk.Entry(self.masterFrame, width=45, textvariable=self.entryTextLink) self.entryLink.grid(row=0, column=0, padx=1, sticky='w') if DEBUG: self.searchLogo = PhotoImage( file=resource_path(r'assets\searchButton.png')) else: self.searchLogo = PhotoImage( file=resource_path(r'searchButton.png')) self.searchButton = ttk.Button(self.masterFrame, image=self.searchLogo, width=10, command=self.search) self.searchButton.image = self.searchLogo self.searchButton.grid(row=0, column=1, sticky='e') self.checkButton = ttk.Checkbutton( self.masterFrame, text='Contagem contínua de episódios', onvalue=True, offvalue=False, var=self.EPSCONTINUOUS) self.checkButton.grid(row=1, column=0, sticky='w') self.labelSeason = Label(self, text='Escolha a Temporada', font=('Calibri', 10, 'italic'), width=45) self.labelSeason.grid(row=2, column=0, pady=1, padx=1, columnspan=2) self.listSeasonBox = Listbox(self, height=17, width=54) self.listSeasonBox.grid(row=3, column=0, pady=1, padx=1, columnspan=2, rowspan=3) self.listSeasonBox.bind('<<ListboxSelect>>', self.seasonListBoxSelectItem) self.openDirectoryButton = ttk.Button(self, text='Escolher episódios', width=20, command=self.fileSearchCommand) self.openDirectoryButton.grid(row=7, column=0, columnspan=2, padx=1, pady=2) self.episodeInfoLabel = Label(self, text='Informações dos Episódios', font=('Calibri', 10, 'italic'), width=65) self.episodeInfoLabel.grid(row=0, column=2, columnspan=4) self.textBoxFrame = Frame(self) self.episodeInfoTextBox = Text(self.textBoxFrame, width=105, height=20, wrap='none') self.verticalScrollBar = Scrollbar( self.textBoxFrame, orient='vertical', command=self.episodeInfoTextBox.yview) self.horizontalScrollBar = Scrollbar( self.textBoxFrame, orient='horizontal', command=self.episodeInfoTextBox.xview) self.episodeInfoTextBox.configure( yscrollcommand=self.verticalScrollBar.set, xscrollcommand=self.horizontalScrollBar.set) self.textBoxFrame.grid(row=1, column=2, columnspan=4, rowspan=6, pady=2, padx=1, sticky='nesw') self.episodeInfoTextBox.grid(row=0, column=0, sticky='nesw') self.verticalScrollBar.grid(row=0, column=1, sticky='ns') self.horizontalScrollBar.grid(row=1, column=0, sticky='ew') self.generateCfgButton = ttk.Button(self, text='Gerar CFG', width=20, state='disabled', command=self.generateCfgCommand) self.generateCfgButton.grid(row=7, column=4, sticky='w') def generateCfgCommand(self): editedJasonList = [] inputList = re.split('\n', self.episodeInfoTextBox.get('1.0', 'end-2c')) flag = False for info1, info2 in zip(inputList, self.cfgFileObject.episodeInfoList): editJson = json.loads(re.sub('\'', '"', re.sub('"', '', info1))) editedJasonList.append(editJson) for key in KEYLIST: if editJson[key] != info2[key]: flag = True if flag == True: if messagebox.askokcancel( 'AnieGrabber', 'Foram feitas modificações, tem certeza que deseja gerar assim mesmo?' ): self.cfgFileObject.setCfgFile(self.directoryPath, editedJasonList) else: if messagebox.askokcancel( 'AnieGrabber', 'Tem certeza que deseja gerar o arquivo cfg?'): self.cfgFileObject.setCfgFile( self.directoryPath, self.cfgFileObject.episodeInfoList) messagebox.showwarning('AnieGrabber', 'CFG Criado com sucesso!') self.resetAll() def resetAll(self): self.animeInfo = None self.cfgFileObject = None self.directoryPath = '' self.fileNames = [] self.seasonList = None self.seasonDict = {} self.listSeasonBoxSelected = '' self.resetEpisodeInfoTextBox() self.resetSeasonListBox() self.entryLink.delete(0, END) self.generateCfgButton['state'] = 'disabled' def showInfoCommand(self): if self.fileNames: self.resetEpisodeInfoTextBox() self.cfgFileObject = CFGfile(self.directoryPath, self.fileNames) self.cfgFileObject.getEpisodesNumbers() season = self.getSeason() if self.EPSCONTINUOUS.get(): names = self.animeInfo.getAnimeNamesContinuous() else: names = self.animeInfo.getAnimeNames(season) try: self.cfgFileObject.getEpisodeInfo(names, season, self.EPSCONTINUOUS) except Exception as fnf: messagebox.showerror('AnieGrabber', fnf) return episodeInfoList = self.cfgFileObject.getEpisodeInfoList() if self.cfgFileObject.epsodeNameVerify(): if self.episodeInfoTextBox.get('1.0', END) != '': self.episodeInfoTextBox.delete('1.0', END) if episodeInfoList: for info in episodeInfoList: self.episodeInfoTextBox.insert(END, str(info) + '\n') self.generateCfgButton['state'] = 'able' else: self.episodeInfoTextBox.insert( END, 'Não há episódios para a temporada escolhida\n') else: messagebox.showerror( 'AnieGrabber', 'Parece que um ou mais arquivos estão com o nome icorreto.' ) self.resetEpisodeInfoTextBox() self.resetSeasonListBox() self.entryLink.delete(0, END) self.fileNames = [] else: messagebox.showwarning( 'AnieGrabber', 'Não é possível mostrar informações dos arquivos.') return def resetEpisodeInfoTextBox(self): self.episodeInfoTextBox.delete('1.0', END) def resetSeasonListBox(self): self.listSeasonBox.delete(0, END) def fileSearchCommand(self): fileNames = filedialog.askopenfilenames(initialdir=os.getcwd(), title='Selecione os Episódios', filetypes=[('Arquivos .mp4', '*.mp4')]) if fileNames: self.directoryPath = '\\'.join(re.split( '/', fileNames[0])[:-1]) + os.sep for name in fileNames: self.fileNames.append(re.split('/', name)[-1]) self.showInfoCommand() def getAnimeInfo(self): if re.search(REGEX_URL, self.entryTextLink.get()): self.animeInfo = GetUrlInfo(self.entryTextLink.get()) else: raise ValueError('Formato de link inválido') def seasonListBoxSelectItem(self, event): try: index = self.listSeasonBox.curselection()[0] self.listSeasonBoxSelected = self.listSeasonBox.get(index) except IndexError: pass def getSeason(self): return self.seasonDict[self.listSeasonBoxSelected] def search(self): if self.entryTextLink.get() == '': messagebox.showwarning('AnieGrabber', 'Forneça um link meu parsero!') return try: self.getAnimeInfo() except ValueError as ve: messagebox.showerror('AnieGrabber - Link inválido', ve) return except urllib.error.URLError: messagebox.showerror( 'AnieGrabber', 'Não foi possível acessar o link. Verifique sua conexão com a internet.' ) return self.seasonList = self.animeInfo.getSeasonName() if self.seasonList: for num, season in enumerate(self.seasonList): self.seasonDict[season] = num else: self.seasonList.append('Temporada 1') self.seasonDict['Temporada 1'] = 0 self.updateSeasonListBox() self.listSeasonBoxSelected = self.listSeasonBox.get(0) def updateSeasonListBox(self): self.listSeasonBox.delete(0, 'end') self.listSeasonBox.insert('end', *self.seasonList)
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 Application(): def __init__(self, master, network, debug=False): """ Init method for the Application class, this method is the GUI Class for our solution, it gets master (Tk root, network and debug (Open debug window if needded) :param master: The root Tk of the Application :param network: network is object from Network class (communication) :param debug: bool, to open or not.. """ self.init_constants(master, network) # create constants self.__create_top_toolbar() self.__create_app_frame() self.bindings() self.__network.listen() # network mainloop.. if debug: self.debug = True self.open_debug_dialog() def init_constants(self, master, network): """ This function contruct all the vital constant for this class it gets the root and the network and save them as constant of the class :param master: The root Tk of the Application :param network: network is object from Network class (communication) """ self.__master_splinter = master self.__user_color = StringVar() self.__current_shape = None self.__drawing_shape = None self.__users_list = [] self.__points = [] # private because I dont want that someone change them self.__network = network # private for the same reason self.debug = False def __create_app_frame(self): """ This function creates and pack (using grid) the main app frame (The left toolbar (users list) and the canvas """ app_frame = Frame(self.__master_splinter) self.create_game_canvas(app_frame) self.create_left_toolbar(app_frame) app_frame.grid(row=1) def create_game_canvas(self, app_frame): """ This function creates and pack the game canvas :param app_frame: Tk frame object """ self.canvas = Canvas(app_frame, width=500, height=500, bg='white') self.canvas.grid(column=1) def __create_top_toolbar(self): """ This function creates and pack the top toolbar (with all the colors, shapes and etc.. """ top_toolbar = Frame(self.__master_splinter) help_button = Button(top_toolbar, text="Help", command=self.open_help_dialog) help_button.grid(row=0, column=4) color_frame = self.create_color_frame(top_toolbar) color_frame.grid(row=0, column=0) empty_label = Label(top_toolbar, padx=20) empty_label.grid(column=1, row=0) my_shapes_frame = self.create_shape_buttons(top_toolbar) my_shapes_frame.grid(row=0, column=2) empty_label = Label(top_toolbar, padx=45) empty_label.grid(column=3, row=0) top_toolbar.grid(row=0) def create_left_toolbar(self, app_frame): """ This function creates and pack the left toolbar :param app_frame: root for this toolbar.. (Frame obj) :return: """ left_toolbar = Frame(app_frame) self.lb_users = Listbox(left_toolbar) self.lb_users.config(height=30) self.lb_users.grid(row=0, column=0) scroll_bar = Scrollbar(left_toolbar) scroll_bar.config(command=self.lb_users.yview) scroll_bar.grid(row=0, column=1, sticky='ns') left_toolbar.propagate("false") left_toolbar.grid(column=0, row=0) self.lb_users.config(yscrollcommand=scroll_bar.set) self.debug_event("Left toolbar was generated") def create_shape_buttons(self, root): """ This function get a root and creates all the shapes buttons (because they have picture they need to compile and resize the icons... :param root: Tk frame :return: returns Frame object (it won`t pack it) """ shapes_frame = Frame(root) shape_text = Label(shapes_frame, text="Shape: ") shape_text.grid(row=0, column=0) self.line_image = self.create_shape_img(SHAPES_DICT[LINE]) line_btn = Button(shapes_frame, image=self.line_image, command=lambda: self.create_shape(LINE)) line_btn.grid(row=0, column=1) self.square_image = self.create_shape_img(SHAPES_DICT[SQUARE]) square_btn = Button(shapes_frame, image=self.square_image, command=lambda: self.create_shape(SQUARE)) square_btn.grid(row=0, column=2) self.triangle_image = self.create_shape_img(SHAPES_DICT[TRIANGLE]) triangle_btn = Button(shapes_frame, image=self.triangle_image, command=lambda: self.create_shape(TRIANGLE)) triangle_btn.grid(row=0, column=3) self.elipse_image = self.create_shape_img(SHAPES_DICT[ELIPSE]) elipse_btn = Button(shapes_frame, image=self.elipse_image, command=lambda: self.create_shape(ELIPSE)) elipse_btn.grid(row=0, column=4) self.debug_event("shapes toolbar was generated") return shapes_frame def create_color_frame(self, root): """ This function creates a color frame :param root: Frame obj :return: frame.. """ color_frame = Frame(root) color_text = Label(color_frame, text="Color: ") color_text.grid(row=0, column=0) self.colors_list = ttk.Combobox(color_frame, textvariable=self.__user_color, values=COLOR_LIST, state="readonly") self.colors_list.grid(row=0, column=1) self.colors_list.current(FIRST_COLOR) self.debug_event("color toolbar was generated") return color_frame def create_shape_img(self, path): """ This function get a path for picture.. and creates a icon in size of 32X32 :param path: :return: """ img = Image.open(path) img = img.resize(ICON_SIZE, Image.ANTIALIAS) return ImageTk.PhotoImage(img) def bindings(self): """ This is our binding function.. it bind some things in the GUI some events like get new user, get clicks, close window """ self.canvas.bind(LEFT_BUTTON_CLICK, lambda event: self.try_draw_user_shape(event)) self.__master_splinter.bind(JOIN_EVT, lambda x: self.change_users_list(JOIN_EVT, self.__network.get_event(JOIN_EVT))) self.__master_splinter.bind(LEAVE_EVT, lambda x: self.change_users_list(LEAVE_EVT, self.__network.get_event(LEAVE_EVT))) self.__master_splinter.bind(SHAPE_EVT, lambda event: self.shape_handler()) self.__master_splinter.bind(USERS_EVT, lambda event: self.init_users()) self.__master_splinter.protocol(CLOSE_WINDOW_PROT, self.on_close) def create_shape(self, shape_type): """ After click on Shape this function appear :) it set the current shape to "shape type" :param shape_type: String repr shape type """ self.canvas.config(cursor="target") self.__points = [] self.__current_shape = shape_type self.debug_event("button " + shape_type + " clicked") def shape_handler(self): """ This function handle new shapes events :return: """ shape = self.__network.get_event(SHAPE_EVT) points = self.points_to_tuple(shape[COORDS]) self.debug_event("shape msg:") self.debug_event(str(points)) self.draw_shape(points, shape[SHAPE_TYPE], shape[USER], shape[COLOR]) def init_users(self): """ This function handle "connected" msg when connected it asks the communicator for users list, group name and user name and update the users list """ group_name = self.__network.get_group() self.add_user_to_list(group_name + ":") user = self.__network.get_user_name() self.add_user_to_list(user) users = self.__network.get_user_list() self.debug_event("users list generated") for user in users: self.add_user_to_list(user) def try_draw_user_shape(self, event): """ This function handles canvas clicks, after any click on the canvas this function checks if there was enough clicks to create the relevant shape (If shape is None it won`t happen..) :param event: event obj, contain the x,y of the click """ # trying to draw if self.__current_shape is not self.__drawing_shape: # check if it is a new shape self.__drawing_shape = self.__current_shape self.__points.append((event.x, event.y)) if len(self.__points) is POINTS_NEEDED[self.__drawing_shape]: # Success self.send_shape_details_and_restart() self.debug_event("button is clicked in " + str(event.x) + "," + str(event.y)) def send_shape_details_and_restart(self): """ This function called when the user completed a shape it send to communicator a message the says "New shape was added" """ self.__network.shape_msg([self.__drawing_shape, self.__points, self.__user_color.get()]) self.__current_shape = None self.__drawing_shape = None self.__points = [] self.canvas.config(cursor="") def draw_shape(self, points, s_type, user_name, color): """ This function draw a new shape on the screen :param points: "x,y,z,w,a,b" string that each odd nu is x and each even is y :param s_type: shape type, string :param user_name: user_name string :param color: color, string """ if s_type == LINE: self.canvas.create_line(points, fill=color, width=LINE_WIDTH) elif s_type == SQUARE: self.canvas.create_rectangle(points, fill=color) elif s_type == ELIPSE: self.canvas.create_oval(points, fill=color) elif s_type == TRIANGLE: self.canvas.create_polygon(points, fill=color) self.canvas.create_text(points[:FIRST_XY], text=user_name) self.debug_event("draws: " + s_type) def points_to_tuple(self, str_points): """ this function gets alot of numbers in string and returns :param str_points: "x,y,z,w,a,b" string that each odd nu is x and each even is y :return: list of coordinates as tuple in format (x,y,x,y,x,y) """ nums = str_points.split(',') return tuple(nums) def open_help_dialog(self): """ This function creates new "help" dialog :return: """ try: self.help_frame.destroy() except: pass infromative_txt = self.get_informative_text() self.help_frame = Tk() self.help_frame.title(HELP_TITLE) infromative_text = Label(self.help_frame, text=infromative_txt) infromative_text.pack() self.help_frame.mainloop() def get_informative_text(self): f = open(INFO_DIR, READ_PREM) reader = f.read() f.close() return reader def open_debug_dialog(self): """ this function create new "debug" dialog :return: """ self.debug_frame = Tk() self.debug_frame.title(DEBUG_TITLE) self.debug_messages = Text(self.debug_frame) self.debug_messages.insert(END, "Messages") self.debug_messages.pack() self.debug_frame.mainloop() def debug_event(self, event): """ This function check if the debug option is enabled if it is it will record the event in the debug messages dialog :param event: string repr event to debug.. """ if self.debug: self.debug_messages.insert(END, "\nEVENT: " + str(event)) def on_close(self): """ Handles closing the programe :return: """ self.__network.leave_msg() self.__master_splinter.destroy() try: self.debug_frame.destroy() self.help_frame.destroy() except: pass def change_users_list(self, msg_type, user): """ Handle "change user" event (Leave\Join) :param msg_type: CONSTANT, JOIN\LEAVE :param user: list of users.. """ users = user[ONE_USER] self.debug_event(user + " has " + msg_type) if msg_type is LEAVE_EVT: self.remove_user_from_list(users) elif msg_type is JOIN_EVT: self.add_user_to_list(users) def add_user_to_list(self, user): """ Add specific user the list_box.. of users list :param user: string repr username """ if user not in self.__users_list: self.__users_list.append(user) self.lb_users.insert(END, user) else: self.debug_event(user + " already exists") def remove_user_from_list(self, user): """ This function tries to delete specific username from the list :param user: string repr username :return: """ try: i = self.__users_list.index(user) self.lb_users.delete(i) self.__users_list.pop(i) except: self.debug_event(user + " is not in our list..")
class MemberChecker(PanedWindow): def __init__(self, parent): PanedWindow.__init__(self, parent, background="white") self.parent = parent self.init_data() self.init_log() self.init_ui() self.update_status() def init_data(self): self.data_store = api.DataStore() def init_log(self): self.entrance_log = entrance_log.EntranceLog() def init_ui(self): self.parent.title("Member Checker") self.columnconfigure(3, weight=3) self.pack(fill=BOTH, expand=True) self.input = StringVar() self.input_entry = Entry(self, textvariable=self.input) self.input_entry.bind('<Return>', self.submit) self.input_entry.grid(row=0, column=0, columnspan=3, sticky=E + W) self.result = StringVar() self.result_label = Label(self, textvariable=self.result) self.result_label.grid(row=3, column=0, columnspan=3, sticky=E + W) self.name = StringVar() name_label = Label(self, textvariable=self.name) name_label.grid(row=2, column=0, columnspan=3, sticky=E + W) self.status = StringVar() status_label = Label(self, textvariable=self.status) status_label.grid(row=4, column=0, columnspan=4, sticky=E + W) submit_button = Button(self, text="Submit", command=self.submit) submit_button.grid(row=1, column=2) enter_without_card_button = Button(self, text="Enter without card", command=self.enter_without_card) enter_without_card_button.grid(row=1, column=0) enter_member_without_card_button = Button(self, text="Enter member without card", command=self.enter_member_without_card) enter_member_without_card_button.grid(row=1, column=1) self.entrance_log_list = Listbox(self) self.entrance_log_list.grid(row=0, column=3, rowspan=4, sticky=E + W + S + N) self.input_entry.focus() def load_data(self): if messagebox.askyesno("Load new API Data", "Are you sure you want to load the new API data? All previous data will be removed. The program might be unresponsive for a few seconds, but don't kill it, please! It has feelings too."): self.data_store.load_api_data() def enter_by_identification(self, identification): member = self.data_store.find_member_by_identification(identification) if member is None: if messagebox.askyesno("Not a member", "This university identification is not registered as a member. Do you want to let them in as a non-member?"): self.enter_non_member_by_identification(identification) else: self.enter_member(member) def enter_by_barcode(self, barcode): member = self.data_store.find_member_by_barcode(barcode) if member is None: if messagebox.askyesno("Not a member", "This barcode is not registered as a member. Do you want to let them in as a non-member?"): self.enter_non_member_by_barcode(barcode) else: self.enter_member(member) def enter_non_member_by_identification(self, identification): self.entrance_log.enter_non_member_by_identification(identification) self.enter_non_member() def enter_non_member_by_barcode(self, barcode): self.entrance_log.enter_non_member_by_barcode(barcode) self.enter_non_member() def enter_without_card(self): self.clear_result() self.entrance_log.enter_without_card() self.enter_non_member() self.input_entry.focus() def enter_member(self, member): inside_result = self.entrance_log.is_member_inside(member) if inside_result[0]: if not messagebox.askyesno("Already inside", "This membership card has already been used to enter at {}. Are you sure you want to register it again? Normally you should let this person enter without card (and bill them accordingly).".format( inside_result[1])): return self.entrance_log.enter_member(member) self.result.set('Member!') self.result_label.configure(background='green') self.name.set(member['firstName'] + ' ' + member['lastName']) self.update_status() def enter_non_member(self): self.result.set('Not a member!') self.result_label.configure(background='red') self.name.set('Not in the database') self.update_status() def enter_member_without_card(self): name = self.input.get() if len(name) == 0: messagebox.showinfo('Name required', 'Please enter the name of this person!') return self.entrance_log.enter_member_without_card(name) self.result.set('Member without card!') self.result_label.configure(background="orange") self.name.set('') self.input.set('') self.update_status() def clear_result(self): self.result.set('') self.result_label.configure(background='white') self.name.set('') def submit(self, event=None): self.clear_result() entry = self.input.get() if helpers.is_valid_identification(entry): self.enter_by_identification(entry) elif helpers.is_valid_barcode(entry): self.enter_by_barcode(entry) else: messagebox.showinfo('Invalid entry', 'The data entered was not recognized as a valid bar code or a valid university identification. You should click \'enter without card\' to let this person in.') return self.input.set('') self.input_entry.focus() def clear_log(self): if messagebox.askyesno("Clear log", "Are you sure you want to clear the log of all people who entered?"): self.entrance_log.clear_log() self.update_status() def update_status(self): self.status.set("{} members inside. Total: {}".format(self.entrance_log.members_inside_count(), self.entrance_log.inside_count())) logs = self.entrance_log.get_latest_logs(15) self.entrance_log_list.delete(0, 15) for l in logs: s = l['timestamp'] + ": " data = l['data'] if 'member_id' in data: member = self.data_store.find_member(data['member_id']) s += member['firstName'] + " " + member['lastName'] elif 'barcode' in data: s += data['barcode'] elif 'identification' in data: s += data['identification'] elif 'name' in data: s += '[no card]' + data['name'] else: s += "-" self.entrance_log_list.insert(0, s)
class Viewer(Frame): files = None folder = None def __init__(self, parent): Frame.__init__(self, parent) # Frame for Listbox and Scrollbar self.frm = Frame(self) self.frm.grid(row=2, sticky=NW) # Button and Labels self.file_path = Button(self, text="Choose Folder", command=self.set_dcm_files) self.file_path.grid(row=0) self.msg_label = Label( self, text="Double click the folder \n and then click OK") self.msg_label.grid(row=1) self.info = StringVar(self) self.info_label = Label(self.frm, textvariable=self.info) self.info_label.grid(row=3) # Declaring Scrollbar and Listbox self.sbar = Scrollbar(self.frm, orient='vertical') self.dcm_list = Listbox(self.frm, width=20, yscrollcommand=self.sbar.set) self.dcm_list.bind("<<ListboxSelect>>", self.view_selected_item) self.sbar.config(command=self.dcm_list.yview) self.dcm_list.grid(row=0, column=0) self.sbar.grid(row=0, column=1, sticky=NS) # Sets dcm files and populates Listbox def set_dcm_files(self): self.folder = askdirectory() self.files = os.listdir(self.folder) self.files.sort() self.populate_list() # Populates the Listbox def populate_list(self): self.dcm_list.delete(0, 'end') for f in self.files: self.dcm_list.insert(END, f) # Views the selected item from the Listbox def view_selected_item(self, event): file = self.dcm_list.get(self.dcm_list.curselection()) try: if file.split(".")[1] == 'dcm': self.show_info(file) dataset = pydicom.read_file(self.folder + "/" + file) plt.imshow(dataset.pixel_array, cmap=plt.cm.bone) plt.show() else: self.show_info(f"{file} is not a .dcm file") except IndexError: self.show_info(f'{file} is a directory') # Display info below the Listbox def show_info(self, text=""): self.info.set(text) self.info_label.grid(row=3)
def second_window(root, info): def next_step(): idxs = lbox.curselection() for blogger in idxs: name = bloggers()[blogger] if name not in info['bloggers']: info['bloggers'].append(name) if 'Blogs' in info['platforms']: blog_posts(root, info) else: third_window(root, info) def cantfind(info=info): idxs = lbox.curselection() for blogger in idxs: name = bloggers()[blogger] if name not in info['bloggers']: info['bloggers'].append(name) add_blogger(info=info) def active_next(*args): send.state(['!disabled', 'active']) def back(): idxs = lbox.curselection() for blogger in idxs: name = bloggers()[blogger] if name not in info['bloggers']: info['bloggers'].append(name) first_window(root, info=info) c = ttk.Frame(root, padding=(5, 0, 0, 0)) c.grid(column=0, row=0, sticky=(N, W, E, S)) background_image = tkinter.PhotoImage(file='%s/Desktop/natappy/images/moon.gif' % home) background_label = tkinter.Label(c, image=background_image) background_label.image = background_image background_label.place(x=0, y=0, relwidth=1, relheight=1) root.grid_columnconfigure(0, weight=3) root.grid_rowconfigure(0, weight=3) lbox = Listbox(c, selectmode=MULTIPLE) lbox.grid(column=0, row=1, rowspan=11, columnspan=7, sticky=( N, W, S), padx=(10, 10), pady=(1, 1), ipadx=75) yscroll = ttk.Scrollbar(command=lbox.yview, orient=VERTICAL) yscroll.grid(row=0, column=0, padx=(0, 10), sticky=(N, W, S)) lbox.configure(yscrollcommand=yscroll.set) for blogger in bloggers(): lbox.insert(END, blogger) lbox.bind("<<ListboxSelect>>") lbox.yview_scroll(40, 'units') cantfind = ttk.Button(c, text='Add new bloggers', command=cantfind) cantfind.grid(column=4, row=1, padx=(10, 0), sticky=(N, S, E, W), pady=(20, 10)) send = ttk.Button(c, text='Next', command=next_step, default='active', state='disabled') send.grid(column=6, row=11, sticky=E, pady=20, padx=(2, 20)) close = ttk.Button(c, text='Back', command=back, default='active') close.grid(column=5, row=11, sticky=S + E, pady=20, padx=2) lbox.bind('<<ListboxSelect>>', active_next) if info['bloggers']: for blogger in info['bloggers']: i = bloggers().index(blogger) lbox.selection_set(i) active_next() for i in range(len(bloggers()), 2): lbox.itemconfigure(i, background='#f0f0ff') c.grid_columnconfigure(0, weight=1) c.grid_rowconfigure(5, weight=1) root.title('2/5 Select bloggers') root.geometry('680x550+300+40')
'TCombobox': { 'configure': {'selectborderwidth': 1, 'padding': 2, 'insertwidth': 2, 'font': 'TkTextFont'}} # end of theme extract - don't forget to add comma at end when inserting }) style.theme_use('yummy') # 'default' fr1 = Frame(fr, height=250, width=250) fr1.grid(column=0, row=11, sticky='nsew') widg = Scrollbar(fr1, orient="vertical") widg1 = Scrollbar(fr1, orient="horizontal") mylist = Listbox(fr1) for line in range(100): mylist.insert('end', "A really long line. " + str(line) + " Line number ") mylist.grid(column=0, row=0) widg.grid(column=1, row=0, sticky='ns') widg.configure(command=mylist.yview) widg1.grid(column=0, row=1, sticky='ew') widg1.configure(command=mylist.xview) mylist.configure(yscrollcommand=widg.set, xscrollcommand=widg1.set) # run_state(fr, widg, widg1) root.mainloop()
class SpeciesListDialog: def __init__(self, parent): self.parent = parent self.gui = Toplevel(parent.guiRoot) self.gui.grab_set() self.gui.focus() self.gui.columnconfigure(0, weight=1) self.gui.rowconfigure(1, weight=1) Label(self.gui, text="Registered Species:").grid(row=0, column=0, pady=5, padx=5, sticky="w") self.listRegisteredSpecies = Listbox(self.gui, width=70) self.buttonAdd = Button(self.gui, text=" + ") self.buttonDel = Button(self.gui, text=" - ") self.listRegisteredSpecies.grid(row=1, column=0, columnspan=3, sticky="nswe", pady=5, padx=5) self.buttonAdd.grid(row=2, column=1, pady=5, padx=5) self.buttonDel.grid(row=2, column=2, pady=5, padx=5) # Set (minimum + max) Window size self.gui.update() self.gui.minsize(self.gui.winfo_width(), self.gui.winfo_height()) # self.gui.maxsize(self.gui.winfo_width(), self.gui.winfo_height()) self.actionUpdate(None) self.gui.bind("<<Update>>", self.actionUpdate) self.gui.protocol("WM_DELETE_WINDOW", self.actionClose) self.buttonDel.bind("<ButtonRelease>", self.actionDel) self.buttonAdd.bind("<ButtonRelease>", self.actionAdd) self.gui.mainloop() def actionClose(self): self.parent.guiRoot.event_generate("<<Update>>", when="tail") self.gui.destroy() def actionUpdate(self, event): self.listRegisteredSpecies.delete(0, "end") for (taxid, name) in self.parent.optimizer.speciesList: self.listRegisteredSpecies.insert("end", taxid + ": " + name) def actionDel(self, event): try: selection = self.listRegisteredSpecies.selection_get() selectionSplit = selection.split(": ") self.parent.optimizer.speciesList.remove((selectionSplit[0], selectionSplit[1])) self.gui.event_generate("<<Update>>") except tkinter.TclError: # no selection pass def actionAdd(self, Event): SpeciesSearchDialog(self.parent, self)