class _Select(WidgetBase): def __init__(self, master, default="", command=None, values=[], inline=False, label="", **options): super().__init__(master) from tkinter import StringVar from tkinter.ttk import Frame, Label self.var = StringVar(self.master, value=default) self.inline = inline self.value = default self.command = [command] self.values = values self.widget = Frame(self.master, **options) if label != "": self.label = Label(self.widget, text=label) self.label.pack(side="left", fill="y") if inline: from tkinter.ttk import OptionMenu self.children = OptionMenu(master=self.widget, variable=self.var, command=self.callback, **options) self.children.set_menu(default, *values) self.children.pack(side="right", fill="both") else: self.children = {} for value in values: self.add_item(value) def add_item(self, label=None, **options): if self.inline: self.values.append(label) self.children.set_menu(*self.children) else: from tkinter.ttk import Radiobutton if not label is None: options.update(text=label, value=label) self.children.append( Radiobutton(self.widget, variable=self.var, command=self.callback, **options)) self.children[-1].pack(side="right", fill="both") def del_item(self, label): if self.inline: self.children.pop(label) self.widget.set_menu(*self.children) else: self.children[label].destroy() def callback(self, *args): self.value = self.var.get() self.command[0]()
def initUI(self, mainFrame): """initialize the User Interface""" # styles style = Style() style.configure("GRN.TLabel", background="#ACF059") style.configure("GRN.TFrame", background="#ACF059") style.configure("BLK.TFrame", background="#595959") # create top frame topFrame = Frame(mainFrame, style="GRN.TFrame", padding=8) topFrame.pack(fill=BOTH, side=TOP) # create black border borderFrame = Frame(mainFrame, style="BLK.TFrame") borderFrame.pack(fill=BOTH, side=TOP) # create add player frame addPlayerFrame = Frame(mainFrame, padding=8) addPlayerFrame.pack(side=TOP) # create text field for add button self.nameFieldVar = StringVar() self.playerNameEntry = Entry(addPlayerFrame, textvariable = self.nameFieldVar) self.playerNameEntry.pack(side=LEFT) # create add player button addButton = Button(addPlayerFrame, text="Add player") addButton.pack(side=LEFT) # create choose game list self.currentGame = StringVar() self.currentGame.set(self.gameList[0]) gameDropDown = OptionMenu(mainFrame, self.currentGame, self.gameList[0], *self.gameList) gameDropDown.pack(side=TOP) # create start game button startGameButton = Button(mainFrame, text="Start") startGameButton.bind("<Button-1>", self.startGame) startGameButton.pack(side=TOP) # create label and set text self.playerString = StringVar() self.playerString.set(self.buildPlayerHeaderString()) headerLabel = Label(topFrame, textvariable=self.playerString, style="GRN.TLabel") headerLabel.pack(side=TOP) addButton.bind("<Button-1>", self.onAddPlayerClick) self.playerNameEntry.bind("<Key>", self.onAddPlayerEnter) #set focus self.playerNameEntry.focus()
class PlotFrame(Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.plot_title = '' self.create_widgets() def create_widgets(self): self.dropdown_label = Label(self, text='Choose a type of graph') self.option_var = StringVar(self, name="option") self.option_var.set('Bar') self.option_var.trace('w', self.on_option_change) self.close_button = Button(self, text='Close Tab', command=self.close_tab) self.data = { 'Country': ['US', 'CA', 'GER', 'UK', 'FR'], 'GDP_Per_Capita': [45000, 42000, 52000, 49000, 47000] } self.data_frame = DataFrame(self.data) # self.plot = self.create_plot(self.plot_title, self.data_frame, self, self.option_var) self.plot = None self.options = ['Bar', 'Line'] self.dropdown = OptionMenu(self, self.option_var, self.options[0], *self.options) self.close_button.pack(anchor=W) self.dropdown_label.pack(side=TOP, anchor=N) self.dropdown.pack(side=TOP, anchor=N) def on_option_change(self, *args): if args[0] == 'option' and self.plot is not None: self.plot.graph.get_tk_widget().pack_forget() self.plot.plot_graph(self, self.option_var) def create_plot(self, title, data_frame, master, option_var): self.plot = Plot(title, data_frame, master, option_var) def close_tab(self): self.master.forget(self)
def __init__(self, window): super(Themes, self).__init__(window) self.window = window self.title("PyCreator - Themes") title = Label(self, text="Choisissez le thème") liste_themes = [self.window.theme] for i in Style().theme_names(): if i not in liste_themes: liste_themes.append(i) self.v = StringVar() self.v.set(liste_themes[0]) om = OptionMenu(self, self.v, *liste_themes) b = Button(self, text="Valider", command=self.validate) title.pack(padx=10, pady=10) om.pack(padx=10, pady=5) b.pack(padx=10, pady=5)
def __init__(self, parent=None): Frame.__init__(self, parent) self.parent = parent self.parent.title("Partlocater - Manual Add") self.parent.iconbitmap(self.FAVICON) self.manual_frame = LabelFrame(self, text="Add Component") self.manual_frame.pack(side=TOP, fill=BOTH, expand=YES, pady=4, padx=4) self.prop_frame = [] self.propvalue = [] for item in self.PROPLIST: self.prop_frame.append(Frame(self.manual_frame)) self.prop_frame[-1].pack(side=TOP, fill=X, expand=YES) prop_label = Label(self.prop_frame[-1], anchor=E, text=item, width=20) prop_label.pack(side=LEFT, anchor=E, fill=X, expand=YES, pady=4) self.propvalue.append(StringVar()) if item != "Category": prop_entry = Entry(self.prop_frame[-1], textvariable=self.propvalue[-1], state=NORMAL, width=30) prop_entry.pack(side=LEFT, fill=X, expand=YES, pady=4, padx=4) self.propvalue[-1].trace("w", self.check_minentry) else: self.cat_entry = Entry(self.prop_frame[-1], textvariable=self.propvalue[-1], state=DISABLED, width=40) self.cat_entry.pack(side=LEFT, fill=X, expand=YES, pady=4, padx=4) if (item.startswith("Manufacturer")): self.propvalue[-1].trace("w", self.check_minentry) self.cat_option = StringVar() table_list = ['Capacitors'] + Config().tables cat_menu = OptionMenu(self.prop_frame[-1], self.cat_option, *table_list, command=self.on_category) cat_menu.pack(side=TOP, anchor=N, fill=X, expand=YES) self.button_frame = Frame(self.manual_frame) self.button_frame.pack(side=TOP, fill=X, expand=NO) self.clear_button = ttk.Button(self.button_frame, text="Clear", command=self.do_clear, state=NORMAL, width=8) self.clear_button.pack(side=RIGHT, anchor=W, fill=X, expand=NO) self.commit_button = ttk.Button(self.button_frame, text="Add", command=self.do_commit, state=DISABLED, width=8) self.commit_button.pack(side=RIGHT, anchor=W, fill=X, expand=NO) self.status_frame = LabelFrame(self, text="Status") self.status_frame.pack(side=BOTTOM, fill=X, expand=YES, pady=4, padx=6) self.status = self.StatusBar(self.status_frame, self) self.status.set("Set Category") self.pack(side=LEFT, fill=BOTH, expand=YES)
class HoukagoFrameTime(Frame): def __init__(self, *args, **kwargs): super().__init__(args[0], **kwargs) self.algs = args[1] # Блок выбора алгоритма self.frm_alg = Frame(self) self.frm_alg.pack(side=TOP) # Заголовок self.lbl_alg = Label(self.frm_alg, text="Алгоритм:") self.lbl_alg.pack(side=LEFT) # Выбор алгоритма self.cur_alg = StringVar() self.cur_alg.trace("w", self.alg_changed) self.ddl_alg = OptionMenu(self.frm_alg, self.cur_alg, *list(self.algs.keys())) self.ddl_alg.pack(side=LEFT) def alg_changed(self, *args): pass
def initUI(self): def stop(): #os.killpg(os.getpgid(self.pid), signal.SIGINT) print("[*] Stop sniffing") self.sniffer.join(2.0) if self.sniffer.isAlive(): self.sniffer.socket.close() # update database with the new records AirTrack.update_db() def start(): self.sniffer = AirTrack.Sniffer('-i ' + self.iface.get()) self.sniffer.start() #AirTrack.start_session('-i '+self.iface.get()) self.cleanScrollText() self.updateScrolltext("Inizio rilevazione:\n") numberOfStudents = set() def count(): global previousNumberOfStudends for element in AirTrack.records_from_sniffing: if element.last_time - element.first_time > 0: numberOfStudents.add(element) students = "Studenti presenti: " + str( len(numberOfStudents) ) #sostituire counter con una stringa che venga aggiornata con l'output del terminale in questa riga if numberOfStudents is not previousNumberOfStudends: previousNumberOfStudends != numberOfStudents self.cleanScrollText() self.updateScrolltext(str(students) + "\n") self.after(5000, count) count() self.master.title("AirTrack") #self.style = Style() #self.style.theme_use("default") top_label = Label(self, text="Welcome to AirTrack:") top_label.pack(side=TOP, padx=5, pady=5, anchor='w') scrollbarLogFrame = Frame(self, relief=RAISED, borderwidth=1) scrollbarLogFrame.pack(fill=BOTH, expand=True) self.pack(fill=BOTH, expand=True) self.scrollbarLog = scrolledtext.ScrolledText( scrollbarLogFrame, background="black", foreground="green") #, state=DISABLED) self.scrollbarLog.pack(fill=BOTH, expand=True, padx=5, pady=5) startButton = Button(self, text="Start", command=start) #inserire command startButton.pack(side=RIGHT, padx=5, pady=5) stopButton = Button(self, text="Stop", command=stop) #inserire command stopButton.pack(side=RIGHT) interface_label = Label(self, text="Interface:") interface_label.pack(side=LEFT, padx=5, pady=5) interfaces_list = OptionMenu(self, self.iface, next(iter(self.INTERFACES)), *self.INTERFACES) interfaces_list.pack(side=LEFT) self.updateScrolltext("Select network interface and press Start.\n")
def cont_display(): #Sets up the content to be displayed during exam global op_s, opt_s, ent, answers, res_var, prog, pages, text, ques_count, test global vsb, mafore, rev, red_vars, rev_butList, quesList, opList def scrollwheel(event): #Prevents MouseWheel binding to Text return 'break' text = Text(main_frame, wrap="none", bd = 0) text.pack(fill="both", expand=True, padx = (10,0)) text.bind('<MouseWheel>', scrollwheel) temp = 1 ques_count = 0 height = int(screen_height/1.2) width = int((2480/1748)*height) rev_butList = [] prev_butList = [] next_butList = [] quesList = [] opList = [] for images in sorted(os.listdir(opath)): #Canvas, Scrollbar, Frame canvas = Canvas(main_frame, height = height, width = width+15, bd = 0) img_frame = Frame(canvas) img_text = Text(img_frame, bd = 0) vsb = Scrollbar(canvas, orient = 'vertical') vsb.pack(side = 'right', fill = 'y') vsb.configure(command = img_text.yview) img_text.config(yscrollcommand = vsb.set) img_frame.configure(height = height, width = width) #Insert Image into the Text im = Image.open(os.path.join(opath, f'Ques_{str(temp)}.png')) w, h = im.size im = im.resize((width, int((h/w)*width)), Image.ANTIALIAS) img = ImageTk.PhotoImage(im) img_frame.pack(side = 'left', fill = 'both', expand = True) img_frame.pack_propagate(False) img_text.pack(side = 'left', fill = 'both', expand = True) img_text.configure(state = 'disabled') img_text.image_create('end', image = img) img_text.image = img text.window_create("end", window = canvas) text.insert("end", "\n") #CheckButtons buttons() options = Label(main_frame, text = "OPTIONS", font=("Open Sans",15), bg = 'white') text.window_create("end", window=options) text.insert("end", " "*16) for i in range(0, 4): text.window_create("end", window=op_s[i]) k = BooleanVar() op_s[i].configure(variable = k, bg = 'white') text.insert("end", " "*8) res_var.append(k) text.insert("end", "\n\n") #Entry entry = Label(main_frame, text = "ENTRY", font=("Open Sans",15), bg = 'white') text.window_create("end", window=entry) text.insert("end", " "*19) text.window_create("end", window=ent) #Navigation/Marking Buttons prev = Button(main_frame, text = " Previous ", font=("Havelika",12), command = lambda temp = temp: seek_prev(temp), bg = 'RoyalBlue', fg = 'white', relief = 'flat') prev_butList.append(prev) mfr = Button(main_frame, text = " Mark for Review ", font=("Sans",12), command = lambda temp = temp: mfor(temp), bg = 'RoyalBlue', fg = 'white', relief = 'flat') rev_butList.append(mfr) nex = Button(main_frame, text = " Next ", font=("Havelika",12), command = lambda temp = temp: seek_next(temp), bg = 'RoyalBlue', fg = 'white', relief = 'flat') next_butList.append(nex) text.insert("end", " "*13) text.window_create("end", window=prev) text.insert("end", " "*11) text.window_create("end", window=mfr) text.insert("end", " "*11) text.window_create("end", window=nex) text.insert("end", "\n") m = StringVar() ent.configure(textvariable = m) res_var.append(m) if temp != len(os.listdir(opath)): text.insert("end", "\n") #Updation temp += 1 ques_count += 1 prog += ((1/pages)*50) progress['value'] = prog load.update_idletasks() #Configuration text.configure(state="disabled") prev_butList[0].configure(state = "disabled") next_butList[-1].configure(state = "disabled") #SideFrames Initialization info_lab = Label(toggle_frame, text = "Quick Question Navigation", bg = 'white', font=("Sans",12)) info_lab.pack(side = 'top', anchor = 'nw', pady = 10) lab_frame = Frame(toggle_frame, bg = 'white') lab_frame.pack(side = 'left')#, fill = 'y') opmenu_frame = Frame(toggle_frame, bg = 'white') opmenu_frame.pack(side = 'left')#, fill = 'y') style = Style() style.configure('my.TMenubutton', font=('sans', 12)) #OptionMenu red_vars = [] for i in range (0, len(sections)): qnoList = [] if sections[i] == 0: try: #Issue 3 Fixed for qno in range(0, sections[i+1]+1): qnoList.append("Question "+str(qno)) except: for qno in range(sections[-1], ques_count+1): qnoList.append("Question "+str(qno)) else: try: for qno in range(sections[i], sections[i+1]+1): qnoList.append("Question "+str(qno)) except: for qno in range(sections[-1], ques_count+1): qnoList.append("Question "+str(qno)) ques_redir = "var"+str(i) ques_redir = StringVar() red_vars.append(ques_redir) v = "tog"+str(i) v = OptionMenu(opmenu_frame, ques_redir, *qnoList, command = seek, style = 'my.TMenubutton') opList.append(v) v["menu"].config(font = ('Sans', 12)) label = Label(lab_frame, text = section_name[i], bg = 'white', font=("Sans",12)) label.pack(side = 'top', anchor = 'nw', padx = (0,10), pady = (2,0)) ques_redir.set("Select Question") v.pack(side = 'top', anchor = 'ne', padx = (0,10)) quesList.append(qnoList) mafore = StringVar() mafore.set("Select Question") labelm = Label(lab_frame, text = "Marked for Review", bg = 'white', font=("Sans",12)) labelm.pack(side = 'top', anchor = 'nw', padx = (0,10), pady = (2,0)) rev = OptionMenu(opmenu_frame, mafore, *[None], command = seek, style = 'my.TMenubutton') rev["menu"].config(font = ('Sans', 12)) rev.pack(side = 'top', anchor = 'ne', padx = (0,10)) red_vars[0].set("Question 1") #Indicatiors ligand_frame = Frame(base_frame, bg = 'white') ligand_frame.pack(anchor = 'se', side = 'bottom') color_frame = Frame(ligand_frame, bg = 'white') color_frame.pack(side = 'left', pady = (0,10)) des_frame = Frame(ligand_frame, bg = 'white') des_frame.pack(side = 'right', pady = (0,10)) colors = ['lawn green', 'red', 'SlateBlue2', 'orange'] des = ['Answered', 'Unanswered but Seen', 'Answered and Marked for Review', 'Unanswered and Marked for Review'] for color, description in zip(colors, des): col = Label(color_frame, text = " ", bg = color, bd = 0, font = 10) col.pack(side = 'top', anchor = 'nw', padx = (0,10)) des = Label(des_frame, text = description, bg = 'white', font=("Sans",10), justify = 'left') des.pack(side = 'top', anchor = 'nw', padx = (0,10), pady = (2,0)) #Complete Loading load.destroy() #Threads time_th = Thread(target = timer).start() mon_th = Thread(target = Monitor).start()
class SearchApplication(GenericFrame): FAVICON = "../assets/favicon.ico" def __init__(self, parent=None, app_window=None): self.lastValue = None self.category_option = StringVar("") self.column_id = [ 'ProductDescription', 'ManufacturerName', 'ManufacturerPartNumber', 'DigiKeyPartNumber', 'Category' ] Frame.__init__(self, parent) self.pack() self.parent = parent self.app_window = app_window self.selectedField = None self.parent.title("Partlocater - Advanced Database Search") self.parent.iconbitmap(self.FAVICON) self.menubar = Frame(self, background='white') self.menubar.pack(side=TOP, fill=X, expand=YES) self.win_frame = Frame(self) self.win_frame.pack(side=TOP, fill=BOTH, expand=YES) self.editbutton = Menubutton(self.menubar, text='Edit', background='grey98') self.editbutton.pack(side=LEFT, fill=X) self.editmenu = Menu(self.editbutton, tearoff=0) self.editbutton.config(menu=self.editmenu) self.copySourcesMenu = Menu(self.editbutton, tearoff=0) self.editmenu.add_cascade(label='Copy', menu=self.copySourcesMenu) self.copySourcesMenu.add_command(label='Part Number', state=DISABLED, command=self.on_copy_partnumber) self.partnumber_index = 0 self.copySourcesMenu.add_command(label='Selected Parameter', state=DISABLED, command=self.on_copy_parameters) self.selectedParameter_index = 1 self.copySourcesMenu.add_command(label='Selected Part All Parameters', state=DISABLED, command=self.on_copy_all_parameters) self.allParameters_index = 2 self.editmenu.add_command(label='Delete Part', state=DISABLED, command=self.on_delete) self.searchLF = LabelFrame(self.win_frame, text="Search") self.searchLF.pack(side=LEFT, fill=X, expand=YES, pady=4, padx=6) self.searchLeftF = Frame(self.searchLF) self.searchLeftF.pack(side=LEFT, anchor=W) self.searchRightF = Frame(self.searchLF) self.searchRightF.pack(side=LEFT, anchor=N) self.searchLabelWidth = 20 self.catF = Frame(self.searchLeftF) self.catF.pack(side=TOP, anchor=W) self.catL = Label(self.catF, text='Category', width=self.searchLabelWidth, anchor=W, justify=LEFT) self.catL.pack(side=LEFT, fill=X, expand=YES) self.cat = StringVar() self.catE = Entry(self.catF, textvariable=self.cat, width=50, state=DISABLED) self.catE.config(disabledbackground=self.catE.cget("bg")) self.catE.config(disabledforeground=self.catE.cget("fg")) self.catE.pack(side=LEFT, fill=X, expand=YES, pady=4) self.category_option = StringVar() self.cat.set("All") option_list = ['All', 'All'] + Config().tables self.catM = OptionMenu(self.searchRightF, self.category_option, *option_list, command=self.on_category) self.catM.pack(side=TOP, anchor=N, fill=X, expand=YES) self.manF = Frame(self.searchLeftF) self.manF.pack(side=TOP, anchor=W) self.manL = Label(self.manF, text='ManufacturerName', width=self.searchLabelWidth, anchor=W, justify=LEFT) self.manL.pack(side=LEFT, fill=X, expand=YES, pady=4) self.man = StringVar() self.manE = Entry(self.manF, width=50, textvariable=self.man) self.manE.pack(side=LEFT, fill=X, expand=YES, pady=4) self.mpnF = Frame(self.searchLeftF) self.mpnF.pack(side=TOP, anchor=W) self.mpnL = Label(self.mpnF, text='ManufacturerPartNumber', width=self.searchLabelWidth, anchor=W, justify=LEFT) self.mpnL.pack(side=LEFT, fill=X, expand=YES, pady=4) self.mpn = StringVar() self.mpnE = Entry(self.mpnF, width=50, textvariable=self.mpn) self.mpnE.pack(side=LEFT, fill=X, expand=YES, pady=4) self.spnF = Frame(self.searchLeftF) self.spnF.pack(side=TOP, anchor=W) self.spnL = Label(self.spnF, text='DigiKeyPartNumber', width=self.searchLabelWidth, anchor=W, justify=LEFT) self.spnL.pack(side=LEFT, fill=X, expand=YES, pady=4) self.spn = StringVar() self.spnE = Entry(self.spnF, width=50, textvariable=self.spn) self.spnE.pack(side=LEFT, fill=X, expand=YES, pady=4) self.descF = Frame(self.searchLeftF) self.descF.pack(side=TOP, anchor=W) self.descL = Label(self.descF, text='ProductDescription', width=self.searchLabelWidth, anchor=W, justify=LEFT) self.descL.pack(side=LEFT, fill=X, expand=YES, pady=4) self.desc = StringVar() self.descE = Entry(self.descF, width=50, textvariable=self.desc) self.descE.pack(side=LEFT, fill=X, expand=YES, pady=4) self.descE.focus_force() self.findF = Frame(self.searchLeftF) self.findF.pack(side=TOP, anchor=E) self.findB = ttk.Button(self.findF, text="Find", width=12, command=lambda event=None: self.do_find(event)) self.findB.pack(side=LEFT, pady=4) self.clearB = ttk.Button(self.findF, text="Clear", width=6, command=self.on_clear_search) self.clearB.pack(side=LEFT, pady=4) self.partsLF = LabelFrame(self, text="Found Components") self.partsLF.pack(side=TOP, fill=X, expand=YES, pady=4, padx=4) self.partsF = Frame(self.partsLF) self.partsF.pack(side=TOP, pady=4, padx=4) # change treeview for search here self.partsTV = Treeview(self.partsF, selectmode=BROWSE, show='tree headings', columns=self.column_id) self.partsTV.bind('<Double-Button-1>', self.on_edit_item) self.partsTV.bind('<<TreeviewSelect>>', self.fieldChanged) self.partsTV.bind('<Escape>', self.clearSelection) self.partsTV.bind('<MouseWheel>', self.mousewheel) self.partsTV.bind('<Button-4>', self.mousewheel) self.partsTV.bind('<Button-5>', self.mousewheel) vcmd = (self.register(self.validateEntry), '%P') self.editfield = ttk.Entry(self.partsTV, validate='key', validatecommand=vcmd) self.editfield.bind('<Return>', self.updateField) self.editfield.bind('<Escape>', self.clearSelection) self.partsTV.bind('<Control-c>', self.on_copy_element) self.partsTV.column("#0", minwidth=0, width=18, stretch=NO) for t in self.column_id: self.partsTV.heading(t, text=Config().parameter[t]) self.partsTV.column('Category', width=60) self.scrollbar = Scrollbar(self.partsF, orient='vertical', command=self.partsTV.yview) self.scrollbar.pack(side=RIGHT, fill=Y, expand=YES, anchor=E) self.partsTV.configure(yscroll=self.scrollbar.set) self.scrollbar.config(command=self.yview) self.partsTV.pack(side=TOP, anchor=W, fill=X, expand=YES) self.partsTV.delete(*self.partsTV.get_children()) # end change of treeview # change the following to menu item #self.part_buttonF = Frame(self.partsLF) #self.delete_partB = ttk.Button(self.partsLF, text="Delete Part from Database", command=self.on_delete, #state=DISABLED) #self.delete_partB.pack(side=RIGHT, anchor=W, expand=NO, pady=4, padx=6) #self.partsB = ttk.Button(self.partsLF, text="Copy Selected To Part Find", command=self.on_copy, state=DISABLED) #self.partsB.pack(side=RIGHT, anchor=W, expand=NO, pady=4, padx=6) #self.part_buttonF.pack(side=BOTTOM) # start remove vvv #self.element_labelframe = LabelFrame(self, text="Modify Name/Value") #self.element_labelframe.pack(side=TOP, fill=X, expand=YES, pady=4, padx=6) #self.element_frame = Frame(self.element_labelframe) #self.element_frame.pack(side=TOP) #self.element_name = StringVar() #self.element_label = Label(self.element_frame, textvariable=self.element_name, width=30, anchor=W, justify=LEFT) #self.element_label.pack(side=LEFT, anchor=W, fill=X, expand=YES, pady=4) #self.element_value = StringVar() #self.element_entry = Entry(self.element_frame, width=50, textvariable=self.element_value) #self.element_entry.pack(side=LEFT, fill=X, expand=YES, pady=4) #self.default_color = self.element_entry.cget('background') #self.element_update = ttk.Button(self.element_frame, text="Update", command=self.on_update_element, #state=DISABLED) #self.element_update.pack(side=LEFT, fill=X, expand=YES, pady=4) #self.element_cancel = ttk.Button(self.element_frame, text="Cancel", command=self.on_clear_element, #state=DISABLED) #self.element_cancel.pack(side=LEFT, fill=X, expand=YES, pady=4) # end remove ^^^ self.statusLF = LabelFrame(self, text="Status") self.statusLF.pack(side=BOTTOM, fill=X, expand=YES, pady=4, padx=6) self.statusF = Frame(self.statusLF) self.statusF.pack(side=TOP, fill=X, expand=YES, padx=6) self.status = self.StatusBar(self.statusF, self) def validateEntry(self, P): if (len(P) <= 120): return True else: self.bell() return False # scroll bar event def yview(self, *args): if self.selectedField is not None: self.editfield.place_forget() self.selectedField = None self.partsTV.yview(*args) # mousewheel and button4/5 event def mousewheel(self, event): if self.selectedField is not None: self.editfield.place_forget() self.selectedField = None # escape event in treeview or editfield def clearSelection(self, event): self.editfield.place_forget() self.selectedField = None self.partsTV.selection_remove(self.partsTV.selection()) self.status.set("") # double button event def on_edit_item(self, event): if self.partsTV.parent(self.partsTV.selection() ) == '': # testing should not edit a parent self.selectedField = None return if (self.partsTV.identify_region(event.x, event.y) == 'cell'): self.selectedField = self.partsTV.identify_row(event.y) x, y, width, height = self.partsTV.bbox(self.selectedField, '#2') v = self.partsTV.set(self.selectedField, 1) self.editfield.pack() self.editfield.delete(0, len(self.editfield.get())) self.editfield.insert(0, v) self.editfield.selection_range(0, 'end') self.editfield.focus_force() self.editfield.place(x=x, y=y, width=width, height=height) # find button event def on_find(self): category = self.cat.get() search_list = [] col_list = [] search_str = self.man.get() if not (validate(search_str)): raise Exception("Invalid Manufacture Name") search_list.append(search_str) col_list.append(Config().parameter['ManufacturerName']) search_str = self.mpn.get() if not (validate(search_str)): raise Exception("Invalid Manufacture Part Number") search_list.append(search_str) col_list.append(Config().parameter['ManufacturerPartNumber']) search_str = self.spn.get() if not (validate(search_str)): raise Exception("Invalid Supplier Part Number") search_list.append(search_str) col_list.append(Config().parameter['DigiKeyPartNumber']) search_str = self.desc.get().split() if not (validate(search_str)): raise Exception("Invalid Description") search_list += search_str col_list.append(Config().parameter['ProductDescription']) select = "SELECT * FROM `" + Config().loaded_db.name + "`." where = "WHERE" like = "" i = 0 for item in search_list: if len(item) > 0: item = item.replace('%', '\\%') item = item.replace('"', '') item = item.replace("'", "") if i < 3: like += where + " `" + col_list[ i] + "` LIKE '" + item + "%'" else: like += where + " (`" + col_list[i] + "` LIKE '" + item + "%' OR `" + \ col_list[i] + "` LIKE '% " + item + "%')" where = " AND" i = i + 1 if (i < 3) else i self.partsTV.delete(*self.partsTV.get_children()) count = 0 if category == "All": for table in Config().tables: qry = select + "`" + table + "` " + like result = Config().loaded_db.query(qry) for record in result: v = [] spn = record[Config().parameter['DigiKeyPartNumber']] count += 1 for id in self.column_id: if id == 'Category': v.append(table) else: v.append(record[Config().parameter[id]]) id = self.partsTV.insert('', 'end', iid=spn, text=spn, values=v) for params in record: if record[params] is not None: self.partsTV.insert(id, 'end', text=spn, values=(params, record[params])) else: qry = select + "`" + category + "` " + like result = Config().loaded_db.query(qry) for record in result: v = [] count += 1 spn = record[Config().parameter['DigiKeyPartNumber']] for id in self.column_id: if id == 'Category': v.append(category) else: v.append(record[Config().parameter[id]]) id = self.partsTV.insert('', 'end', iid=spn, text=spn, values=v) for params in record: if record[params] is not None: self.partsTV.insert(id, 'end', text=spn, values=(params, record[params])) self.status.set(("No" if count == 0 else str(count)) + " items found") # return event def updateField(self, event): value = self.editfield.get() self.editfield.place_forget() name = self.partsTV.item(self.selectedField, "text") if not validate(value): self.status.seterror("Invalid value, must not have quotes") return self.partsTV.set(self.selectedField, "#2", value) key = self.partsTV.set(self.selectedField, "#1") self.editfield.place_forget() element_parent = self.partsTV.parent(self.selectedField) table_name = self.partsTV.item( element_parent, "values")[self.column_id.index('Category')] part_number = self.partsTV.item( element_parent, "values")[self.column_id.index('DigiKeyPartNumber')] set_param = "SET `" + key + "` = '" + value + "' " where = "WHERE `" + Config( ).parameter['DigiKeyPartNumber'] + "` = '" + part_number + "'" qry = "UPDATE `" + Config( ).loaded_db.name + "`.`" + table_name + "` " + set_param + where print(qry) try: Config().loaded_db.query(qry) except Exception as e: self.status.seterror("Database query failed: %s", e) return self.status.set("Changed " + key + " to " + value + " for part " + part_number + ".") self.partsTV.see(self.selectedField) # clear button in search frame def on_clear_search(self): self.man.set("") self.mpn.set("") self.spn.set("") self.desc.set("") self.cat.set("All") self.category_option.set("All") self.partsTV.delete(*self.partsTV.get_children()) def do_flash(self): current_color = self.element_entry.cget("background") if current_color == self.default_color: self.element_entry.config(background="red") else: self.element_entry.config(background=self.default_color) return self.after(250, self.do_flash) # category option menu def on_category(self, value): self.catE.config(state=NORMAL) self.cat.set(value) self.catE.config(state=DISABLED) #def on_copy(self): #selected = self.partsTV.selection()[0] #key = self.partsTV.item(selected, "values")[self.column_id.index('DigiKeyPartNumber')] #self.app_window.part_num_string.set(key) #self.status.set("Part Number '" + key + "' copied to Part Find") # Edit -> Delete menu def on_delete(self): selected = self.partsTV.selection()[0] key = self.partsTV.item( selected, "values")[self.column_id.index('DigiKeyPartNumber')] table = self.partsTV.item(selected, "values")[self.column_id.index('Category')] if messagebox.askokcancel( "Delete", "Click OK if you really want to delete '" + key + "' from database?"): Config().loaded_db.query("DELETE FROM `" + table + "` WHERE `" + Config().parameter['DigiKeyPartNumber'] + "` = '" + key + "'") self.status.set("Part Number '" + key + "' deleted from database") # treeview select event def fieldChanged(self, event): selected = self.partsTV.selection() if len(selected) > 0: self.copySourcesMenu.entryconfig(self.partnumber_index, state=NORMAL) self.copySourcesMenu.entryconfig(self.allParameters_index, state=NORMAL) else: self.copySourcesMenu.entryconfig(self.partnumber_index, state=DISABLED) self.copySourcesMenu.entryconfig(self.allParameters_index, state=DISABLED) return if self.partsTV.parent(selected) == '': self.copySourcesMenu.entryconfig(self.selectedParameter_index, state=DISABLED) else: self.copySourcesMenu.entryconfig(self.selectedParameter_index, state=NORMAL) if selected != self.selectedField: self.editfield.place_forget() self.selectedField = None def on_copy_parameters(self): selected = self.partsTV.selection() if len(selected) == 0 or self.partsTV.parent(selected) == '': return try: property = self.partsTV.item(selected, "values") self.parent.clipboard_clear() self.parent.clipboard_append(property[0] + '\t' + property[1]) self.parent.update() self.status.set(property[0] + ' ' + property[1] + " copied to clipboard") except Exception as e: pass def on_copy_partnumber(self): selected = self.partsTV.selection() if len(selected) == 0 or self.partsTV.parent(selected) == '': return try: if self.partsTV.parent(selected) != '': selected = self.partsTV.parent(selected) partnumber = self.partsTV.item( selected, "values")[self.column_id.index('DigiKeyPartNumber')] self.parent.clipboard_clear() self.parent.clipboard_append(partnumber) self.parent.update() self.status.set(" '" + partnumber + "' copied to clipboard") except Exception as e: pass def on_copy_all_parameters(self): selected = self.partsTV.selection() if len(selected) == 0: return try: if self.partsTV.parent(selected) != '': selected = self.partsTV.parent(selected) partnumber = self.partsTV.item( selected, "values")[self.column_id.index('DigiKeyPartNumber')] elements = self.partsTV.get_children(selected) self.parent.clipboard_clear() self.parent.clipboard_clear() for i in elements: element = self.partsTV.item(i, "values") self.parent.clipboard_append(element[0] + "\t" + element[1] + "\n") self.parent.update() self.status.set("All properties of " + partnumber + " copied to clipboard") except Exception as e: pass # deprecate def on_copy_element(self, event): try: selected = self.partsTV.selection()[0] if self.partsTV.parent(selected) == '': partnumber = self.partsTV.item elements = self.partsTV.get_children(selected) self.parent.clipboard_clear() for i in elements: element = self.partsTV.item(i, "values") self.parent.clipboard_append(element[0] + "\t" + element[1] + "\n") self.parent.update() self.status.set("All properties of " + self.partsTV.item(selected, "values")[3] + " copied to clipboard") else: key = self.partsTV.item(selected, "values")[0] val = self.partsTV.item(selected, "values")[1] self.parent.clipboard_clear() self.parent.clipboard_append(val) self.parent.update() self.status.set(key + " '" + val + "' copied to clipboard") except Exception as e: pass def do_find(self, event): try: self.on_find() except Exception as e: self.status.seterror(e)
class Control(Frame): def __init__(self): # initialize RED and BLUE fighters self.RED = 0 self.BLUE = 1 # initialize score and kyonggo variables self.redPoints = 0 self.bluePoints = 0 self.redKyonggo = 0 self.blueKyonggo = 0 self.currentRound = 0 self.display = None self.miniDisplay = None self.numRounds = 0 self.timer = None self.isSuddenDeath = False self.callNextRound = True try: # for Python3 super().__init__() except: # for Python2 Frame.__init__(self) # set title and default style self.master.title("TKD Scoring System") # create style self.s = Style() self.s.configure("TButton", padding=10, font=(None, 20)) self.s.configure("TCheckbutton", padding=10, font=(None, 20)) self.s.configure("TOptionMenu", padding=10, font=(None, 20)) self.pack(fill=BOTH, expand=True) # create setup frames, labels, and entries # time entry frame self.setTimeFrame = Frame(self) self.timerLabel = Label(self.setTimeFrame, text="Time:", font=(None, 20)) self.secondsEntry = Entry(self.setTimeFrame, width=3, font=(None, 20)) self.colonLabel = Label(self.setTimeFrame, text=":", font=(None, 20)) self.minuteEntry = Entry(self.setTimeFrame, width=3, font=(None, 20)) # round entry frame self.roundsFrame = Frame(self) self.roundsLabel = Label(self.roundsFrame, text="Number of Rounds:", font=(None, 20)) self.roundsEntry = Entry(self.roundsFrame, width=3, font=(None, 20)) # serial entry frame self.serialFrame = Frame(self) try: self.arduino_ports = ["None"] + [ p.device for p in serial.tools.list_ports.comports() ] except: # if serial is not installed self.arduino_ports = ["None"] self.serialEntry = StringVar() self.serialEntry.set("None") self.serialLabel = Label(self.serialFrame, text="Serial Input:", font=(None, 20)) self.serialCheck = OptionMenu(self.serialFrame, self.serialEntry, "None", *self.arduino_ports) self.createMatchButton = Button(self, text="Create Match", style="TButton", command=self.hideSetup) # initialize frames for UI # red frame and buttons self.redFrame = Frame(self) self.redScoreButton = Button( self.redFrame, text="Red +", style="TButton", command=lambda: self.incrementPoints(self.RED)) self.redDeletePoint = Button( self.redFrame, text="Red -", style="TButton", command=lambda: self.deductPoints(self.RED)) self.redKyonggoButton = Button( self.redFrame, text="Kyonggo +", style="TButton", command=lambda: self.callKyonggo(self.RED)) self.redKyonggoDelete = Button( self.redFrame, text="Kyonggo -", style="TButton", command=lambda: self.deductKyonggo(self.RED)) # blue frame and buttons self.blueFrame = Frame(self) self.blueScoreButton = Button( self.blueFrame, text="Blue +", style="TButton", command=lambda: self.incrementPoints(self.BLUE)) self.blueDeletePoint = Button( self.blueFrame, text="Blue -", style="TButton", command=lambda: self.deductPoints(self.BLUE)) self.blueKyonggoButton = Button( self.blueFrame, text="Kyonggo +", style="TButton", command=lambda: self.callKyonggo(self.BLUE)) self.blueKyonggoDelete = Button( self.blueFrame, text="Kyonggo -", style="TButton", command=lambda: self.deductKyonggo(self.BLUE)) # reset and new match frame and buttons self.resetFrame = Frame(self) self.startStop = StringVar() self.timerStartStop = Button(self.resetFrame, textvariable=self.startStop, style="TButton", command=self.timerPush) self.startStop.set("Start Round 1") self.newMatch = Button(self.resetFrame, text="New Match", style="TButton", command=self.newMatch) self.resetMatch = Button(self.resetFrame, text="Reset Match", style="TButton", command=self.resetMatch) self.setup() # displays setup frames def setup(self): # timer frame self.setTimeFrame.pack(fill=X) # timer label and entry self.timerLabel.pack(side=LEFT, padx=5, pady=5) self.secondsEntry.pack(side=RIGHT) self.colonLabel.pack(side=RIGHT) self.minuteEntry.pack(side=RIGHT) # frame for number of rounds self.roundsFrame.pack(fill=X) # number of rounds label and entry self.roundsLabel.pack(side=LEFT, padx=5, pady=5) self.roundsEntry.pack(side=RIGHT) # frame for serial entry self.serialFrame.pack(fill=X, expand=True) # serial entry label and checkbox self.serialLabel.pack(side=LEFT, padx=5, pady=5) self.serialCheck.pack(side=RIGHT) # create match button self.createMatchButton.pack(side=BOTTOM) # hides setup widgets and initalizes timer and number of rounds def hideSetup(self): # check if minutes, seconds, and round entries are valid if len(self.minuteEntry.get()) < 1: minutes = 0 else: try: minutes = int(self.minuteEntry.get()) except: minutes = 0 if len(self.secondsEntry.get()) < 1: seconds = 0 else: try: seconds = int(self.secondsEntry.get()) % 60 minutes += int(self.secondsEntry.get()) // 60 except: seconds = 0 if len(self.roundsEntry.get()) < 1: numRounds = 0 else: try: numRounds = int(self.roundsEntry.get()) except: numRounds = 0 # set up serial input if checked if self.serialEntry.get() != "None": self.serialSetup() else: self.arduino = False # only moves on if entries are valid if ((minutes != 0) or (seconds != 0)) and (numRounds != 0): self.roundLength = [minutes, seconds] self.timer = Timer(self.roundLength) self.numRounds = numRounds self.currentRound = 1 self.isSuddenDeath = False self.roundsFrame.pack_forget() self.setTimeFrame.pack_forget() self.createMatchButton.pack_forget() self.serialFrame.pack_forget() self.initUI() # set up serial input def serialSetup(self): try: self.arduino = True self.serialPort = self.serialEntry.get() self.baudRate = 9600 self.ser = serial.Serial(self.serialPort, self.baudRate, timeout=0, writeTimeout=0) self.ser.flushInput() except: self.arduino = False print("Could Not Complete Serial Port Set Up") # creates user interface def initUI(self): # create display if self.display == None: self.display = Display(self.timer) self.display.attributes('-fullscreen', True) else: self.display.newTimer(self.timer) self.display.updateCurrentRound("R1") if self.miniDisplay == None: self.miniDisplay = miniDisplay(self.timer) else: self.miniDisplay.newTimer(self.timer) self.miniDisplay.updateCurrentRound("R1") # red point and kyonggo buttons self.redFrame.pack(fill=BOTH, side=LEFT) self.redScoreButton.pack(padx=5, pady=5, fill=X) self.redDeletePoint.pack(padx=5, pady=5, fill=X) self.redKyonggoButton.pack(padx=5, pady=5, fill=X) self.redKyonggoDelete.pack(padx=5, pady=5, fill=X) # blue point and kyonggo buttons self.blueFrame.pack(fill=BOTH, side=RIGHT) self.blueScoreButton.pack(padx=5, pady=5, fill=X) self.blueDeletePoint.pack(padx=5, pady=5, fill=X) self.blueKyonggoButton.pack(padx=5, pady=5, fill=X) self.blueKyonggoDelete.pack(padx=5, pady=5, fill=X) # timer start/stop button, reset button, and quit button self.resetFrame.pack(side=BOTTOM) self.startStop.set("Start Round " + str(self.currentRound)) self.timerStartStop.pack(side=TOP, pady=5) self.newMatch.pack(side=LEFT, padx=5) self.resetMatch.pack(side=RIGHT, padx=5) def timerPush(self): # if round is over, reset time give option to start next round if self.timer.timeLeft[0] == self.timer.timeLeft[1] == 0: self.timer.reset() self.startStop.set("Start Round " + str(self.currentRound)) self.display.updateCurrentRound("R" + str(self.currentRound)) self.miniDisplay.updateCurrentRound("R" + str(self.currentRound)) self.updateDisplayTimer() # pause timer, give option to unpause elif self.timer.isRunning(): self.timer.stop() self.startStop.set("Start") # unpause timer, give option to pause else: if self.arduino: self.ser.flushInput() self.timer.start() if self.arduino: self.readSerialInput() self.startStop.set("Pause") if not self.callNextRound: self.callNextRound = True self.updateDisplayTimer() def resetMatch(self): if not self.timer.isRunning(): self.timer.reset() self.redPoints = 0 self.bluePoints = 0 self.redKyonggo = 0 self.blueKyonggo = 0 self.currentRound = 1 if self.isSuddenDeath: self.isSuddenDeath = False self.newMatch.pack_forget() self.resetMatch.pack_forget() self.timerStartStop.pack(side=TOP, pady=5) self.newMatch.pack(side=LEFT, padx=5) self.resetMatch.pack(side=RIGHT, padx=5) self.startStop.set("Start Round 1") self.display.reset(self.timer.getTimeString()) self.miniDisplay.reset(self.timer.getTimeString()) def updateDisplayTimer(self): if self.timer.isElapsed(): self.timer.stop() if self.callNextRound: self.nextRound() if self.currentRound < self.numRounds or self.redPoints == self.bluePoints: self.display.updateTimer(self.timer.getTimeString()) self.miniDisplay.updateTimer(self.timer.getTimeString()) elif self.currentRound > self.numRounds: self.suddenDeath() else: self.display.updateTimer(self.timer.getTimeString()) self.miniDisplay.updateTimer(self.timer.getTimeString()) self.after(1000, self.updateDisplayTimer) def nextRound(self): self.callNextRound = False self.currentRound += 1 if self.currentRound <= self.numRounds: self.startStop.set("Reset Timer") elif self.redPoints == self.bluePoints: self.startStop.set("Sudden Death") else: self.declareWinner() self.timerStartStop.pack_forget() def declareWinner(self): if self.redPoints > self.bluePoints: winner = "RED" else: winner = "BLUE" self.display.updateTimer(winner + " WINS") self.display.updateCurrentRound("") def suddenDeath(self): self.redPoints = 0 self.display.updateRedPoints(0) self.miniDisplay.updateRedPoints(0) self.bluePoints = 0 self.display.updateBluePoints(0) self.miniDisplay.updateBluePoints(0) self.display.updateTimer("SUDDEN DEATH") self.miniDisplay.updateTimer("SUDDEN DEATH") self.display.updateCurrentRound("") self.miniDisplay.updateCurrentRound("") self.isSuddenDeath = True if self.arduino: self.readSerialInput() self.timerStartStop.pack_forget() def readSerialInput(self): if self.timer.isRunning() or self.isSuddenDeath: output = self.ser.readline() if len(output) != 0: try: fighter = int(output) self.incrementPoints(fighter) except: print("Invalid Serial Input") self.after(250, self.readSerialInput) else: self.after(50, self.readSerialInput) def incrementPoints(self, fighter): if fighter == self.RED: self.redPoints += 1 self.display.updateRedPoints(self.redPoints) self.miniDisplay.updateRedPoints(self.redPoints) elif fighter == self.BLUE: self.bluePoints += 1 self.display.updateBluePoints(self.bluePoints) self.miniDisplay.updateBluePoints(self.bluePoints) if self.isSuddenDeath: self.declareWinner() def deductPoints(self, fighter): if fighter == self.RED and self.redPoints > 0: self.redPoints -= 1 self.display.updateRedPoints(self.redPoints) self.miniDisplay.updateRedPoints(self.redPoints) elif fighter == self.BLUE and self.bluePoints > 0: self.bluePoints -= 1 self.display.updateBluePoints(self.bluePoints) self.miniDisplay.updateBluePoints(self.bluePoints) def callKyonggo(self, fighter): if fighter == self.RED: self.redKyonggo += 1 self.display.updateRedKyonggo("Kyonggo: " + str(self.redKyonggo)) self.miniDisplay.updateRedKyonggo("Kyonggo: " + str(self.redKyonggo)) if self.redKyonggo % 2 == 0: self.bluePoints += 1 self.display.updateBluePoints(self.bluePoints) self.miniDisplay.updateBluePoints(self.bluePoints) elif fighter == self.BLUE: self.blueKyonggo += 1 self.display.updateBlueKyonggo("Kyonggo: " + str(self.blueKyonggo)) self.miniDisplay.updateBlueKyonggo("Kyonggo: " + str(self.blueKyonggo)) if self.blueKyonggo % 2 == 0: self.redPoints -= 1 self.display.updateRedPoints(self.redPoints) self.miniDisplay.updateRedPoints(self.redPoints) def deductKyonggo(self, fighter): if fighter == self.RED and self.redKyonggo > 0: self.redKyonggo -= 1 self.display.updateRedKyonggo("Kyonggo: " + str(self.redKyonggo)) self.miniDisplay.updateRedKyonggo("Kyonggo: " + str(self.redKyonggo)) if self.redKyonggo % 2 == 1: self.redPoints += 1 self.display.updateRedPoints(self.redPoints) self.miniDisplay.updateRedPoints(self.redPoints) elif fighter == self.BLUE and self.blueKyonggo > 0: self.blueKyonggo -= 1 self.display.updateBlueKyonggo("Kyonggo: " + str(self.blueKyonggo)) self.miniDisplay.updateBlueKyonggo("Kyonggo: " + str(self.blueKyonggo)) if self.blueKyonggo % 2 == 1: self.bluePoints += 1 self.display.updateBluePoints(self.bluePoints) self.miniDisplay.updateBluePoints(self.bluePoints) def newMatch(self): if not self.timer.isRunning(): self.redPoints = 0 self.redKyonggo = 0 self.bluePoints = 0 self.blueKyonggo = 0 self.display.reset("0:00") self.miniDisplay.reset("0:00") self.hideUI() self.setup() def hideUI(self): self.redFrame.pack_forget() self.blueFrame.pack_forget() self.resetFrame.pack_forget()
def __init__(self): super().__init__() self.master.title("Income calculator app") self.pack(fill=BOTH, expand=True) # label frame0 = Frame(self) frame0.pack(fill=X) title = Label(frame0, text='Welcome to the app', font=("Times New Roman", 20)) title.pack() # frame 1 frame1a = Frame(self) frame1a.pack(fill=X, padx=10, pady=10) name_label = Label(frame1a, text="Employee name :", width=15) name_label.pack(side=LEFT, padx=5, pady=5) name = Entry(frame1a) name.pack(fill=X, padx=5, expand=True) frame1b = Frame(self) frame1b.pack(fill=X, padx=10, pady=10) destination_label = Label(frame1b, text="Destination :", width=15) destination_label.pack(side=LEFT, padx=5, pady=5) # destination = Entry(frame1b) # destination.pack(fill=X, padx=5, expand=True) data = pd.read_csv("country_currency.csv") data.dropna(subset=['Country'], inplace=True) destination_select = StringVar(frame1b) destination = AutocompleteCombobox( frame1b, textvariable=destination_select, width=20, completevalues=data['Country'].to_list()) destination.pack() # frame 2 frame2 = Frame(self) frame2.pack(fill=X) netIncome_label = Label(frame2, text='Net income (per year)', width=20) netIncome_label.pack(side=LEFT, padx=5, pady=5) netIncome = Entry(frame2) netIncome.pack(fill=X, padx=5, expand=True) #frame 3 frame3 = Frame(self) frame3.pack(pady=10) maritalStatus_label = Label(frame3, text='Marital status ', width=15) maritalStatus_label.pack(side=LEFT, padx=5, pady=5) maritalStatus_select = StringVar(frame3) maritalStatus_select.set(maritalStatusList[0]) maritalStatus = OptionMenu(frame3, maritalStatus_select, *maritalStatusList) maritalStatus.pack(side=LEFT, padx=10) nKids_label = Label(frame3, text='Number of kids :', width=20) nKids_select = IntVar(frame3) nKids_select.set(nKids_list[0]) nKids_entry = OptionMenu(frame3, nKids_select, *nKids_list) nKids_label.pack(side=LEFT) nKids_entry.pack(side=LEFT) def get_info(): try: df_row = data[data['Country'] == destination_select.get()] currency_code = str(df_row['Currency code'].values[0]) currency_name = str(df_row['Currency'].values[0]) except: messagebox.showwarning('Warning', 'Please select a destination') currency_code = 'EUR' currecy_name = 'Euros' country2_select.set(currency_code) currency.set(currency_name) #frame 3 frame3a = Frame(self) frame3a.pack(pady=5) info_button = Button(frame3a, text='Get info', command=get_info) info_button.pack(side=TOP) forex_label = Label(frame3a, text='Currency conversion From ', width=15) forex_label.pack(side=LEFT, padx=5, pady=5) country1_select = StringVar(frame3a) country1_select.set(currecy_list[0]) country1 = OptionMenu(frame3a, country1_select, *currecy_list) country1.pack(side=LEFT, padx=10) forex_label2 = Label(frame3a, text=' To ', width=5) country2_select = StringVar(frame3a) currency = StringVar(frame3a) country2_select.set('EUR') currency.set('Euros') country2 = Text(frame3a, height=1, width=10) country2.insert(END, country2_select.get()) forex_label2.pack(side=LEFT) country2.pack(side=LEFT) forex_display = Text(frame3a, height=1, width=10) c = CurrencyRates() forex_display.insert( END, c.get_rate(country1_select.get(), country2_select.get())) forex_display.pack(side=RIGHT, padx=10) forex_conversion = StringVar() forex_conversion.set('1.0') def callback(*args): forex_display.delete(1.0, "end") country2.delete(1.0, "end") try: forex_conversion.set( c.get_rate(country1_select.get(), country2_select.get())) forex_display.insert(END, forex_conversion.get()) country2.insert(END, country2_select.get()) except Exception as exception_error: messagebox.showwarning('Warning', exception_error) forex_conversion.set('1.0') forex_display.insert(END, '0') country2_select.trace("w", callback) country1_select.trace("w", callback) #frame 4 frame4 = Frame(self) frame4.pack(pady=10) radioInput = IntVar(self) radioInput.set(1) R1 = Radiobutton(frame4, text="Yearly", variable=radioInput, value=1) R2 = Radiobutton(frame4, text="Montly", variable=radioInput, value=2) R3 = Radiobutton(frame4, text="Daily", variable=radioInput, value=3) period_label = Label(frame4, text='Calculating for period :') period_label.pack(side=LEFT) R1.pack(side=LEFT, pady=10) R2.pack(side=LEFT, pady=10) R3.pack(side=RIGHT, pady=10) now = datetime.now() # current date and time def get_string(): income = float('0' + netIncome.get()) status = str(maritalStatus_select.get()) output_string = "Income calculation \t {} \n\n".format( now.strftime("%d/%m/%Y, %H:%M:%S")) output_string += "Employee name :{} \n\n".format(name.get()) output_string += "Destination :{} \n".format( destination_select.get()) output_string += "Currency :{} - {} \n".format( country2_select.get(), currency.get()) output_string += "\nNet yearly income = {} {} ".format( income, country1_select.get()) output_string += "\n\nCalcualting for " + str( period[radioInput.get() - 1]) if radioInput.get() == 2: income = round(income / 12, 2) elif radioInput.get() == 3: income = round(income / 365, 2) output_string += "\nNet income = {} {} \nMarital status = {} ".format( income, country1_select.get(), status) output_string += "\nNumber of kids = " + str(nKids_select.get()) try: tax_rate = get_tax(country=destination_select.get()) social_sec_em, social_sec_com = get_social_security( country=destination_select.get()) except: messagebox.showwarning( 'Warning', 'Tax / social security information NOT found') tax_rate = 0 social_sec_em, social_sec_com = 0, 0 output_string += "\n\nTax rate : {} %".format(tax_rate) output_string += "\nSocial security rates:" output_string += "\n employee : {} %".format(social_sec_em) output_string += "\n company : {} %".format(social_sec_com) output_string += "\n\n Tax amount : {}".format( round(income * tax_rate / 100, 2)) output_string += "\n Employee social security amount : {}".format( round(income * social_sec_em / 100, 2)) output_string += "\n Company social security amount : {}".format( round(income * social_sec_com / 100, 2)) total = float( get_total(income=income, rate1=tax_rate, rate2=social_sec_em, rate3=social_sec_com)) output_string += "\n\nTotal : {} {}".format( total, country1_select.get()) output_string += '\n conversion = {}'.format( forex_conversion.get()) total *= float(forex_conversion.get()) output_string += "\n after conversion {} {} ".format( round(total, 2), country2_select.get()) return output_string def write_pdf(): pdf = FPDF() pdf.add_page() pdf.set_margins(30, 50, 25) pdf.set_font("Arial", size=15) output_string = get_string().split('\n') for s in output_string: pdf.cell(200, 10, txt=s, ln=1) pdf.output(name.get() + ' ' + str(now.strftime("%d_%m_%Y")) + '_info.pdf') def write_txt(): with open( name.get() + ' ' + str(now.strftime("%d_%m_%Y")) + '_info.txt', 'w') as sfile: sfile.write(get_string()) def string_display(): output_display.delete(1.0, END) output_display.insert(END, get_string()) frame5 = Frame(self, borderwidth=1) frame5.pack(fill=BOTH, expand=True, padx=5, pady=5) output_display = Text(frame5, height=15) scroll_y = Scrollbar(frame5, orient="vertical", command=output_display.yview) scroll_y.pack(side="right", expand=True, fill="y", padx=2, pady=2) output_display.pack(side='left', fill=X, padx=2, pady=2) output_display.configure(yscrollcommand=scroll_y.set) frame_final = Frame(self, relief=RAISED, borderwidth=1) frame_final.pack(fill=X, padx=10, pady=5) submit_button = Button(frame_final, text='Submit', command=string_display) submit_button.pack(side=LEFT) file_type_label = Label(frame_final, text='Choose file type:') file_type_label.pack() file_save_type = StringVar() file_save_type.set(save_list[0]) file_save = OptionMenu(frame_final, file_save_type, *save_list) def save_to_file(): if file_save_type.get() == 'txt': write_txt() messagebox.showinfo('Saved!', 'Saved as text file') elif file_save_type.get() == 'pdf': write_pdf() messagebox.showinfo('Saved!', 'Saved as pdf file') else: messagebox.showwarning('Warning', 'Please select text file or pdf') save_button = Button(frame_final, text='Save to file', command=save_to_file) save_button.pack(side=RIGHT) file_save.pack(side=RIGHT)
def initUI(self): self.parent.title("Digital Cookbook") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1, side=BOTTOM) # Establish menu bar # menubar = Menu(self.parent) self.parent.config(menu=menubar) # Add file menu # filemenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Import recipe from XML file", command=self.xmlImport) filemenu.add_command(label="Add blank recipe to database", command=self.recipeAdd) filemenu.add_command(label="Delete recipe from database", command=self.recipeDelete) filemenu.add_command(label="Load recipe", command=self.recipeLoad) filemenu.add_command(label="Save recipe to database", command=self.recipeSave, accelerator="Ctrl+S") filemenu.add_separator() filemenu.add_command(label="Exit", command=self.onExit, accelerator="Ctrl+W") # Add help menu # helpmenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Help", menu=helpmenu) helpmenu.add_command(label="About...", command=self.helpAbout) # Establish toolbar # frameToolbar = Frame(self.parent) # , relief=RAISED, borderwidth=1) frameToolbar.pack(side=TOP, fill=X) # Add buttons to toolbar # buffer = 2 buttonspaceing = 100 buttonwidth = 12 buttonheight = 30 bImportXML = Button(frameToolbar, text="Import XML", command=self.xmlImport, width=buttonwidth) bImportXML.pack(side=LEFT, padx=buffer, pady=buffer) bAddRecipe = Button(frameToolbar, text="Add Recipe", command=self.recipeAdd, width=buttonwidth) bAddRecipe.pack(side=LEFT, padx=buffer, pady=buffer) bDeleteRecipe = Button(frameToolbar, text="Delete Recipe", command=self.recipeDelete, width=buttonwidth) bDeleteRecipe.pack(side=LEFT, padx=buffer, pady=buffer) bEditRecipe = Button(frameToolbar, text="Load Recipe", command=self.recipeLoad, width=buttonwidth) bEditRecipe.pack(side=LEFT, padx=buffer, pady=buffer) bSaveRecipe = Button(frameToolbar, text="Save Recipe", command=self.recipeSave, width=buttonwidth) bSaveRecipe.pack(side=LEFT, padx=buffer, pady=buffer) # Recipe list section frameRecipeList = Frame(self, borderwidth=1, width=200) frameRecipeList.pack_propagate(0) frameRecipeList.pack(side=LEFT, fill=Y) Label(frameRecipeList, text="Recipe List").pack() # Category option menu default = StringVar(frameRecipeList) default.set("----") recipeCatagories = OptionMenu(frameRecipeList, default, "----", "None", "Cat 1", "Cat 2", "Cat 3") recipeCatagories.pack(side=TOP, fill=X) # Filter Frame frameFilter = Frame(frameRecipeList, relief=RAISED, borderwidth=1, width=200) frameFilter.pack(side=TOP, fill=X) Label(frameFilter, text="Filter...").pack() # Filter text filterText = Entry(frameFilter) filterText.pack_propagate(0) filterText.pack(side=LEFT, fill=X) # Filter Button filterButton = Button(frameFilter, text="Go", command=self.placeholder) filterButton.pack_propagate(0) filterButton.pack(side=RIGHT) # Recipe Box Frame frameRecipeBox = Frame(frameRecipeList, relief=RAISED, borderwidth=1) frameRecipeBox.pack(side=TOP, fill=BOTH, expand=1) # ==== Recipe List box ==== recipeListScroll = Scrollbar(frameRecipeBox, orient=VERTICAL) self.recipeList = Listbox(frameRecipeBox, selectmode=EXTENDED, yscrollcommand=recipeListScroll.set) self.recipeList.pack(side=LEFT, fill=BOTH, expand=1) recipeListScroll.config(command=self.recipeList.yview) recipeListScroll.pack(side=RIGHT, fill=Y) self.getReciepList() self.populateRecipeList(self.recipes) # Spacer frameSpacer1 = Frame(self, borderwidth=1, width=10) frameSpacer1.pack_propagate(0) frameSpacer1.pack(side=LEFT, fill=Y) # Recipe info section frameRecipeInfo = Frame(self, borderwidth=1, width=200) frameRecipeInfo.pack_propagate(0) frameRecipeInfo.pack(side=LEFT, fill=Y) # Recipe name Label(frameRecipeInfo, text="Recipe Name:", anchor=E, justify=LEFT).pack() self.recipeName = Entry(frameRecipeInfo) self.recipeName.pack(side=TOP, fill=X) # Prep Time framePrepTime = Frame(frameRecipeInfo) framePrepTime.pack(side=TOP, fill=X) Label(framePrepTime, text="Prep Time:", anchor=E, justify=LEFT).pack() self.prepTime = Entry(framePrepTime) self.prepTime.pack(side=LEFT, fill=X) default = StringVar(framePrepTime) default.set("----") self.prepTimeUnit = OptionMenu(framePrepTime, default, "----", "Min", "Hr") self.prepTimeUnit.pack(side=RIGHT, fill=X) # Cook Time frameCookTime = Frame(frameRecipeInfo) frameCookTime.pack(side=TOP, fill=X) Label(frameCookTime, text="Cook Time:", anchor=E, justify=LEFT).pack() self.cookTime = Entry(frameCookTime) self.cookTime.pack(side=LEFT, fill=X) default = StringVar(frameCookTime) default.set("----") self.cookTimeUnit = OptionMenu(frameCookTime, default, "----", "Min", "Hr") self.cookTimeUnit.pack(side=RIGHT, fill=X) # Spacer frameSpacer2 = Frame(self, borderwidth=1, width=10) frameSpacer2.pack_propagate(0) frameSpacer2.pack(side=LEFT, fill=Y) # Ingredient List frameIngredients = Frame(self, borderwidth=1, width=300) frameIngredients.pack_propagate(0) frameIngredients.pack(side=LEFT, fill=Y) Label(frameIngredients, text="Ingredients").pack() # Ingredient Name self.ingredientName = Entry(frameIngredients) self.ingredientName.pack(side=TOP, fill=X) # Ingredient info frameIngredientQuantity = Frame(frameIngredients) frameIngredientQuantity.pack(side=TOP, fill=X) Label(frameIngredientQuantity, text="Ingredient Quantity (value, unit):", anchor=E, justify=LEFT).pack() self.ingredientQuantity = Entry(frameIngredientQuantity) self.ingredientQuantity.pack(side=LEFT, fill=X, expand=1) self.ingredientUnit = Entry(frameIngredientQuantity, width=20) self.ingredientUnit.pack_propagate(0) self.ingredientUnit.pack(side=RIGHT, fill=X) # Spacer frameSpacer3 = Frame(frameIngredients, height=10) frameSpacer3.pack_propagate(0) frameSpacer3.pack(side=TOP, fill=X) # Ingredient List buttons frameIngredientButtons = Frame(frameIngredients) frameIngredientButtons.pack(side=TOP, fill=X) ingredientAdd = Button(frameIngredientButtons, text="+", command=self.ingredientAdd, width=3) ingredientAdd.pack(side=LEFT) ingredientDel = Button(frameIngredientButtons, text="-", command=self.ingredientDelete, width=3) ingredientDel.pack(side=LEFT) ingredientUp = Button(frameIngredientButtons, text=u"\u25B2", command=self.ingredientMoveUp, width=3) ingredientUp.pack(side=LEFT) ingredientDwn = Button(frameIngredientButtons, text=u"\u25BC", command=self.ingredientMoveDown, width=3) ingredientDwn.pack(side=LEFT) ingredientLoad = Button(frameIngredientButtons, text="Load", command=self.ingredientLoadInfo) ingredientLoad.pack(side=LEFT) ingredientSave = Button(frameIngredientButtons, text="Save", command=self.ingredientSaveInfo) ingredientSave.pack(side=LEFT) # Ingredient List Box Frame frameIngredientList = Frame(frameIngredients, relief=RAISED, borderwidth=1) frameIngredientList.pack(side=TOP, fill=BOTH, expand=1) # Ingredient List box ingredientListScroll = Scrollbar(frameIngredientList, orient=VERTICAL) self.ingredientList = Listbox( frameIngredientList, selectmode=SINGLE, yscrollcommand=ingredientListScroll.set ) # Set selectmode=SINGLE???? self.ingredientList.pack(side=LEFT, fill=BOTH, expand=1) ingredientListScroll.config(command=self.ingredientList.yview) ingredientListScroll.pack(side=RIGHT, fill=Y) # Spacer frameSpacer4 = Frame(self, borderwidth=1, width=10) frameSpacer4.pack_propagate(0) frameSpacer4.pack(side=LEFT, fill=Y) # Recipe Procedure frameProcedure = Frame(self, borderwidth=1) frameProcedure.pack(side=LEFT, fill=BOTH, expand=1) Label(frameProcedure, text="Procedure", anchor=E, justify=LEFT).pack(side=TOP) procedureScroll = Scrollbar(frameProcedure, orient=VERTICAL) self.procedure = Text(frameProcedure, maxundo=30, undo=1, wrap=WORD, yscrollcommand=procedureScroll.set) self.procedure.pack(side=LEFT, fill=BOTH, expand=1) procedureScroll.config(command=self.procedure.yview) procedureScroll.pack(side=LEFT, fill=Y)
class windowFrame(Frame): def __init__(self, parent): self.Data = Data() self.getReciepList() Frame.__init__(self, parent) self.parent = parent self.recipeList = None # Listbox self.recipeName = None # Entry self.prepTime = None # Entry self.prepTimeUnit = None # OptionMenu self.cookTime = None # Entry self.cookTimeUnit = None # OptionMenu self.ingredientName = None # Entry self.ingredientQuantity = None # Entry self.ingredientUnit = None # OptionMenu self.ingredientList = None # Listbox self.procedure = None # Text self.recipes = [] self.ingredients = [] self.activeRecipeID = {"lst": None, "db": None} # (listID, dbID) self.activeIngredientID = {"lst": None, "db": None} # (listID, dbID) self.initUI() self.bind_all("<Control-w>", self.onExit) self.bind_all("<Control-s>", self.recipeSave) # display an error message to the user def msgError(self, error): print("error: " + error) showerror("ERROR!", error) # dispaly a warning to the user def msgWarning(self, warning): showwarning("Warning!", warning) # display caution message to user def msgCaution(self, caution): return askokcancel("Caution!", caution) # Get current ingredient selection from ingredient list def getIngredientSelection(self): if self.ingredients == []: self.msgWarning("No ingredient selected. Try loading a recipe.") return -1 else: return self.ingredientList.index(ACTIVE) # Get current recipe selection from recipe list def getRecipeSelection(self): if self.recipes == []: self.msgError("No recipes available.") return -1 else: selection = list(self.recipeList.curselection()) if selection == []: self.msgError("No recipe selected.") return -1 else: return selection # retrieve recipe list from the database def getReciepList(self): self.recipes = self.Data.dbGetRecipeList() # retrieve recipe info from the database by recipe ID def getRecipeInfo(self, recipeID): return self.Data.dbGetRecipeInfo(recipeID) # retrieve ingredient info from the database by ingredient ID def getIngredientInfo(self, ingredientID): return self.Data.dbGetIngredientInfo(ingredientID) # Populate the recipe list from a provided list of recipes def populateIngredientList(self, ingredients): self.ingredients = sorted(self.ingredients, key=itemgetter(-1)) self.ingredientList.delete(0, END) for ingredient in self.ingredients: ingredientName = str(ingredient[2]) ingredientQuantity = str(ingredient[3]) ingredientUnit = str(ingredient[4]) self.ingredientList.insert(END, ingredientQuantity + " " + ingredientUnit + " of " + ingredientName) # Populate the recipe list from a provided list of recipes def populateRecipeList(self, recipes): self.recipeList.delete(0, END) for recipe in [recipe[1] for recipe in recipes]: self.recipeList.insert(END, recipe) # save currently loaded ingredient info to database def ingredientSaveInfo(self): if self.activeIngredientID["lst"] == None: self.msgWarning("No ingredient is loaded.") else: print("Saving ingredient info") name = self.ingredientName.get() quantity = self.ingredientQuantity.get() unit = self.ingredientUnit.get() ingredient = self.ingredients[self.activeIngredientID["lst"]] print(ingredient) ingredient = (ingredient[0], ingredient[1], name, quantity, unit, ingredient[-1]) print(ingredient) self.ingredients[self.activeIngredientID["lst"]] = ingredient self.populateIngredientList(self.ingredients) # load active ingredient info into GUI elements def ingredientLoadInfo(self, ID=None): if ID == None: currentSelection = self.getIngredientSelection() if currentSelection == -1: return -1 else: self.activeIngredientID["lst"] = currentSelection self.activeIngredientID["db"] = self.ingredients[currentSelection][0] print("\n\nLoading ingredient info for ID " + str(self.activeIngredientID)) ingredient = self.ingredients[self.activeIngredientID["lst"]] elif ID >= 0: self.activeIngredientID["lst"] = ID self.activeIngredientID["db"] = self.ingredients[ID][0] ingredient = self.ingredients[self.activeIngredientID["lst"]] elif ID == -1: print("Clearing ingredient info...") self.activeIngredientID = {"lst": None, "db": None} ingredient = ["", "", "", "", ""] name = ingredient[2] quantity = ingredient[3] unit = ingredient[4] self.ingredientName.delete(0, END) self.ingredientName.insert(END, name) self.ingredientQuantity.delete(0, END) self.ingredientQuantity.insert(END, quantity) self.ingredientUnit.delete(0, END) self.ingredientUnit.insert(END, unit) # Move an ingredient further up in the ingredient list def ingredientMoveUp(self): currentSelection = self.getIngredientSelection() if currentSelection == -1: return -1 elif currentSelection > 0: if ( currentSelection == self.activeIngredientID["lst"] or currentSelection - 1 == self.activeIngredientID["lst"] ): if not self.msgCaution( "Reordering the actively loaded ingredient could cause duplicate and deleted entries when saving. Continue?" ): return print("ingredient %d up\n\n" % currentSelection) self.ingredients[currentSelection] = self.ingredients[currentSelection][0:-1] + ( self.ingredients[currentSelection][-1] - 1, ) self.ingredients[currentSelection - 1] = self.ingredients[currentSelection - 1][0:-1] + ( self.ingredients[currentSelection - 1][-1] + 1, ) self.populateIngredientList(self.ingredients) self.ingredientList.select_set(currentSelection - 1) self.ingredientList.event_generate("<<ListboxSelect>>") # Move an ingredient further down in the ingredient list def ingredientMoveDown(self): ##################################################### # Bug: when repeatedly pressing the down button, # # every press after the first switches the order of # # the first ingredient with the second ingredient. # ##################################################### currentSelection = self.getIngredientSelection() if currentSelection == -1: return -1 elif currentSelection < len(self.ingredients) - 1: if ( currentSelection == self.activeIngredientID["lst"] or currentSelection + 1 == self.activeIngredientID["lst"] ): if not self.msgCaution( "Reordering the actively loaded ingredient could cause duplicate and deleted entries when saving. Continue?" ): return print("ingredient %d down\n\n" % currentSelection) self.ingredients[currentSelection] = self.ingredients[currentSelection][0:-1] + ( self.ingredients[currentSelection][-1] + 1, ) self.ingredients[currentSelection + 1] = self.ingredients[currentSelection + 1][0:-1] + ( self.ingredients[currentSelection + 1][-1] - 1, ) self.populateIngredientList(self.ingredients) self.ingredientList.select_set(currentSelection + 1) self.ingredientList.event_generate("<<ListboxSelect>>") # Add an ingredient slot to the bottom of the list def ingredientAdd(self): if self.activeRecipeID["lst"] == None: self.msgWarning("No recipe loaded.") else: blankIngredient = (None, self.activeRecipeID["db"], "blank", "?", "?", len(self.ingredients)) self.ingredients.append(blankIngredient) self.populateIngredientList(self.ingredients) self.ingredientLoadInfo(len(self.ingredients) - 1) # Delete the currently selected ingredient def ingredientDelete(self): ####################################################### # BUG: when pressing the delete button several times, # # all but the first press just deletes the first # # ingredient in the list. # ####################################################### currentSelection = self.getIngredientSelection() if currentSelection == -1 or self.activeRecipeID["lst"] == None: return -1 elif currentSelection < len(self.ingredients) and currentSelection >= 0: print("remove ingredient %d\n\n" % currentSelection) del self.ingredients[currentSelection] for ingredient in range(currentSelection, len(self.ingredients)): self.ingredients[ingredient] = self.ingredients[ingredient][0:-1] + ( self.ingredients[ingredient][-1] - 1, ) self.populateIngredientList(self.ingredients) self.ingredientList.select_set(currentSelection) self.ingredientList.event_generate("<<ListboxSelect>>") print(self.ingredients) # Display help: about dialogue def helpAbout(self): print("Digital Cookbook v1.0 - Theodore Lindsey") aboutDialog = Toplevel() aboutDialog.geometry("200x100+300+300") aboutDialog.title("About Digital Cookbook") Message(aboutDialog, text="Digital Cookbook v1.0\nTheodore Lindsey").pack(side=TOP, fill=BOTH, expand=1) Button(aboutDialog, text="Ok", command=aboutDialog.destroy).pack(side=TOP) # Import recipe from XML file - need to implement def xmlImport(self): print("Importing XML file...") # add a recipe to the database and create a blank space for the recipe to go - need to implement def recipeAdd(self): print("Adding recipe...") # delete the currently selected recipe - need to implement def recipeDelete(self): recipeID = self.recipeList.curselection() print(recipeID) if len(recipeID) == 0: self.msgError("No recipes selected.") return elif len(recipeID) > 1: if not askokcancel("Caution!", "Are you sure you want to delete these %d recipes?" % len(recipeID)): return print("\nDeleting %d recipes..." % len(recipeID)) else: if not askokcancel("Caution!", "Are you sure you want to delete this recipe?"): return print("\nDeleting recipe %d..." % recipeID) blankrecipe = ((None, "", None, "", "", "", "", ""), []) self.recipeLoad(blankrecipe) # load currently selected recipe def recipeLoad(self, recipe=None): activeSelection = self.getRecipeSelection() if activeSelection == -1: return -1 elif len(activeSelection) > 1: self.msgError("Too many recipes selected.") return -1 else: if recipe == None: listID = activeSelection[0] self.activeRecipeID["lst"] = listID self.activeRecipeID["db"] = self.recipes[listID][0] print(self.activeRecipeID) recipe = self.getRecipeInfo(self.activeRecipeID["db"]) else: print("Clearing recipe info...") self.activeRecipeID = {"lst": None, "db": None} self.ingredientLoadInfo(-1) print(recipe) name = recipe[0][1] servings = recipe[0][2] prepTime = recipe[0][3] prepTimeUnits = recipe[0][4] cookTime = recipe[0][5] cookTimeUnits = recipe[0][6] procedure = recipe[0][7] self.ingredients = recipe[1] self.recipeName.delete(0, END) self.recipeName.insert(END, name) self.prepTime.delete(0, END) self.prepTime.insert(END, prepTime) self.cookTime.delete(0, END) self.cookTime.insert(END, cookTime) self.populateIngredientList(self.ingredients) self.procedure.delete(0.0, END) self.procedure.insert(END, procedure) # save changes to active recipe to database def recipeSave(self, event=""): print(self.activeRecipeID) if self.activeRecipeID["lst"] == None: self.msgError("No active recipe to save.") return -1 listID = self.activeRecipeID["lst"] dbID = self.activeRecipeID["db"] name = self.recipeName.get() servings = 0 # self.recipes[listID][2] prepTime = self.prepTime.get() prepUnit = None # self.prepTimeUnit.????() cookTime = self.cookTime.get() cookUnit = None # self.cookTimeUnit.????() procedure = self.procedure.get(0.0, END) recipeInfo = (dbID, name, servings, prepTime, prepUnit, cookTime, cookUnit, procedure) recipe = (recipeInfo, self.ingredients) self.recipes[listID] = (dbID, name) self.populateRecipeList(self.recipes) # quit the program def onExit(self, event=""): print("Quitting...") sys.exit(0) # Create the UI layout def initUI(self): self.parent.title("Digital Cookbook") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1, side=BOTTOM) # Establish menu bar # menubar = Menu(self.parent) self.parent.config(menu=menubar) # Add file menu # filemenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Import recipe from XML file", command=self.xmlImport) filemenu.add_command(label="Add blank recipe to database", command=self.recipeAdd) filemenu.add_command(label="Delete recipe from database", command=self.recipeDelete) filemenu.add_command(label="Load recipe", command=self.recipeLoad) filemenu.add_command(label="Save recipe to database", command=self.recipeSave, accelerator="Ctrl+S") filemenu.add_separator() filemenu.add_command(label="Exit", command=self.onExit, accelerator="Ctrl+W") # Add help menu # helpmenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Help", menu=helpmenu) helpmenu.add_command(label="About...", command=self.helpAbout) # Establish toolbar # frameToolbar = Frame(self.parent) # , relief=RAISED, borderwidth=1) frameToolbar.pack(side=TOP, fill=X) # Add buttons to toolbar # buffer = 2 buttonspaceing = 100 buttonwidth = 12 buttonheight = 30 bImportXML = Button(frameToolbar, text="Import XML", command=self.xmlImport, width=buttonwidth) bImportXML.pack(side=LEFT, padx=buffer, pady=buffer) bAddRecipe = Button(frameToolbar, text="Add Recipe", command=self.recipeAdd, width=buttonwidth) bAddRecipe.pack(side=LEFT, padx=buffer, pady=buffer) bDeleteRecipe = Button(frameToolbar, text="Delete Recipe", command=self.recipeDelete, width=buttonwidth) bDeleteRecipe.pack(side=LEFT, padx=buffer, pady=buffer) bEditRecipe = Button(frameToolbar, text="Load Recipe", command=self.recipeLoad, width=buttonwidth) bEditRecipe.pack(side=LEFT, padx=buffer, pady=buffer) bSaveRecipe = Button(frameToolbar, text="Save Recipe", command=self.recipeSave, width=buttonwidth) bSaveRecipe.pack(side=LEFT, padx=buffer, pady=buffer) # Recipe list section frameRecipeList = Frame(self, borderwidth=1, width=200) frameRecipeList.pack_propagate(0) frameRecipeList.pack(side=LEFT, fill=Y) Label(frameRecipeList, text="Recipe List").pack() # Category option menu default = StringVar(frameRecipeList) default.set("----") recipeCatagories = OptionMenu(frameRecipeList, default, "----", "None", "Cat 1", "Cat 2", "Cat 3") recipeCatagories.pack(side=TOP, fill=X) # Filter Frame frameFilter = Frame(frameRecipeList, relief=RAISED, borderwidth=1, width=200) frameFilter.pack(side=TOP, fill=X) Label(frameFilter, text="Filter...").pack() # Filter text filterText = Entry(frameFilter) filterText.pack_propagate(0) filterText.pack(side=LEFT, fill=X) # Filter Button filterButton = Button(frameFilter, text="Go", command=self.placeholder) filterButton.pack_propagate(0) filterButton.pack(side=RIGHT) # Recipe Box Frame frameRecipeBox = Frame(frameRecipeList, relief=RAISED, borderwidth=1) frameRecipeBox.pack(side=TOP, fill=BOTH, expand=1) # ==== Recipe List box ==== recipeListScroll = Scrollbar(frameRecipeBox, orient=VERTICAL) self.recipeList = Listbox(frameRecipeBox, selectmode=EXTENDED, yscrollcommand=recipeListScroll.set) self.recipeList.pack(side=LEFT, fill=BOTH, expand=1) recipeListScroll.config(command=self.recipeList.yview) recipeListScroll.pack(side=RIGHT, fill=Y) self.getReciepList() self.populateRecipeList(self.recipes) # Spacer frameSpacer1 = Frame(self, borderwidth=1, width=10) frameSpacer1.pack_propagate(0) frameSpacer1.pack(side=LEFT, fill=Y) # Recipe info section frameRecipeInfo = Frame(self, borderwidth=1, width=200) frameRecipeInfo.pack_propagate(0) frameRecipeInfo.pack(side=LEFT, fill=Y) # Recipe name Label(frameRecipeInfo, text="Recipe Name:", anchor=E, justify=LEFT).pack() self.recipeName = Entry(frameRecipeInfo) self.recipeName.pack(side=TOP, fill=X) # Prep Time framePrepTime = Frame(frameRecipeInfo) framePrepTime.pack(side=TOP, fill=X) Label(framePrepTime, text="Prep Time:", anchor=E, justify=LEFT).pack() self.prepTime = Entry(framePrepTime) self.prepTime.pack(side=LEFT, fill=X) default = StringVar(framePrepTime) default.set("----") self.prepTimeUnit = OptionMenu(framePrepTime, default, "----", "Min", "Hr") self.prepTimeUnit.pack(side=RIGHT, fill=X) # Cook Time frameCookTime = Frame(frameRecipeInfo) frameCookTime.pack(side=TOP, fill=X) Label(frameCookTime, text="Cook Time:", anchor=E, justify=LEFT).pack() self.cookTime = Entry(frameCookTime) self.cookTime.pack(side=LEFT, fill=X) default = StringVar(frameCookTime) default.set("----") self.cookTimeUnit = OptionMenu(frameCookTime, default, "----", "Min", "Hr") self.cookTimeUnit.pack(side=RIGHT, fill=X) # Spacer frameSpacer2 = Frame(self, borderwidth=1, width=10) frameSpacer2.pack_propagate(0) frameSpacer2.pack(side=LEFT, fill=Y) # Ingredient List frameIngredients = Frame(self, borderwidth=1, width=300) frameIngredients.pack_propagate(0) frameIngredients.pack(side=LEFT, fill=Y) Label(frameIngredients, text="Ingredients").pack() # Ingredient Name self.ingredientName = Entry(frameIngredients) self.ingredientName.pack(side=TOP, fill=X) # Ingredient info frameIngredientQuantity = Frame(frameIngredients) frameIngredientQuantity.pack(side=TOP, fill=X) Label(frameIngredientQuantity, text="Ingredient Quantity (value, unit):", anchor=E, justify=LEFT).pack() self.ingredientQuantity = Entry(frameIngredientQuantity) self.ingredientQuantity.pack(side=LEFT, fill=X, expand=1) self.ingredientUnit = Entry(frameIngredientQuantity, width=20) self.ingredientUnit.pack_propagate(0) self.ingredientUnit.pack(side=RIGHT, fill=X) # Spacer frameSpacer3 = Frame(frameIngredients, height=10) frameSpacer3.pack_propagate(0) frameSpacer3.pack(side=TOP, fill=X) # Ingredient List buttons frameIngredientButtons = Frame(frameIngredients) frameIngredientButtons.pack(side=TOP, fill=X) ingredientAdd = Button(frameIngredientButtons, text="+", command=self.ingredientAdd, width=3) ingredientAdd.pack(side=LEFT) ingredientDel = Button(frameIngredientButtons, text="-", command=self.ingredientDelete, width=3) ingredientDel.pack(side=LEFT) ingredientUp = Button(frameIngredientButtons, text=u"\u25B2", command=self.ingredientMoveUp, width=3) ingredientUp.pack(side=LEFT) ingredientDwn = Button(frameIngredientButtons, text=u"\u25BC", command=self.ingredientMoveDown, width=3) ingredientDwn.pack(side=LEFT) ingredientLoad = Button(frameIngredientButtons, text="Load", command=self.ingredientLoadInfo) ingredientLoad.pack(side=LEFT) ingredientSave = Button(frameIngredientButtons, text="Save", command=self.ingredientSaveInfo) ingredientSave.pack(side=LEFT) # Ingredient List Box Frame frameIngredientList = Frame(frameIngredients, relief=RAISED, borderwidth=1) frameIngredientList.pack(side=TOP, fill=BOTH, expand=1) # Ingredient List box ingredientListScroll = Scrollbar(frameIngredientList, orient=VERTICAL) self.ingredientList = Listbox( frameIngredientList, selectmode=SINGLE, yscrollcommand=ingredientListScroll.set ) # Set selectmode=SINGLE???? self.ingredientList.pack(side=LEFT, fill=BOTH, expand=1) ingredientListScroll.config(command=self.ingredientList.yview) ingredientListScroll.pack(side=RIGHT, fill=Y) # Spacer frameSpacer4 = Frame(self, borderwidth=1, width=10) frameSpacer4.pack_propagate(0) frameSpacer4.pack(side=LEFT, fill=Y) # Recipe Procedure frameProcedure = Frame(self, borderwidth=1) frameProcedure.pack(side=LEFT, fill=BOTH, expand=1) Label(frameProcedure, text="Procedure", anchor=E, justify=LEFT).pack(side=TOP) procedureScroll = Scrollbar(frameProcedure, orient=VERTICAL) self.procedure = Text(frameProcedure, maxundo=30, undo=1, wrap=WORD, yscrollcommand=procedureScroll.set) self.procedure.pack(side=LEFT, fill=BOTH, expand=1) procedureScroll.config(command=self.procedure.yview) procedureScroll.pack(side=LEFT, fill=Y) # placeholder function for unimplemented UI elements def placeholder(self): print("Coming soon!")
class GUI(Frame): def __init__(self, parent): Frame.__init__(self, parent, name="frame") self.parent = parent self.initUI() def getFilePath(self): currdir = os.getcwd() tempdir = filedialog.askdirectory(master=self, initialdir=currdir, title='Please select a directory') self.ent1.delete(0, END) self.ent1.insert(0, tempdir) def initUI(self): self.parent.title("backup client") self.pack(fill=BOTH, expand=True) self.grid_columnconfigure(6, weight=1) self.grid_rowconfigure(9, weight=1) # display config info in txt box f1 = Frame(self) lblConfig = Label(f1, text="Config Settings:") txtConfig = Text(f1, height=4, width=40) s3Host = config['S3']['s3.server'] msg = "s3.server: " + s3Host + '\n' encPass = config['DEFAULT']['file.encryption_password'] msg = msg + "encryption_pass: "******"s3.access_key: " + s3AccessKey + '\n' txtConfig.insert('end', msg) txtConfig.configure(state='disabled') f1.grid(row=0, column=0, sticky="nsew") lblConfig.pack(side="top", anchor="w", padx=10) txtConfig.pack(side="top", anchor="w", padx=10) # run timer fTimer = Frame(self) lbl3 = Label(fTimer, text="Run Time: ") self.lbl4 = Label(fTimer, text="N/A") fTimer.grid(row=0, column=1, sticky=W, padx=20, pady=20) lbl3.pack(side="top") self.lbl4.pack(side="top") # backup / restore radio button fRadio = Frame(self) self.br = StringVar(fRadio, "backup") lblJobType = Label(fRadio, text="Job Type:") self.rbBackup = Radiobutton(fRadio, text="backup", variable=self.br, value="backup", command=self.onSelectRadio) self.rbRestore = Radiobutton(fRadio, text="restore", variable=self.br, value="restore", command=self.onSelectRadio) fRadio.grid(row=0, column=2, sticky=W) lblJobType.pack(side="top") self.rbBackup.pack(side="left") self.rbRestore.pack(side="left") # horizontal line on this row sp1 = Separator(self, orient=HORIZONTAL) sp1.grid(row=3, column=0, columnspan=6, sticky='ew', padx=10, pady=20) # inputDir entry with FileDialog f2 = Frame(self) lblSrc = Label(f2, text="SOURCE INFO") self.lbl1 = Label(f2, text="Src Directory:") self.ent1 = Entry(f2, width=40) b1 = Button(f2, text="Browse", width=8, command=self.getFilePath) f2.grid(row=4, column=0, sticky=W, padx=10, pady=10) lblSrc.pack(side="top") self.lbl1.pack(side="top", anchor=W) self.ent1.pack(side="left", anchor=W) b1.pack(side="left", anchor=E) # vertical separator sp3 = Separator(self, orient=VERTICAL) sp3.grid(row=4, column=1, sticky='ns', padx=20, pady=10, rowspan=2) # s3 bucket selection fBucket = Frame(self) lblTgt = Label(fBucket, text="TARGET INFO") lblBucket = Label(fBucket, text="S3 bucket:") buckets = backup_util.getBucketList(config) options = list() self.selectedBucket = StringVar(fBucket) for bucket in buckets: options.append(bucket.name) self.bucketMenu = OptionMenu(fBucket, self.selectedBucket, *options) self.bucketMenu.config(width=30) fBucket.grid(row=4, column=2, sticky=W, padx=10, pady=10) lblTgt.pack(side="top") lblBucket.pack(side="top", anchor=W) self.bucketMenu.pack(side="top") # s3 folder entry f3 = Frame(self) lblFolder = Label(f3, text="S3 Folder:") self.ent2 = Entry(f3, width=30) f3.grid(row=5, column=2, sticky=W, padx=10) lblFolder.pack(side="top", anchor=W) self.ent2.pack(side="top", anchor=W) # horizontal line on this row sp2 = Separator(self, orient=HORIZONTAL) sp2.grid(row=6, column=0, columnspan=6, sticky='ew', padx=10, pady=20) # buttons (backup/stop/reset/restore) fButtons = Frame(self) self.backupBtn = Button(fButtons, text="Backup", command=self.onBackup) self.restoreBtn = Button(fButtons, text="Restore", command=self.onRestore) self.stopBtn = Button(fButtons, text="Stop", command=self.onStop) self.resetBtn = Button(fButtons, text="Reset", command=self.onResetBtn) fButtons.grid(row=7, column=0, sticky=W, padx=10, pady=10) self.backupBtn.pack(side="left") self.restoreBtn.pack(side="left") self.restoreBtn.config(state=DISABLED) self.stopBtn.pack(side="left") self.resetBtn.pack(side="left") # progress bar self.pbar = Progressbar(self, mode='indeterminate') self.pbar.grid(row=7, column=1, columnspan=1, sticky=W + E) # a couple of checkbox items fchkbox = Frame(self) self.quitOnEnd = IntVar(fchkbox, 0) self.chkboxQuitOnEnd = Checkbutton(fchkbox, text="quit upon completion", variable=self.quitOnEnd, command=self.onSelectedQoe) self.doEncrypt = IntVar(fchkbox, 1) self.chkboxEncrypt = Checkbutton(fchkbox, text="encrypt data", variable=self.doEncrypt, command=self.onCheckEncrypt) fchkbox.grid(row=7, column=2, sticky=W, padx=10) self.chkboxQuitOnEnd.pack(side="top", anchor="w") self.chkboxEncrypt.pack(side="top", anchor="w") # scrolled txt f4 = Frame(self) f4.grid_columnconfigure(1, weight=1) f4.grid(row=8, column=0, columnspan=7, rowspan=5, padx=10, pady=10, sticky=(N, E, S, W)) lblStatus = Label(f4, text="//Job Status//") self.txt = scrolledtext.ScrolledText(f4) lblStatus.pack(side="top") self.txt.pack(side="top", fill=BOTH, expand=True) # check to make sure we could list the buckets if (len(buckets) == 0): messagebox.showerror(title="bucket error", message="could not list buckets") def onCheckEncrypt(self): print("doEncrypt: [{}]".format(self.doEncrypt.get())) def onSelectedQoe(self): print("quitOnEnd: [{}]".format(self.quitOnEnd.get())) def onSelectRadio(self): # set value of lbl for inputDir if (self.br.get() == "restore"): self.lbl1.config(text="Restore Directory:") self.backupBtn.config(state=DISABLED) self.restoreBtn.config(state=NORMAL) else: self.lbl1.config(text="Input Directory:") self.backupBtn.config(state=NORMAL) self.restoreBtn.config(state=DISABLED) # # start button clicked # def onBackup(self): backup_util.stopFlag = False # check to make sure we have values if (not self.ent1.get()): messagebox.showerror("Error", "inputDir is empty") return if (not self.ent2.get()): messagebox.showerror("Error", "s3Folder is empty") return inputDir = str(self.ent1.get()) folder = str(self.ent2.get()) # start timer self.starttime = timeit.default_timer() self.backupBtn.config(state=DISABLED) self.txt.delete("1.0", END) useQ = True self.t = ThreadedBackupTask(inputDir, folder, q, config, logger, useQ, self.doEncrypt.get(), self.selectedBucket.get()) self.t.start() # start progress bar self.pbar.start(DELAY2) # look for values self.after(DELAY1, self.onGetValue) # # restore button clicked # def onRestore(self): backup_util.stopFlag = False # check to see if we have input data if (not self.ent1.get()): messagebox.showerror("Error", "inputDir is empty") return if (not self.ent2.get()): messagebox.showerror("Error", "s3Folder is empty") return inputDir = str(self.ent1.get()) folder = str(self.ent2.get()) # start timer self.starttime = timeit.default_timer() self.restoreBtn.config(state=DISABLED) self.backupBtn.config(state=DISABLED) self.txt.delete("1.0", END) useQ = True self.t = ThreadedRestoreTask(inputDir, folder, q, config, logger, useQ, self.selectedBucket.get()) self.t.start() # start progress bar & look for values self.pbar.start(DELAY2) self.after(DELAY1, self.onGetValue) def onStop(self): backup_util.stopFlag = True print("set stop flag: {}".format(str())) self.t.join() self.onGetValue() def onResetBtn(self): self.initUI() # check for messages on q # process msgs - increment progress bar def onGetValue(self): # get some timing self.checktime = timeit.default_timer() runTime = self.checktime - self.starttime minutes = int(runTime / 60) seconds = round(runTime % 60, 0) msg = "{}m {}s".format(minutes, seconds) self.lbl4.config(text=msg) try: while (q.qsize() > 0): msg = q.get(0) lines = int(self.txt.index('end').split('.')[0]) - 1 if (lines > 500): self.txt.delete('1.0', '2.0') self.txt.insert('end', msg) self.txt.insert('end', "\n") self.txt.yview('end') except Empty: print("queue is empty") # if process is still alive - set timer and go again if (self.t.is_alive()): self.after(DELAY1, self.onGetValue) return else: self.pbar.stop() self.backupBtn.config(state=NORMAL) self.restoreBtn.config(state=DISABLED) if (self.quitOnEnd.get() == 1): sys.exit(0)
class Grid(): def __init__(self, master): # Top menu self.menu = Frame(master) self.menu.pack(fill='both', expand=True) self.save_button = Button(master, text='Save', command=self.save_grid) self.save_button.pack(in_=self.menu, side='right') self.load_button = Button(master, text='Load', command=self.load_grid) self.load_button.pack(in_=self.menu, side='right') # Place the canvas self.canvas = Canvas(master, width=MAP_CELL_SIZE * MAP_SIZE, height=MAP_CELL_SIZE * MAP_SIZE) self.grid = [[Cell(self.canvas, row, col) for col in range(MAP_SIZE)] for row in range(MAP_SIZE)] self.plant_grid = [[None for col in range(MAP_SIZE)] for row in range(MAP_SIZE)] self.canvas.bind("<Button-1>", self.event_set_cell) self.canvas.bind("<B1-Motion>", self.event_set_cell) self.canvas.pack() # Tools self.tools = Frame(master) self.tools.pack(fill='both', expand=True) self.fill_button = Button(self.tools, text="Fill", command=self.fill_grid) self.fill_button.pack(side='left') types = list(list_draw_types()) self.draw_type = StringVar(master) self.draw_type.set(DEFAULT_CELL_TYPE) self.dd_draw_type = OptionMenu(self.tools, self.draw_type, DEFAULT_CELL_TYPE, *types) self.dd_draw_type.pack(side='left') self.symetry = StringVar(master) self.symetry.set(SYMETRY[0]) self.dd_symetry = OptionMenu(self.tools, self.symetry, SYMETRY[0], *SYMETRY) self.dd_symetry.pack(side='right') self.draw() def draw(self): for row in self.grid: for cell in row: cell.draw() self.display_plants() #for elem in self.plant_list: # Cell(self.canvas, elem[0], elem[1]) # cell.set(elem[3]) def display_plants(self): for row in self.plant_grid: for plant in row: if plant: plant.draw() # ____ _ _ # / ___|___| | |___ # | | / _ \ | / __| # | |__| __/ | \__ \ # \____\___|_|_|___/ # @staticmethod def inside_grid(row, col): return 0 <= row < MAP_SIZE and 0 <= col < MAP_SIZE def set_cell(self, row, col): #print(self.draw_type.get()) #print('plante' in self.draw_type.get()) if 'plante' in self.draw_type.get(): if not self.plant_grid[row][col]: self.plant_grid[row][col] = Plante(self.canvas, col, row, self.draw_type.get()) else: self.plant_grid[row][col] = None else: self.grid[row][col].set(self.draw_type.get()) opp = get_opp((row, col), self.symetry.get()) if opp is not None: if 'plante' in self.draw_type.get(): if not self.plant_grid[opp[0]][opp[1]]: self.plant_grid[opp[0]][opp[1]] = Plante( self.canvas, opp[0], opp[1], self.draw_type.get()) else: self.plant_grid[opp[0]][opp[1]] = None else: self.grid[opp[0]][opp[1]].set(self.draw_type.get()) self.display_plants() def fill_grid(self): for row in self.grid: for cell in row: cell.set(self.draw_type.get()) # _____ _ _ _ _ _ _ # | ____|_ _____ _ __ | |_ | | | | __ _ _ __ __| | (_)_ __ __ _ # | _| \ \ / / _ \ '_ \| __| | |_| |/ _` | '_ \ / _` | | | '_ \ / _` | # | |___ \ V / __/ | | | |_ | _ | (_| | | | | (_| | | | | | | (_| | # |_____| \_/ \___|_| |_|\__| |_| |_|\__,_|_| |_|\__,_|_|_|_| |_|\__, | # |___/ def event_set_cell(self, event): row = int(event.y / MAP_CELL_SIZE) col = int(event.x / MAP_CELL_SIZE) if self.inside_grid(row, col): self.set_cell(row, col) # ____ _ _ _ _ _ # / ___| ___ _ __(_) __ _| (_)______ _| |_(_) ___ _ __ # \___ \ / _ \ '__| |/ _` | | |_ / _` | __| |/ _ \| '_ \ # ___) | __/ | | | (_| | | |/ / (_| | |_| | (_) | | | | # |____/ \___|_| |_|\__,_|_|_/___\__,_|\__|_|\___/|_| |_| # def save_grid(self): filename = asksaveasfilename() if not filename: return with open(filename, 'w+') as f: # Init raw and list outputs datas raw_output = dict() list_output = dict() for name, conf in CELL_TYPES.items(): if conf['serialize']['method'] == 'raw': default_data = [0, 0] + ([0] * len(conf['extra']) if 'extra' in conf else []) raw_output[conf['serialize']['order']] = default_data elif conf['serialize']['method'] == 'list': list_output[conf['serialize']['order']] = [] # Serialize the grid and catch raw and list outputs for row, row_data in enumerate(self.grid): for col, cell in enumerate(row_data): conf = get_type_conf(cell.cell_type) data = [row, col] # Add extra infos if necessary if 'extra' in conf: data += [ conf['default'][field] for field in conf['extra'] ] # Serialization of the grid if 'ascii' in conf['serialize']: f.write(conf['serialize']['ascii']) elif 'ascii_space' in conf['serialize']: f.write(conf['serialize']['ascii_space']) if not col == MAP_SIZE - 1: f.write(' ') f.write('\n') # Serialize the grid and catch raw and list outputs for row, row_data in enumerate(self.plant_grid): for col, plant in enumerate(row_data): if not plant: continue conf = get_type_conf(plant.type) data = [col, row] # Add extra infos if necessary if 'extra' in conf: data += [ conf['default'][field] for field in conf['extra'] ] # Register for raw and list outputs if conf['serialize']['method'] == 'raw': raw_output[conf['serialize']['order']] = data elif conf['serialize']['method'] == 'list': list_output[conf['serialize']['order']].append(data) # Serialize raw and list outputs order_keys = sorted( list(raw_output.keys()) + list(list_output.keys())) for order in order_keys: if order in raw_output: f.write('{}\n'.format(' '.join(map(str, raw_output[order])))) else: f.write('{}\n'.format(len(list_output[order]))) for item in list_output[order]: f.write('{}\n'.format(' '.join(map(str, item)))) def load_grid(self, filename=None): if filename is None: filename = askopenfilename() # Index of symbols to consider in the grid from_ascii = { conf['serialize']['ascii']: name for name, conf in CELL_TYPES.items() if conf['serialize']['method'] == 'ascii' } # Ascii separated by space from_ascii_space = { conf['serialize']['ascii_space']: name for name, conf in CELL_TYPES.items() if conf['serialize']['method'] == 'ascii_space' } # Ordered list of items to catch after reading the grid from_raw_or_list = [(name, conf['serialize']['order']) for name, conf in CELL_TYPES.items() if conf['serialize']['method'] in ['raw', 'list']] from_raw_or_list.sort(key=lambda x: x[1]) from_raw_or_list = map(lambda x: x[0], from_raw_or_list) # Need to match exactly a preset when 'extra' is specified, create # an index to get which preset is used fullname_index = dict() for full_name in list_draw_types(): if ':' in full_name: conf = get_type_conf(full_name) parent_name, preset_name = full_name.split(':') key = tuple( [parent_name] + [conf['default'][field] for field in conf['extra']]) fullname_index[key] = full_name else: fullname_index[(full_name, )] = full_name with open(filename, 'r') as f: # Read the grid for row in range(MAP_SIZE): if bool(from_ascii): for col, char in enumerate(f.readline()): if self.inside_grid(row, col) and char in from_ascii: self.grid[row][col].set(from_ascii[char]) elif bool(from_ascii_space): chars = f.readline().rstrip().split(' ') for col, char in enumerate(chars): #print(col,char,self.inside_grid(row, col)) if self.inside_grid(row, col) and char in from_ascii_space: self.grid[row][col].set(from_ascii_space[char]) # Read raw and list infos for name in from_raw_or_list: conf = CELL_TYPES[name] if conf['serialize']['method'] == 'raw': row, col, *extra = map(int, f.readline().split(' ')) self.grid[row][col].set(name) elif conf['serialize']['method'] == 'list': n = int(f.readline()) for _ in range(n): if 'plante' in name: values = list(map(int, f.readline().split(' '))) row, col = values[0:2] vie, force, elegance = values[2:5] type = "" if vie >= 100: type = "normal" elif force >= 100: type = "beast" else: type = "beauty" type_plant = name + ":" + type self.plant_grid[row][col] = Plante( self.canvas, col, row, type_plant) self.draw()
progress_bar.after(100, poller) upload_process = Process(target=up.upload_hex) upload_process.start() popup.mainloop() if upload_process.exitcode: popup_notification("Uploader error!", "Error!").destroy() if upload_timeout: popup_notification("Upload timed out", "Error!").destroy() popup.destroy() if __name__ == "__main__": multiprocessing.freeze_support() root = Tk() root.title("Firmware Updater") selected_board = StringVar() board_list = {board.name: board for board in boards.boardlist} board_menu = OptionMenu(root, selected_board, "Pinguino 4550", *board_list.keys()) board_menu.pack() load_button = Button(root, text="Load firmware", command=load_firmware) load_button.pack() upload_button = Button(root, text="Upload firmware", command=upload_firmware) upload_button.pack() root.mainloop()