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()
def _addNeueMahlzeitFrame(self): self.fr_neue_mz = Frame(self.fr_mahlzeit) self.fr_neue_mz.grid_rowconfigure(2, weight=1) self.fr_neue_mz.grid(row=0, column=1, sticky="WSNE") lbl_name = Label(self.fr_neue_mz, text="Name:") lbl_name.grid(row=0, column=0, sticky="NW") self.en_name = Entry(self.fr_neue_mz) self.en_name.grid(row=0, column=1, columnspan=2, sticky="WNE") lbl_zutat = Label(self.fr_neue_mz, text="Zutaten:") lbl_zutat.grid(row=1, column=0, sticky="NW") self.lb_zutat = Listbox(self.fr_neue_mz) sb_zutat = Scrollbar(self.lb_zutat, orient=VERTICAL) self.lb_zutat.configure(yscrollcommand=sb_zutat.set) sb_zutat.configure(command=self.lb_zutat.yview) sb_zutat.pack(side="right", fill="both") self.lb_zutat.grid(row=2, column=0, columnspan=3, sticky="NWSE") self.var_zutat = StringVar(self.fr_neue_mz) self.opt_zutat = OptionMenu(self.fr_neue_mz, self.var_zutat, "Auswahl") self.opt_zutat.grid(row=3, column=0) self.en_menge = Entry(self.fr_neue_mz) self.en_menge.grid(row=3, column=1) self.btn_mahlzeit_hinzu = Button(self.fr_neue_mz, text="Hinzu") self.btn_mahlzeit_hinzu.grid(row=3, column=2, sticky="E")
def __init__(self, master=None): # Inherit from frame Frame.__init__(self, master) self.master = master self.queue = queue.Queue() # String vars self.directory = StringVar() self.status = StringVar() self.language = StringVar() self.language.set('EN') self.status.set("Please choose a folder") # Pseudo booleans self.check_flag = IntVar() self.check_flag.set(1) self.files = [] # Get languages try: self.languages = SubtitleDownloader.get_languages() # First element must be null, because tkinter makes no sense self.languages.insert(0, None) except Exception as e: msg = "Error when fetching languages, defaulting to English\n" \ + str(e) messagebox.showerror("Connection error", msg) self.languages = ['en'] # Create widgets # The "important" widgets needed later self.status_label = Label(self.master, textvariable=self.status) self.progress_bar = ttk.Progressbar(self.master, orient="horizontal", mode="determinate", length=620) self.file_area = Frame(self.master) self.folder_fame = Frame(self.master) self.button_frame = Frame(self.master) self.language_selector = OptionMenu(self.button_frame, self.language, *self.languages) self.canvas = Canvas(self.file_area, borderwidth=0, background=COLORS['grey'], width=600, height=400) self.file_frame = Frame(self.canvas) self.create_widgets()
class Main(Frame): REMOTE_UPDATE_URL = "http://www.aiquimist.com/update/parameters.json" data = None shouldUpdate = False snapshot_dir = "snapshots" canvas = None capture = None photo = None delay = 15 def __init__(self, parent=None): super().__init__(parent) self.pack(side=LEFT, fill=BOTH, expand=True) self.columnconfigure(0, weight=1) self.rowconfigure(1, weight=1) self.bind("<configure>", self.on_window_resize()) self.master.protocol("WM_DELETE_WINDOW", self.on_window_close) style = AppStyle() # Read application settings. self.data = read_settings() # Top frame styles. style.configure("TOP.TFrame") # Bottom frame styles. style.configure("BOT.TFrame") # Button styles. style.configure("TOP.TMenubutton", padding=13) top_frame = Frame(self, padding=10, style="TOP.TFrame") top_frame.grid(row=0, column=0, sticky="ew") top_frame.columnconfigure(0, weight=1) top_frame.columnconfigure(7, weight=1) cams_list = self.get_cams_list() self.selected_camera_var = StringVar() self.selected_camera_var.trace('w', self.on_camera_option_select) self.cameras_option = OptionMenu(top_frame, self.selected_camera_var, None, *cams_list, command=self.on_camera_option_select, style="TOP.TMenubutton") self.cameras_option.grid(row=0, column=1, padx=[0, 10]) self._biometry_image = PhotoImage(file="resources/biometrical.gif") biometry_button = Button(top_frame, image=self._biometry_image, compound=LEFT, text="Recognize", command=self.on_recognize_button_click) biometry_button.grid(row=0, column=2, padx=[0, 10]) self._open_image = PhotoImage(file="resources/folder_open.gif") open_button = Button(top_frame, image=self._open_image, compound=LEFT, text="Open", command=self.on_open_button_click) open_button.grid(row=0, column=3, padx=[0, 10]) self._config_image = PhotoImage(file="resources/config.gif") config_button = Button(top_frame, image=self._config_image, compound=LEFT, text="Config", command=self.on_config_button_click) config_button.grid(row=0, column=4, padx=[0, 10]) self._update_image = PhotoImage(file="resources/download.gif") update_button = Button(top_frame, image=self._update_image, compound=LEFT, text="Update", command=self.on_update_button_click) update_button.grid(row=0, column=5, padx=[0, 10]) self._close_image = PhotoImage(file="resources/close.gif") close_button = Button(top_frame, image=self._close_image, compound=LEFT, text="Close", command=self.on_window_close) close_button.grid(row=0, column=6, padx=[0, 10]) bottom_frame = Frame(self, padding=10, style="BOT.TFrame", relief=SUNKEN) bottom_frame.grid(row=1, column=0, padx=10, pady=[0, 10], sticky="nsew") self.canvas = Canvas(bottom_frame, bg="black") self.canvas.pack(fill=BOTH, expand=True) # Set the default camera. self.selected_camera_var.set(cams_list[0]) def get_cams_list(self): cams = [] # Load cameras section for cam in self.data["cameras"]: cams.append(cam) # Return the sorted list return sorted(cams) def on_window_close(self): self.shouldUpdate = False self.master.quit() def on_window_resize(self): if self.canvas is not None: self.canvas.configure(relx=0.5, rely=0.5, anchor=CENTER) def on_camera_option_select(self, *args): # Delete the existing capture object. if self.capture is not None: del self.capture source = self.data["cameras"][self.selected_camera_var.get()] self.init_video(source) def init_video(self, source): # Convert source to integer if numeric. if source.isnumeric(): source = int(source) try: self.capture = VideoCapture(video_source=source, snapshot_dir=self.snapshot_dir) except ValueError as e: msg = "Couldn't open the stream: {0}".format(str(e)) logging.critical(msg) messagebox.showerror("Error Opening Stream", msg) self.canvas.delete("all") return self.shouldUpdate = True while self.shouldUpdate: self.master.after(self.delay, self.update_canvas()) def update_canvas(self): if self.capture is not None: # Force update values. self.canvas.update() can_width = self.canvas.winfo_width() can_height = self.canvas.winfo_height() # Get a frame from the video source. try: ret, frame = self.capture.get_frame(can_width, can_height) if ret: self.photo = PhotoImage(image=fromarray(frame)) self.canvas.create_image(can_width / 2, can_height / 2, image=self.photo) except Exception as e: self.shouldUpdate = False def on_recognize_button_click(self): ret = self.capture.take_snapshot() if ret: messagebox.showinfo("Image Capture", "Snapshot saved!") else: messagebox.showerror("Image Capture", "Failed to save snapshot.") def on_open_button_click(self): open_file(self.snapshot_dir) def on_config_button_click(self): child = Toplevel(self) child.title("Config") child.geometry("400x235") center_window(child) child.transient(self) child.resizable(False, False) child.grab_set() Config(child) self.wait_window(child) # Read the new settings. self.data = read_settings() def on_update_button_click(self): try: opener = URLopener() opener.retrieve(self.REMOTE_UPDATE_URL, "resources/parameters.json") # Read the new settings. self.data = read_settings() messagebox.showinfo( "Settings Update", "Settings successfully updated from the server.") except Exception as e: logging.critical( "Couldn't open the remote settings file: {0}".format(str(e))) messagebox.showerror("Couldn't Update Settings", "Couldn't open the remote settings file.")
def __init__(self, tab_control, expense_controller, user_controller, username): """Initializes statistics tab with all visual elements""" self.statistics_tab = ttk.Frame(tab_control) tab_control.add(self.statistics_tab, text='Statistics') self.expense_controller = expense_controller self.user_controller = user_controller self.username = username self.dateformat_menu = StringVar() self.start_date = StringVar() self.end_date = StringVar() Label(self.statistics_tab, text='Graph settings', font='Helvetica 16 bold').grid(row=0, column=0, padx=15, pady=15, sticky='w') Label(self.statistics_tab, text="Show expenses").grid(row=1, column=0, padx=(15, 0), sticky='w') option_list_format = ['daily', 'weekly', 'monthly', 'yearly'] OptionMenu(self.statistics_tab, self.dateformat_menu, option_list_format[2], *option_list_format)\ .grid(row=1, column=1, sticky='w') self.radio_btn_selection = IntVar( value=2 ) # has to be part of self, otherwise preselection doesn't work Radiobutton(self.statistics_tab, text='Select period:', variable=self.radio_btn_selection, value=1)\ .grid(row=2, column=0, padx=(15, 0), sticky='w') DateEntry(self.statistics_tab, width=9, textvariable=self.start_date, date_pattern='dd/MM/yyyy')\ .grid(row=2, column=1, sticky='w') Label(self.statistics_tab, text='to').grid(row=2, column=2, sticky='w') DateEntry(self.statistics_tab, width=9, textvariable=self.end_date, date_pattern='dd/MM/yyyy')\ .grid(row=2, column=3, sticky='w') Radiobutton(self.statistics_tab, text='Entire period', variable=self.radio_btn_selection, value=2) \ .grid(row=3, column=0, padx=(15, 0), sticky='w') Button(self.statistics_tab, text="Update graphs", command=self.display_graph).grid(row=4, column=0, padx=(15, 0), pady=10, sticky='w') # FIRST FIGURE: Barchart self.fig1, self.ax1 = plt.subplots(figsize=(6, 3), dpi=100) self.canvas1 = FigureCanvasTkAgg(self.fig1, master=self.statistics_tab) self.canvas1.get_tk_widget().grid(row=0, column=4, rowspan=8, padx=15, pady=(15, 0)) self.toolbarFrame = Frame(master=self.statistics_tab) self.toolbarFrame.grid(row=8, column=4) self.toolbar = NavigationToolbar2Tk(self.canvas1, self.toolbarFrame) # SECOND FIGURE: Barchart self.fig2, self.ax2 = plt.subplots(figsize=(6, 3), dpi=100) self.canvas2 = FigureCanvasTkAgg(self.fig2, master=self.statistics_tab) self.canvas2.get_tk_widget().grid(row=9, column=4, padx=15, pady=(15, 0)) self.toolbarFrame2 = Frame(master=self.statistics_tab) self.toolbarFrame2.grid(row=10, column=4) self.toolbar2 = NavigationToolbar2Tk(self.canvas2, self.toolbarFrame2) # THIRD FIGURE: Piechart self.fig3, self.ax3 = plt.subplots(figsize=(4, 3), dpi=100) self.canvas3 = FigureCanvasTkAgg(self.fig3, master=self.statistics_tab) self.canvas3.get_tk_widget().grid(row=9, column=0, columnspan=4, padx=15, pady=(15, 0)) self.toolbarFrame3 = Frame(master=self.statistics_tab) self.toolbarFrame3.grid(row=10, column=0, columnspan=4) self.toolbar3 = NavigationToolbar2Tk(self.canvas3, self.toolbarFrame3)
class NewMorphWindow(Toplevel): def __init__(self, master=None): super().__init__(master=master) self.set_basic() self.set_widgets() def set_basic(self): self.minsize(500, 300) self.maxsize(500, 300) self.title("Operacje morfologiczne") self.protocol("WM_DELETE_WINDOW", lambda: self.cancel()) self.operations = [ "EROZJA", "DYLACJA", "OTWARCIE", "ZAMKNIĘCIE", "SZKIELETYZACJA" ] self.shapes = ["KWADRAT", "ROMB"] self.handleBorder = { "Bez zmian (isolated)": 0, "Odbicie lustrzane (reflect)": 1, "Powielenie skrajnego piksela (replicate)": 2 } def set_widgets(self): self.operationChoice = StringVar(self, self.operations[0]) self.shape = StringVar(self, value=self.shapes[0]) self.size = StringVar(self, value="3") self.borderType = StringVar(self, list(self.handleBorder.keys())[0]) self.operationChoice.trace("w", self.update_preview) self.shape.trace("w", self.update_preview) self.borderType.trace("w", self.update_preview) self.operationList = OptionMenu(self, self.operationChoice) self.shapeList = OptionMenu(self, self.shape) self.sizeSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=3, to=9999, textvariable=self.size, command=self.update_preview, state='readonly', increment=2) self.borderList = OptionMenu(self, self.borderType) for oper in self.operations: self.operationList['menu'].add_command( label=oper, command=lambda v=oper: self.operationChoice.set(v)) for sh in self.shapes: self.shapeList['menu'].add_command( label=sh, command=lambda v=sh: self.shape.set(v)) for border in self.handleBorder: self.borderList['menu'].add_command( label=border, command=lambda v=border: self.borderType.set(v)) self.saveButton = Button(self, image=saveIcon, command=self.update_image) self.cancelButton = Button(self, image=closeIcon, command=self.cancel) self.update_preview() self.place_widgets() def update_image(self): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.image.morph_operations( self.operationChoice.get(), self.shape.get(), int(self.size.get()), self.handleBorder[self.borderType.get()]) self.master.image.copy = copy.deepcopy(self.master.image.cv2Image) self.master.manager.new_state(self.master.image.cv2Image) self.master.update_visible_image() self.master.update_child_windows() self.destroy() def update_preview(self, *args): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.image.morph_operations( self.operationChoice.get(), self.shape.get(), int(self.size.get()), self.handleBorder[self.borderType.get()]) self.master.update_visible_image() self.master.update_child_windows() def place_widgets(self): Label(self, text="Operacja:", font=("Helvetica", 15)).place(x=25, y=25) Label(self, text="Kształt i rozmiar:", font=("Helvetica", 15)).place(x=25, y=85) Label(self, text="Piksele skrajne:", font=("Helvetica", 15)).place(x=25, y=145) self.operationList.place(width=250, height=50, x=225, y=20) self.shapeList.place(width=100, height=50, x=225, y=80) self.sizeSpin.place(width=100, height=50, x=375, y=80) self.borderList.place(width=250, height=50, x=225, y=140) self.saveButton.place(width=40, height=40, x=200, y=255) self.cancelButton.place(width=40, height=40, x=260, y=255) def cancel(self): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.update_visible_image() self.master.image.fill_histogram() self.master.update_child_windows() self.destroy()
class GUI(object): '''Stellt die Oberflaeche dar. Alle steuerden Taetigkeiten werden (sollten) vom Controller Objekt uebernommen werden. ''' def __init__(self): ''' Constructor ''' self.root = Tk() self.root.title("DinnerLog") self.root.minsize(800, 600) self.root.grid_columnconfigure(0, weight=1) self.root.grid_rowconfigure(0, weight=1) self.root.grid_rowconfigure(1, weight=3) # Ein Frame für alles, das mit Zutaten zu tun hat self.fr_zutaten = Labelframe(self.root, borderwidth=2, relief=GROOVE, text="Zutaten") self.fr_zutaten.grid_columnconfigure(0, weight=1) self.fr_zutaten.grid_rowconfigure(0, weight=1) self.fr_zutaten.grid(row=0, column=0, sticky="NSWE") self.lb_zutaten = Listbox(self.fr_zutaten) sb_zutaten = Scrollbar(self.lb_zutaten, orient=VERTICAL) self.lb_zutaten.configure(yscrollcommand=sb_zutaten.set) sb_zutaten.config(command=self.lb_zutaten.yview) sb_zutaten.pack(side="right", fill="both") self.lb_zutaten.grid(row=0, column=0, sticky="NSEW") self._addNeueZutatFrame() # Ein Frame in den alles, das mit Mahlzeiten zu tun hat, kommt self.fr_mahlzeit = Labelframe(self.root, borderwidth=2, relief=GROOVE, text="Mahlzeiten") self.fr_mahlzeit.grid_columnconfigure(0, weight=1) self.fr_mahlzeit.grid_rowconfigure(0, weight=1) self.fr_mahlzeit.grid(row=1, column=0, sticky="NSWE") self._addNeueMahlzeitFrame() self.lb_mahlzeiten = Listbox(self.fr_mahlzeit, selectmode=SINGLE) sb_mahlzeiten = Scrollbar(self.lb_mahlzeiten, orient=VERTICAL) sb_mahlzeiten.configure(command=self.lb_mahlzeiten.yview) self.lb_mahlzeiten.configure(yscrollcommand=sb_mahlzeiten.set) sb_mahlzeiten.pack(side="right", fill="both") self.lb_mahlzeiten.grid(row=0, column=0, sticky="NSEW") fr_neu_ok = Frame(self.fr_mahlzeit) fr_neu_ok.grid(row=1, column=0, columnspan=2, sticky="E") self.btn_neu = Button(fr_neu_ok, text="Neu") self.btn_neu.pack(side="left") self.btn_mahlzeit_als_zt = Button(fr_neu_ok, text="Als Zutat") self.btn_mahlzeit_als_zt.pack(anchor=E, side="right") self.btn_insert = Button(fr_neu_ok, text="Hinzufuegen") self.btn_insert.pack(anchor=E, side="right") self.btn_update = Button(fr_neu_ok, text="Update") self.btn_update.pack(anchor=E, side="right") self.btn_delete = Button(fr_neu_ok, text="Loeschen") self.btn_delete.pack(anchor=E, side="right") # Ein Frame der Statistiken darstellt self.fr_stats = Labelframe(self.root, borderwidth=2, relief=GROOVE, text="Statistik") self.fr_stats.grid(row=3, column=0, sticky="NSWE") #self.cv_stats = Canvas(self.fr_stats, height=80, width=600) #self.cv_stats.create_line(2,5,598,5, fill="#bbb") def _addNeueMahlzeitFrame(self): self.fr_neue_mz = Frame(self.fr_mahlzeit) self.fr_neue_mz.grid_rowconfigure(2, weight=1) self.fr_neue_mz.grid(row=0, column=1, sticky="WSNE") lbl_name = Label(self.fr_neue_mz, text="Name:") lbl_name.grid(row=0, column=0, sticky="NW") self.en_name = Entry(self.fr_neue_mz) self.en_name.grid(row=0, column=1, columnspan=2, sticky="WNE") lbl_zutat = Label(self.fr_neue_mz, text="Zutaten:") lbl_zutat.grid(row=1, column=0, sticky="NW") self.lb_zutat = Listbox(self.fr_neue_mz) sb_zutat = Scrollbar(self.lb_zutat, orient=VERTICAL) self.lb_zutat.configure(yscrollcommand=sb_zutat.set) sb_zutat.configure(command=self.lb_zutat.yview) sb_zutat.pack(side="right", fill="both") self.lb_zutat.grid(row=2, column=0, columnspan=3, sticky="NWSE") self.var_zutat = StringVar(self.fr_neue_mz) self.opt_zutat = OptionMenu(self.fr_neue_mz, self.var_zutat, "Auswahl") self.opt_zutat.grid(row=3, column=0) self.en_menge = Entry(self.fr_neue_mz) self.en_menge.grid(row=3, column=1) self.btn_mahlzeit_hinzu = Button(self.fr_neue_mz, text="Hinzu") self.btn_mahlzeit_hinzu.grid(row=3, column=2, sticky="E") def _addNeueZutatFrame(self): fr_neue_zt = Frame(self.fr_zutaten) fr_neue_zt.grid(row=0, column=2,sticky="NWSE") lbl_name = Label(fr_neue_zt, text="Name:") lbl_name.grid(row=0, column=0, sticky="W") self.en_name_zt = Entry(fr_neue_zt) self.en_name_zt.grid(row=0, column=1, columnspan=2, sticky="WE") lbl_fett = Label(fr_neue_zt, text="Fett:") lbl_fett.grid(row=1, column=0, sticky="W") self.en_fett = Entry(fr_neue_zt) self.en_fett.grid(row=1, column=1, columnspan=2) lbl_eiweiss = Label(fr_neue_zt, text="Eiweiss:") lbl_eiweiss.grid(row=2, column=0, sticky="W") self.en_eiweiss = Entry(fr_neue_zt) self.en_eiweiss.grid(row=2, column=1, columnspan=2) lbl_kh = Label(fr_neue_zt, text="Kohlenhy.:") lbl_kh.grid(row=3, column=0, sticky="W") self.en_kh = Entry(fr_neue_zt) self.en_kh.grid(row=3, column=1, columnspan=2) self.btn_zutat_insert = Button(fr_neue_zt, text="Hinzu") self.btn_zutat_insert.grid(row=4, column=1, sticky="E") self.btn_zutat_update = Button(fr_neue_zt, text="Update") self.btn_zutat_update.grid(row=5, column=1, sticky="E") self.btn_zutat_delete = Button(fr_neue_zt, text="Loeschen") self.btn_zutat_delete.grid(row=6, column=1, sticky="E")
def set_widgets(self): self.horizontalSizeW = StringVar(self, value="3") self.horizontalSizeH = StringVar(self, value="1") self.verticalSizeW = StringVar(self, value="3") self.verticalSizeH = StringVar(self, value="1") self.borderType = StringVar(self, list(self.handleBorder.keys())[0]) self.cbVarHorizontal = IntVar(value=1) self.cbVarVertical = IntVar(value=1) self.cbVarOuter = IntVar(value=1) self.cbVarNegate = IntVar(value=0) self.sizeHorizontalWSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=1, to=9999, textvariable=self.horizontalSizeW, command=self.update_preview, state='readonly', increment=2) self.sizeHorizontalHSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=1, to=9999, textvariable=self.horizontalSizeH, command=self.update_preview, state='readonly', increment=2) self.sizeVerticalWSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=1, to=9999, textvariable=self.verticalSizeW, command=self.update_preview, state='readonly', increment=2) self.sizeVerticalHSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=1, to=9999, textvariable=self.verticalSizeH, command=self.update_preview, state='readonly', increment=2) self.horizontalSizeW.trace("w", self.update_preview) self.horizontalSizeH.trace("w", self.update_preview) self.verticalSizeW.trace("w", self.update_preview) self.verticalSizeH.trace("w", self.update_preview) self.borderType.trace("w", self.update_preview) self.cbVarHorizontal.trace("w", self.update_preview) self.cbVarVertical.trace("w", self.update_preview) self.cbVarOuter.trace("w", self.update_preview) self.cbVarNegate.trace("w", self.update_preview) self.cbHorizontal = Checkbutton(self, width=0, variable=self.cbVarHorizontal) self.cbVertical = Checkbutton(self, width=0, variable=self.cbVarVertical) self.cbOuterOnly = Checkbutton(self, width=0, variable=self.cbVarOuter) self.cbNegateFirst = Checkbutton(self, width=0, variable=self.cbVarNegate) self.borderList = OptionMenu(self, self.borderType) for border in self.handleBorder: self.borderList['menu'].add_command( label=border, command=lambda v=border: self.borderType.set(v)) self.saveButton = Button(self, image=saveIcon, command=self.update_image) self.cancelButton = Button(self, image=closeIcon, command=self.cancel) self.update_preview() self.place_widgets()
class GUI(): def __init__(self): self.root = ThemedTk(theme="radiance") INIT_WIDTH, INIT_HEIGHT = self.root.winfo_screenwidth( ), self.root.winfo_screenheight() boldStyle = ttk.Style() boldStyle.configure("Bold.TButton", font=('Sans', '12', 'bold')) #icon_loc = os.path.join(os.getcwd(),ICON_NAME) #img = ImageTk.PhotoImage(master = self.root, file=icon_loc) #self.root.wm_iconbitmap(img) #self.root.ttk.call('wm', 'iconphoto', self.root._w, img) self.root.title("Form Labeller") self.root.maxsize(INIT_WIDTH, INIT_HEIGHT) self.supported_formats = SUPPORTED_FORMATS self.left_frame = Frame(self.root, width=BUTTON_WIDTH) self.top_frame1 = Frame(self.left_frame, width=BUTTON_WIDTH, height=int(INIT_HEIGHT / 2)) self.top_frame = Frame(self.left_frame, width=BUTTON_WIDTH, height=INIT_HEIGHT - int(INIT_HEIGHT / 2)) self.bottom_frame = Frame(self.root, width=INIT_WIDTH - BUTTON_WIDTH, height=INIT_HEIGHT) self.load_image_directory_button = Button(self.top_frame1, text='Open Folder', command=self.load_directory, width=int(BUTTON_WIDTH), style="Bold.TButton") self.load_image_directory_button.grid(row=OPEN_FOLDER_ROW, columnspan=2, sticky=tk.W + tk.E) self.prev_img_button = Button(self.top_frame1, text='← Prev', command=self.previous_img, state=tk.DISABLED, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.prev_img_button.grid(row=PREV_ROW, column=0, sticky=tk.W + tk.E) self.next_img_button = Button(self.top_frame1, text='Next → ', command=self.next_img, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.next_img_button.grid(row=NEXT_COL, column=1, sticky=tk.W + tk.E) self.save_image_button = Button(self.top_frame1, text='Save ', command=self.saver, width=int(BUTTON_WIDTH), style="Bold.TButton") self.save_image_button.grid(row=SAVE_ROW, columnspan=2, sticky=tk.W + tk.E) self.delete_poly_button = Button(self.top_frame, text='Delete Selected', command=self.delete_selected, width=int(BUTTON_WIDTH), style="Bold.TButton") self.delete_poly_button.grid(row=DEL_SELECTED_ROW, columnspan=2, sticky=tk.W + tk.E) self.type_choices = TYPE_CHOICES self.variable = StringVar(self.top_frame) self.variable.set(self.type_choices[0]) self.type_options = OptionMenu(self.top_frame, self.variable, *self.type_choices, style="Bold.TButton") self.type_options.config(width=int(BUTTON_WIDTH / 2)) self.type_options.grid(row=DROP_DOWN_ROW, column=0) self.save_type_button = Button(self.top_frame, text='Save Type', command=self.save_type, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.save_type_button.grid(row=SAVE_TYPE_ROW, column=1, sticky=tk.W + tk.E) self.deselect_all_button = Button(self.top_frame, text='Deselect All', command=self.deselect_all, width=BUTTON_WIDTH, style="Bold.TButton") self.deselect_all_button.grid(row=DESELECT_ALL_ROW, columnspan=2, sticky=tk.W + tk.E) self.select_all_button = Button(self.top_frame, text='Select All', command=self.select_all, width=BUTTON_WIDTH, style="Bold.TButton") self.select_all_button.grid(row=SELECT_ALL_ROW, columnspan=2, sticky=tk.W + tk.E) self.draw_poly_button = Button(self.top_frame, text='Draw Poly', command=self.draw_poly_func, width=BUTTON_WIDTH, style="Bold.TButton") self.draw_poly_button.grid(row=DRAW_POLY_ROW, columnspan=2, sticky=tk.W + tk.E) self.draw_rect_button = Button(self.top_frame, text='Draw Rectangle', command=self.draw_rect_func, width=BUTTON_WIDTH, style="Bold.TButton") self.draw_rect_button.grid(row=DRAW_RECT_ROW, columnspan=2, sticky=tk.W + tk.E) self.delete_all_button = Button(self.top_frame, text='Delete All', command=self.delete_all, width=BUTTON_WIDTH, style="Bold.TButton") self.save_poly_button = Button(self.top_frame, text='Save Poly', command=self.save_drawing, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.discard_poly_button = Button(self.top_frame, text='Discard Poly', command=self.discard_drawing, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.save_rect_button = Button(self.top_frame, text='Save Rect', command=self.save_drawing, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.discard_rect_button = Button(self.top_frame, text='Discard Rect', command=self.discard_drawing, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.show_type_button = Button(self.top_frame, text='Show Type', command=self.show_type, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.show_type_button.grid(row=SHOW_TYPE_ROW, column=0, columnspan=1, sticky=tk.W + tk.E) self.hide_type_button = Button(self.top_frame, text='Hide Type', command=self.hide_type, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.hide_type_button.grid(row=HIDE_TYPE_ROW, columnspan=1, column=1, sticky=tk.W + tk.E) self.make_tight_button = Button(self.top_frame, text='Make Tight', command=self.make_tight, width=int(BUTTON_WIDTH / 2), style="Bold.TButton") self.make_tight_button.grid(row=MAKE_TIGHT_ROW, columnspan=2, column=0, sticky=tk.W + tk.E) self.threshold_scale = Scale(self.top_frame, from_=0, to=255, orient=HORIZONTAL, width=int(BUTTON_WIDTH / 2), label="Binary Threshold") self.threshold_scale.set(128) self.threshold_scale.grid(row=THRESHOLD_ROW, columnspan=2, column=0, sticky=tk.W + tk.E) self.tight_save_button = Button(self.top_frame, text='Accept Tight', command=self.save_tight) self.tight_discard_button = Button(self.top_frame, text='Discard Tight', command=self.discard_tight) self.canvas = Canvas(self.bottom_frame, width=INIT_WIDTH - BUTTON_WIDTH, height=INIT_HEIGHT, borderwidth=1) self.image_name = None #self.image_path = os.path.join('imgs','img1.jpg') self.image_dir = None self.images_in_dir = None self.curr_idx = None self.img_cnv = None #self.img_cnv = ImageOnCanvas(self.root,self.canvas,self.image_path) self.drawing_obj = None self.tight_box_obj = None self.left_frame.pack(side=tk.LEFT) self.top_frame1.pack(side=tk.TOP) self.top_frame.pack(side=tk.BOTTOM) self.bottom_frame.pack(side=tk.LEFT) max_w, max_h = self.canvas.winfo_screenwidth( ), self.canvas.winfo_screenheight() self.hbar = Scrollbar(self.bottom_frame, orient=HORIZONTAL) self.hbar.pack(side=BOTTOM, fill=X) self.hbar.config(command=self.canvas.xview) self.vbar = Scrollbar(self.bottom_frame, orient=VERTICAL) self.vbar.pack(side=RIGHT, fill=Y) self.vbar.config(command=self.canvas.yview) max_w, max_h = self.canvas.winfo_width(), self.canvas.winfo_height() self.canvas.configure( #scrollregion=self.canvas.bbox('all'), scrollregion=(0, 0, max_w - BUTTON_WIDTH, max_h), yscrollcommand=self.vbar.set, xscrollcommand=self.hbar.set) self.canvas.pack() self.hide_buttons() self.load_image_directory_button.config(state="normal") def save_tight(self): self.tight_box_obj.save_tight_box() self.tight_save_button.grid_forget() self.tight_discard_button.grid_forget() self.make_tight_button.grid(row=MAKE_TIGHT_ROW, columnspan=2, sticky=tk.W + tk.E) self.show_buttons() self.tight_box_obj = None def discard_tight(self): self.tight_box_obj.discard_tight_box() self.tight_save_button.grid_forget() self.tight_discard_button.grid_forget() self.make_tight_button.grid(row=MAKE_TIGHT_ROW, columnspan=2, sticky=tk.W + tk.E) self.show_buttons() self.tight_box_obj = None def show_type(self): for poly in self.img_cnv.polygons: if poly.select_poly: poly.show_type() def hide_type(self): for poly in self.img_cnv.polygons: poly.unshow_type() def hide_buttons(self): self.load_image_directory_button.config(state=tk.DISABLED) self.save_image_button.config(state=tk.DISABLED) self.delete_poly_button.config(state=tk.DISABLED) self.save_type_button.config(state=tk.DISABLED) self.deselect_all_button.config(state=tk.DISABLED) self.select_all_button.config(state=tk.DISABLED) self.delete_all_button.config(state=tk.DISABLED) self.show_type_button.config(state=tk.DISABLED) self.hide_type_button.config(state=tk.DISABLED) self.make_tight_button.config(state=tk.DISABLED) def show_buttons(self): self.load_image_directory_button.config(state="normal") self.save_image_button.config(state="normal") self.delete_poly_button.config(state="normal") self.save_type_button.config(state="normal") self.deselect_all_button.config(state="normal") self.select_all_button.config(state="normal") self.delete_all_button.config(state="normal") self.show_type_button.config(state="normal") self.hide_type_button.config(state="normal") self.draw_poly_button.config(state="normal") self.draw_rect_button.config(state="normal") self.make_tight_button.config(state="normal") def select_all(self): for poly in self.img_cnv.polygons: poly.select_polygon() def deselect_all(self): self.hide_type() for poly in self.img_cnv.polygons: poly.deselect_poly() def delete_all(self): result = messagebox.askyesno("Confirm Delete All", "Delete All Annotations?") if not result: return self.select_all() self.delete_selected() #self.img_cnv.polygons_mutex.acquire() #for poly in self.img_cnv.polygons: # poly.delete_self() #self.img_cnv.polygons_mutex.release() def save_type(self): selected_option = self.variable.get() self.img_cnv.polygons_mutex.acquire() for poly in self.img_cnv.polygons: if poly.select_poly == True: if selected_option == "None": poly.poly_type = None else: poly.poly_type = selected_option #poly.unshow_type() #poly.show_type() self.img_cnv.polygons_mutex.release() self.variable.set(self.type_choices[0]) #self.deselect_all() def load_new_img(self): self.canvas.delete('all') self.img_cnv = None path = os.path.join(self.image_dir, self.image_name) self.img_cnv = ImageOnCanvas(self.root, self.bottom_frame, self.canvas, path) logger("LOADED: " + self.img_cnv.image_path) def load_directory(self): while True: selection = filedialog.askdirectory() if selection == () or selection == '': return self.root.directory = selection self.image_dir = self.root.directory file_names = os.listdir(self.image_dir) self.images_in_dir = [] self.curr_idx = None self.image_name = None for name in file_names: if name.split('.')[-1] in self.supported_formats: self.images_in_dir.append(name) if len(self.images_in_dir) == 0: self.pop_up("No supported images in the selected directory") else: break self.show_buttons() self.next_img() def pop_up(self, text): top = Toplevel() top.title("ERROR") msg = Message(top, text=text) msg.pack() button = Button(top, text="Dismiss", command=top.destroy) button.pack() def next_img(self): if self.curr_idx == None: self.curr_idx = -1 self.curr_idx = self.curr_idx + 1 if self.curr_idx >= len(self.images_in_dir): self.pop_up("Done with Images in this directory") self.curr_idx = self.curr_idx - 1 return if self.curr_idx > 0: self.prev_img_button.config(state="normal") self.image_name = self.images_in_dir[self.curr_idx] self.load_new_img() self.root.title("Form Labeller - " + self.image_name + "(" + str(self.curr_idx + 1) + "/" + str(len(self.images_in_dir)) + ")") def previous_img(self): if self.curr_idx == 1: self.curr_idx = -1 self.prev_img_button.config(state=tk.DISABLED) else: self.curr_idx = self.curr_idx - 2 self.next_img() def delete_selected(self): to_be_deleted = [] for i, poly in enumerate(self.img_cnv.polygons): if poly.select_poly == True: poly.delete_self() to_be_deleted.append(i) j = 0 for idx in to_be_deleted: self.img_cnv.polygons.pop(idx - j) self.img_cnv.bbs.pop(idx - j) self.img_cnv.poly_type.pop(idx - j) j = j + 1 def start_gui(self): self.root.mainloop() def saver(self): logger("Saving: " + self.img_cnv.image_path) self.save_image_button.config(state=tk.DISABLED) self.img_cnv.save_json(self.root.directory) self.save_image_button.config(state="normal") def draw_poly_func(self): self.deselect_all() self.img_cnv.drawing_polygon = True self.draw_poly_button.grid_forget() self.save_poly_button.grid(row=DRAW_POLY_ROW, column=0, sticky=tk.W + tk.E) self.discard_poly_button.grid(row=DRAW_POLY_ROW, column=1, sticky=tk.W + tk.E) self.hide_buttons() self.draw_rect_button.config(state=tk.DISABLED) self.drawing_obj = DrawPoly(self.bottom_frame, self.canvas, self.img_cnv, RADIUS) def draw_rect_func(self): self.deselect_all() self.img_cnv.drawing_polygon = True self.draw_rect_button.grid_forget() self.save_rect_button.grid(row=DRAW_RECT_ROW, column=0, sticky=tk.W + tk.E) self.discard_rect_button.grid(row=DRAW_RECT_ROW, column=1, sticky=tk.W + tk.E) self.hide_buttons() self.draw_poly_button.config(state=tk.DISABLED) self.drawing_obj = DrawRect(self.bottom_frame, self.canvas, self.img_cnv, RADIUS) def save_drawing(self): self.show_buttons() self.img_cnv.drawing_polygon = False new_poly_pts = self.drawing_obj.pt_coords print("Trying to save polygon with pts:", str(new_poly_pts)) for pt in self.drawing_obj.points: self.canvas.delete(pt) if self.img_cnv.scale_factor != None: for i in range(len(new_poly_pts)): for j in range(2): new_poly_pts[i][ j] = new_poly_pts[i][j] / self.img_cnv.scale_factor self.img_cnv.add_poly(new_poly_pts) #self.img_cnv.bbs.append(new_poly_pts) #self.img_cnv.draw_bbs([self.img_cnv.bbs[-1]]) #debug (1, str(type(self.drawing_obj))) if isinstance(self.drawing_obj, DrawRect): self.save_rect_button.grid_forget() self.discard_rect_button.grid_forget() self.draw_rect_button.grid(row=DRAW_RECT_ROW, columnspan=2, sticky=tk.W + tk.E) elif isinstance(self.drawing_obj, DrawPoly): self.save_poly_button.grid_forget() self.discard_poly_button.grid_forget() self.draw_poly_button.grid(row=DRAW_POLY_ROW, columnspan=2, sticky=tk.W + tk.E) self.drawing_obj.delete_self() self.drawing_obj = None def discard_drawing(self): self.show_buttons() self.img_cnv.drawing_polygon = False #for pt in self.drawing_obj.points: # self.canvas.delete(pt) self.drawing_obj.delete_self() if isinstance(self.drawing_obj, DrawRect): self.save_rect_button.grid_forget() self.discard_rect_button.grid_forget() self.draw_rect_button.grid(row=DRAW_RECT_ROW, columnspan=2, sticky=tk.W + tk.E) elif isinstance(self.drawing_obj, DrawPoly): self.save_poly_button.grid_forget() self.discard_poly_button.grid_forget() self.draw_poly_button.grid(row=DRAW_POLY_ROW, columnspan=2, sticky=tk.W + tk.E) self.drawing_obj = None def make_tight(self): self.hide_buttons() self.tight_box_obj = TightBox(self.root, self.img_cnv, self.threshold_scale.get()) self.tight_box_obj.tight_box() self.make_tight_button.grid_forget() self.tight_save_button.grid(row=MAKE_TIGHT_ROW, column=0, columnspan=1, sticky=tk.W + tk.E) self.tight_discard_button.grid(row=MAKE_TIGHT_ROW, column=1, columnspan=1, sticky=tk.W + tk.E)
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 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.delete_part_index = 1 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()) 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") try: self.on_find() except Exception as e: self.status.seterror(e) # 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) self.copySourcesMenu.entryconfig(self.selectedParameter_index, state=DISABLED) self.editmenu.entryconfig(self.delete_part_index, state=DISABLED) return if self.partsTV.parent(selected) == '': self.copySourcesMenu.entryconfig(self.selectedParameter_index, state=DISABLED) self.editmenu.entryconfig(self.delete_part_index, state=NORMAL) else: self.copySourcesMenu.entryconfig(self.selectedParameter_index, state=NORMAL) self.editmenu.entryconfig(self.delete_part_index, state=DISABLED) 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)
penColorEntry.grid(row = 3, column = 1) #backgroundColor bgColorLabel = Label(root, text = "BackgroundColor") bgColorLabel.grid(row = 3, column = 2) bgColorStr = StringVar() bgColorEntry = Entry(root, width = 10, textvariable = bgColorStr) bgColorEntry.grid(row = 3, column = 3) #optionMenu figureLabel = Label(root, text = "Figure") figureLabel.grid(row = 4, column = 0) turtleStr = StringVar() turtleMenu = OptionMenu(root, turtleStr, shapes[0], *shapes) turtleMenu.grid(row = 4, column = 1) #button clearButton = Button(root, text = "Clear", command = clearF) clearButton.grid(row = 5, column = 0) drawButton = Button(root, text = "Draw", command = DrawF) drawButton.grid(row = 5, column = 1) clearScrButton = Button(root, text = "ClearScreen", command = ClearScrF) clearScrButton.grid(row = 5, column = 2) #labelInformation infoLabelT = Label(root, text = "Info:")
def initInputs(self): graphFrame = Frame(self) graphFrame.pack(fill=BOTH, expand=True) fig = Figure(figsize=(1, 1), dpi=100) canvas = FigureCanvasTkAgg(fig, master=graphFrame) # A tk.DrawingArea. canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) canvas.draw() toolbar = NavigationToolbar2Tk(canvas, graphFrame) toolbar.update() inputsFrame = Frame(self) inputsFrame.grid_columnconfigure(1, weight=1) inputsFrame.grid_columnconfigure(3, weight=1) inputsFrame.pack(fill=X, padx=5, pady=5) # Loan Amount Label(inputsFrame, text="Loan Amount $", width=14).grid(row=0, column=0) e_loan = Entry(inputsFrame) e_loan.grid(row=0, column=1, stick="we", padx=(0, 5)) # Loan Term Label(inputsFrame, text="Term (Months)", width=14).grid(row=1, column=0) e_term = Entry(inputsFrame) e_term.grid(row=1, column=1, stick="we", padx=(0, 5)) # Loan Interest Label(inputsFrame, text="Monhtly Interest", width=14).grid(row=0, column=2) e_interest = Entry(inputsFrame) e_interest.grid(row=0, column=3, stick="we", padx=(0, 5)) # Increase Foresee Label(inputsFrame, text="Commodity Type", width=14).grid(row=1, column=2) e_commodity_options = ["", "MSFT", "AAPL", "IBM", "USDTRY=X", "EURTRY=X", "BTC-USD", "PETKM.IS", "TKC"] e_commodity_var = StringVar(inputsFrame) e_commodity_var.set(e_commodity_options[0]) e_commodity = OptionMenu(inputsFrame, e_commodity_var, *e_commodity_options) e_commodity.grid(row=1, column=3, stick="we", padx=(0, 5)) # Currently just printing values. predict_plot = fig.add_subplot(111) def calculate(): # Input variables. loan = int(e_loan.get()) interest = float(e_interest.get()) times = int(e_term.get()) commodity = e_commodity_var.get() debt = loan * interest * times / 100 + loan # YahooFinance historical data df = yf.download(commodity, period="10y", interval="1d") #---> Data Size dfreg = df.loc[:, ['Open', 'Close', 'Adj Close', 'Volume']] dfreg['HILO_PCT'] = (df['High'] - df['Low']) / df['Close'] * 100.0 dfreg['DELT_PCT'] = (df['Close'] - df['Open']) / df['Open'] * 100.0 dfreg.fillna(value=-99999, inplace=True) #Forecastout = Calculation of the time forecast_out = times * 30 # month times product days 30 so get the total time days dfreg['label'] = dfreg['Close'].shift(-forecast_out) #label stununa close vaerilirini atıyoruz forecastout dan alına sure kadar # Calculation of the lot liste2 = list(dfreg['Close'][-1:])# YF'den alınan son close datası alım olarak kabul edilir lot = loan / int(liste2[0]) # Separation x = dfreg.drop(columns='label') x = scale(x) # label dışındaki bütün verileri belli parametereye yerleştiriyor. y = dfreg.iloc[:, -1] # labeldaki tüm satırları al,en son sütunu al x_to_predict = x[-forecast_out:] # the last day we will guess # baştan al en son da ki tahmin ediceğimiz günü alma x = x[:-forecast_out] y = y[:-forecast_out] x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, random_state=0) regressor = LinearRegression() regressor.fit(x_train, y_train) # Training # Percentage of Accuracy accuracy = regressor.score(x_test, y_test) * 100 prediction_set = regressor.predict(x_to_predict) dfreg['Prediction'] = np.nan # Last date detection last_date = dfreg.iloc[-1].name lastDatetime = last_date.timestamp() one_day = 86400 # New date detection nexDatetime = lastDatetime + one_day for i in prediction_set: # Calculate elapsed time next_date = datetime.datetime.fromtimestamp(nexDatetime) nexDatetime += one_day dfreg.loc[next_date] = [np.nan for q in range(len(dfreg.columns) - 1)] + [i] # Last and First Predict detection firstPredict = list(dfreg['Prediction'][-forecast_out:-forecast_out + 1]) #----> ilk predict değerini listeden bulmka için -forecast:-forecast+1 yaparak predict forecastin ilk değerini buluruz. lastPredict = list(dfreg['Prediction'][-1:]) # Calculation of increase amount liste = lastPredict + firstPredict a = liste[0] b = liste[1] result = b - a increase = result / a * -1 * 100 #calculation of total profit total_profit = loan * increase - debt # Calculation of new list = lot X predict liste3 = list(dfreg['Prediction'][-forecast_out:]) liste3 = [i * lot for i in liste3] # Output labels Label(inputsFrame, text="Accuracy: {:.2f}%".format(accuracy), width=14).grid(row=2, column=0) Label(inputsFrame, text="Debt: ${:.2f}".format(debt), width=14).grid(row=2, column=1) Label(inputsFrame, text="Change: {:.2f}%".format(increase), width=14).grid(row=2, column=2) Label(inputsFrame, text="Total Profit : {:.2f}%".format(totalm), width=14).grid(row=2, column=3) # Plot Stuff predict_plot.clear() predict_plot.plot(liste3) predict_plot.plot([0, forecast_out], [loan, debt]) canvas.draw() # Button buttonsFrame = Frame(self) buttonsFrame.pack(fill=X, padx=5, pady=(0, 5)) b_calculate = Button(buttonsFrame, text="Calculate", command=calculate) b_calculate.pack(side=RIGHT)
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.delete_part_index = 1 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()) 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 __init__(self, master, app, **kwargs): """Create category manager.""" Frame.__init__(self, master, padding=4, **kwargs) self.columnconfigure(0, weight=1) self.rowconfigure(1, weight=1) self.app = app self.style = Style(self) self.style.theme_use("clam") self.im_plus = PhotoImage(file=IM_PLUS) self.im_delete = PhotoImage(file=IM_DELETE) # --- Default category self.frame_def_cat = Frame(self) self.default_category = StringVar( self.frame_def_cat, CONFIG.get("General", "default_category").capitalize()) Label(self.frame_def_cat, text=_("Default category ")).grid(row=0, column=0, sticky="e", padx=(4, 0)) self.categories = CONFIG.options("Categories") self.categories.sort() categories = [cat.capitalize() for cat in self.categories] self.def_cat_menu = OptionMenu( self.frame_def_cat, self.default_category, CONFIG.get("General", "default_category").capitalize(), *categories) optionmenu_patch(self.def_cat_menu, self.default_category) self.def_cat_menu.grid(row=0, column=1, sticky="w", padx=4, pady=4) # --- Category colors, names ... style = Style(self) style.configure('txt.TFrame', relief='ridge', border=2) bg = style.lookup('TFrame', 'background') frame = Frame(self, style='txt.TFrame', padding=1) frame.columnconfigure(0, weight=1) frame.rowconfigure(0, weight=1) txt = Text(frame, width=1, height=1, bg=bg, relief='flat', highlightthickness=0, padx=6, pady=6, cursor='arrow') scroll_x = AutoScrollbar(frame, orient='horizontal', command=txt.xview) scroll_y = AutoScrollbar(frame, orient='vertical', command=txt.yview) txt.configure(xscrollcommand=scroll_x.set, yscrollcommand=scroll_y.set) txt.grid(row=0, column=0, sticky='ewns') scroll_x.grid(row=1, column=0, sticky='ew') scroll_y.grid(row=0, column=1, sticky='ns') self.frame_cat = Frame(txt) txt.window_create('1.0', window=self.frame_cat) txt.configure(state='disabled') self.colors = list(COLORS.keys()) self.colors.sort() self.images = [] self.cat_colors = {} self.cat_labels = {} self.cat_menus = {} self.cat_buttons = {} for i, cat in enumerate(self.categories): self.cat_labels[cat] = Label(self.frame_cat, text="%s" % cat.capitalize(), anchor='e') self.cat_labels[cat].grid(row=i + 2, column=0, sticky="ew", padx=2) self.cat_labels[cat].bind('<Double-Button-1>', self.change_name) self.cat_colors[cat] = StringVar(self) color = CONFIG.get("Categories", cat) self.cat_menus[cat] = OptionMenu(self.frame_cat, self.cat_colors[cat], INV_COLORS[color], *self.colors, command=lambda color, c=cat: self. change_menubutton_color(color, c), style="%s.TMenubutton" % cat) optionmenu_patch(self.cat_menus[cat], self.cat_colors[cat]) self.style.configure("%s.TMenubutton" % cat, background=color) self.cat_menus[cat].grid(row=i + 2, column=1, sticky="w", padx=4, pady=4) self.cat_buttons[cat] = Button( self.frame_cat, image=self.im_delete, padding=0, command=lambda c=cat: self.del_cat(c)) self.cat_buttons[cat].grid(row=i + 2, column=2, padx=4, pady=4, sticky='ns') if len(self.categories) == 1: self.cat_buttons[self.categories[0]].configure(state="disabled") # --- placement self.frame_def_cat.grid(row=0, column=0, sticky="eswn", pady=4) frame.grid(row=1, column=0, sticky="eswn") Button(self, image=self.im_plus, command=self.add_cat).grid(row=2, column=0, sticky='w', pady=8)
class CategoryManager(Frame): """Category manager for the sticky notes.""" def __init__(self, master, app, **kwargs): """Create category manager.""" Frame.__init__(self, master, padding=4, **kwargs) self.columnconfigure(0, weight=1) self.rowconfigure(1, weight=1) self.app = app self.style = Style(self) self.style.theme_use("clam") self.im_plus = PhotoImage(file=IM_PLUS) self.im_delete = PhotoImage(file=IM_DELETE) # --- Default category self.frame_def_cat = Frame(self) self.default_category = StringVar( self.frame_def_cat, CONFIG.get("General", "default_category").capitalize()) Label(self.frame_def_cat, text=_("Default category ")).grid(row=0, column=0, sticky="e", padx=(4, 0)) self.categories = CONFIG.options("Categories") self.categories.sort() categories = [cat.capitalize() for cat in self.categories] self.def_cat_menu = OptionMenu( self.frame_def_cat, self.default_category, CONFIG.get("General", "default_category").capitalize(), *categories) optionmenu_patch(self.def_cat_menu, self.default_category) self.def_cat_menu.grid(row=0, column=1, sticky="w", padx=4, pady=4) # --- Category colors, names ... style = Style(self) style.configure('txt.TFrame', relief='ridge', border=2) bg = style.lookup('TFrame', 'background') frame = Frame(self, style='txt.TFrame', padding=1) frame.columnconfigure(0, weight=1) frame.rowconfigure(0, weight=1) txt = Text(frame, width=1, height=1, bg=bg, relief='flat', highlightthickness=0, padx=6, pady=6, cursor='arrow') scroll_x = AutoScrollbar(frame, orient='horizontal', command=txt.xview) scroll_y = AutoScrollbar(frame, orient='vertical', command=txt.yview) txt.configure(xscrollcommand=scroll_x.set, yscrollcommand=scroll_y.set) txt.grid(row=0, column=0, sticky='ewns') scroll_x.grid(row=1, column=0, sticky='ew') scroll_y.grid(row=0, column=1, sticky='ns') self.frame_cat = Frame(txt) txt.window_create('1.0', window=self.frame_cat) txt.configure(state='disabled') self.colors = list(COLORS.keys()) self.colors.sort() self.images = [] self.cat_colors = {} self.cat_labels = {} self.cat_menus = {} self.cat_buttons = {} for i, cat in enumerate(self.categories): self.cat_labels[cat] = Label(self.frame_cat, text="%s" % cat.capitalize(), anchor='e') self.cat_labels[cat].grid(row=i + 2, column=0, sticky="ew", padx=2) self.cat_labels[cat].bind('<Double-Button-1>', self.change_name) self.cat_colors[cat] = StringVar(self) color = CONFIG.get("Categories", cat) self.cat_menus[cat] = OptionMenu(self.frame_cat, self.cat_colors[cat], INV_COLORS[color], *self.colors, command=lambda color, c=cat: self. change_menubutton_color(color, c), style="%s.TMenubutton" % cat) optionmenu_patch(self.cat_menus[cat], self.cat_colors[cat]) self.style.configure("%s.TMenubutton" % cat, background=color) self.cat_menus[cat].grid(row=i + 2, column=1, sticky="w", padx=4, pady=4) self.cat_buttons[cat] = Button( self.frame_cat, image=self.im_delete, padding=0, command=lambda c=cat: self.del_cat(c)) self.cat_buttons[cat].grid(row=i + 2, column=2, padx=4, pady=4, sticky='ns') if len(self.categories) == 1: self.cat_buttons[self.categories[0]].configure(state="disabled") # --- placement self.frame_def_cat.grid(row=0, column=0, sticky="eswn", pady=4) frame.grid(row=1, column=0, sticky="eswn") Button(self, image=self.im_plus, command=self.add_cat).grid(row=2, column=0, sticky='w', pady=8) def change_name(self, event): """Change category name.""" def ok(event): cats = [l.cget('text').lower() for l in self.cat_labels.values()] cat = name.get().strip().lower() if cat and cat not in cats: label.configure(text=cat.capitalize()) if old_cat == self.default_category.get(): self.default_category.set(cat.capitalize()) self.update_def_cat_menu() name.destroy() label = event.widget old_cat = label.cget('text') name = Entry(self, justify='center') name.insert(0, label.cget('text')) name.place(in_=label, relx=0, rely=0, anchor='nw', relwidth=1, relheight=1) name.bind('<FocusOut>', lambda e: name.destroy()) name.bind('<Escape>', lambda e: name.destroy()) name.bind('<Return>', ok) name.selection_range(0, 'end') name.focus_set() def get_color(self, category): """Return color of category.""" return self.cat_colors[category].get() def get_name(self, category): return self.cat_labels[category].cget('text').lower() def change_menubutton_color(self, color, cat): """ Change the color of the menubutton of the category cat when its default color is changed. """ self.style.configure("%s.TMenubutton" % cat, background=COLORS[color]) def del_cat(self, category): """Remove category.""" rep = askyesnocancel( _("Question"), _("Do you want to delete all notes belonging to \ the category %(category)s? If you answer 'No', the category will be deleted but \ the notes will belong to the default category. Be careful, the change will take \ effect immediately and cannot be undone.") % {"category": category}) if rep is not None: del (self.cat_colors[category]) self.cat_buttons[category].grid_forget() del (self.cat_buttons[category]) self.cat_labels[category].grid_forget() cat = self.cat_labels[category].cget('text') del (self.cat_labels[category]) self.cat_menus[category].grid_forget() del (self.cat_menus[category]) self.categories.remove(category) CONFIG.remove_option("Categories", category) if self.default_category.get() == cat: default = list(self.cat_labels.values())[0].cget('text') self.default_category.set(default) CONFIG.set("General", "default_category", default.lower()) self.update_def_cat_menu() if len(self.categories) == 1: self.cat_buttons[self.categories[0]].configure( state="disabled") if rep: self.app.delete_cat(category) self.app.update_notes() self.app.update_menu() save_config() def update_def_cat_menu(self): """Update default caregory menu.""" self.def_cat_menu.destroy() categories = [l.cget('text') for l in self.cat_labels.values()] self.def_cat_menu = OptionMenu(self.frame_def_cat, self.default_category, None, *categories) optionmenu_patch(self.def_cat_menu, self.default_category) self.def_cat_menu.grid(row=0, column=1, sticky="w", padx=4, pady=4) def add_cat(self): """Add a category.""" top = Toplevel(self, class_='MyNotes') top.transient(self) top.grab_set() top.resizable(False, False) top.title(_("New Category")) def valide(event=None): cats = [l.cget('text').lower() for l in self.cat_labels.values()] cat = name.get().strip().lower() if cat and cat not in cats: c, i = self.frame_cat.grid_size() self.cat_labels[cat] = Label(self.frame_cat, text="%s" % cat.capitalize()) self.cat_labels[cat].grid(row=i, column=0, sticky="e") self.cat_colors[cat] = StringVar(self, _("Yellow")) self.cat_menus[cat] = OptionMenu( self.frame_cat, self.cat_colors[cat], _("Yellow"), *self.colors, command=lambda color, c=cat: self.change_menubutton_color( color, c), style="%s.TMenubutton" % cat) self.style.configure("%s.TMenubutton" % cat, background=COLORS[_("Yellow")]) optionmenu_patch(self.cat_menus[cat], self.cat_colors[cat]) self.cat_menus[cat].grid(row=i, column=1, padx=4, pady=4) self.cat_buttons[cat] = Button( self.frame_cat, image=self.im_delete, padding=0, command=lambda c=cat: self.del_cat(c)) self.cat_buttons[cat].grid(row=i, column=2, padx=4, pady=4, sticky='ns') self.cat_buttons[self.categories[0]].configure(state="normal") self.categories.append(cat) self.categories.sort() self.update_def_cat_menu() top.destroy() name = Entry(top, justify="center") name.grid(row=0, column=0, columnspan=2, sticky="ew") name.bind("<Return>", valide) name.bind("<Escape>", lambda e: top.destroy()) name.focus_set() Button(top, text="Ok", command=valide).grid(row=1, column=0, sticky="nswe") Button(top, text=_("Cancel"), command=top.destroy).grid(row=1, column=1, sticky="nswe")
class NewMorphLineWindow(Toplevel): def __init__(self, master=None): super().__init__(master=master) self.set_basic() self.set_widgets() def set_basic(self): self.minsize(600, 400) self.maxsize(600, 400) self.title("Ekstrakcja linii") self.protocol("WM_DELETE_WINDOW", lambda: self.cancel()) self.handleBorder = { "Bez zmian (isolated)": 0, "Odbicie lustrzane (reflect)": 1, "Powielenie skrajnego piksela (replicate)": 2 } def set_widgets(self): self.horizontalSizeW = StringVar(self, value="3") self.horizontalSizeH = StringVar(self, value="1") self.verticalSizeW = StringVar(self, value="3") self.verticalSizeH = StringVar(self, value="1") self.borderType = StringVar(self, list(self.handleBorder.keys())[0]) self.cbVarHorizontal = IntVar(value=1) self.cbVarVertical = IntVar(value=1) self.cbVarOuter = IntVar(value=1) self.cbVarNegate = IntVar(value=0) self.sizeHorizontalWSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=1, to=9999, textvariable=self.horizontalSizeW, command=self.update_preview, state='readonly', increment=2) self.sizeHorizontalHSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=1, to=9999, textvariable=self.horizontalSizeH, command=self.update_preview, state='readonly', increment=2) self.sizeVerticalWSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=1, to=9999, textvariable=self.verticalSizeW, command=self.update_preview, state='readonly', increment=2) self.sizeVerticalHSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=1, to=9999, textvariable=self.verticalSizeH, command=self.update_preview, state='readonly', increment=2) self.horizontalSizeW.trace("w", self.update_preview) self.horizontalSizeH.trace("w", self.update_preview) self.verticalSizeW.trace("w", self.update_preview) self.verticalSizeH.trace("w", self.update_preview) self.borderType.trace("w", self.update_preview) self.cbVarHorizontal.trace("w", self.update_preview) self.cbVarVertical.trace("w", self.update_preview) self.cbVarOuter.trace("w", self.update_preview) self.cbVarNegate.trace("w", self.update_preview) self.cbHorizontal = Checkbutton(self, width=0, variable=self.cbVarHorizontal) self.cbVertical = Checkbutton(self, width=0, variable=self.cbVarVertical) self.cbOuterOnly = Checkbutton(self, width=0, variable=self.cbVarOuter) self.cbNegateFirst = Checkbutton(self, width=0, variable=self.cbVarNegate) self.borderList = OptionMenu(self, self.borderType) for border in self.handleBorder: self.borderList['menu'].add_command( label=border, command=lambda v=border: self.borderType.set(v)) self.saveButton = Button(self, image=saveIcon, command=self.update_image) self.cancelButton = Button(self, image=closeIcon, command=self.cancel) self.update_preview() self.place_widgets() def update_image(self): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.image.morph_line(int(self.horizontalSizeW.get()), int(self.horizontalSizeH.get()), int(self.verticalSizeW.get()), int(self.verticalSizeH.get()), self.cbVarHorizontal.get(), self.cbVarVertical.get(), self.handleBorder[self.borderType.get()], self.cbVarOuter.get(), self.cbVarNegate.get()) self.master.image.copy = copy.deepcopy(self.master.image.cv2Image) self.master.manager.new_state(self.master.image.cv2Image) self.master.update_visible_image() self.master.update_child_windows() self.destroy() def update_preview(self, *args): self.sizeHorizontalWSpin.config(from_=int(self.horizontalSizeH.get()) + 2) self.sizeHorizontalHSpin.config(to=int(self.horizontalSizeW.get()) - 2) self.sizeVerticalWSpin.config(from_=int(self.verticalSizeH.get()) + 2) self.sizeVerticalHSpin.config(to=int(self.verticalSizeW.get()) - 2) self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.image.morph_line(int(self.horizontalSizeW.get()), int(self.horizontalSizeH.get()), int(self.verticalSizeW.get()), int(self.verticalSizeH.get()), self.cbVarHorizontal.get(), self.cbVarVertical.get(), self.handleBorder[self.borderType.get()], self.cbVarOuter.get(), self.cbVarNegate.get()) self.master.update_visible_image() self.master.update_child_windows() def place_widgets(self): Label(self, text="Poziome linie", font=("Helvetica", 15)).place(x=85, y=15) Label(self, text="Pionowe linie", font=("Helvetica", 15)).place(x=395, y=15) self.sizeHorizontalWSpin.place(width=100, height=50, x=150, y=60) self.sizeHorizontalHSpin.place(width=100, height=50, x=150, y=120) self.sizeVerticalWSpin.place(width=100, height=50, x=450, y=60) self.sizeVerticalHSpin.place(width=100, height=50, x=450, y=120) Label(self, text="Min. długość", font=("Helvetica", 15)).place(x=30, y=70) Label(self, text="Min. grubość", font=("Helvetica", 15)).place(x=30, y=130) Label(self, text="Min. długość", font=("Helvetica", 15)).place(x=330, y=70) Label(self, text="Min. grubość", font=("Helvetica", 15)).place(x=330, y=130) Label(self, text="Szukać poziomych?", font=("Helvetica", 9)).place(x=70, y=175) Label(self, text="Szukać pionowych?", font=("Helvetica", 9)).place(x=380, y=175) self.cbHorizontal.place(x=180, y=175) self.cbVertical.place(x=500, y=175) Label(self, text="Szukać tylko zewnętrznych?", font=("Helvetica", 11)).place(x=190, y=225) Label(self, text="Wstępnie zanegować?", font=("Helvetica", 11)).place(x=190, y=255) self.cbOuterOnly.place(x=390, y=225) self.cbNegateFirst.place(x=390, y=255) self.borderList.place(width=200, height=50, x=200, y=300) self.saveButton.place(width=40, height=40, x=220, y=355) self.cancelButton.place(width=40, height=40, x=340, y=355) def cancel(self): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.update_visible_image() self.master.image.fill_histogram() self.master.update_child_windows() self.destroy()
def __init__(self, parent=None): super().__init__(parent) self.pack(side=LEFT, fill=BOTH, expand=True) self.columnconfigure(0, weight=1) self.rowconfigure(1, weight=1) self.bind("<configure>", self.on_window_resize()) self.master.protocol("WM_DELETE_WINDOW", self.on_window_close) style = AppStyle() # Read application settings. self.data = read_settings() # Top frame styles. style.configure("TOP.TFrame") # Bottom frame styles. style.configure("BOT.TFrame") # Button styles. style.configure("TOP.TMenubutton", padding=13) top_frame = Frame(self, padding=10, style="TOP.TFrame") top_frame.grid(row=0, column=0, sticky="ew") top_frame.columnconfigure(0, weight=1) top_frame.columnconfigure(7, weight=1) cams_list = self.get_cams_list() self.selected_camera_var = StringVar() self.selected_camera_var.trace('w', self.on_camera_option_select) self.cameras_option = OptionMenu(top_frame, self.selected_camera_var, None, *cams_list, command=self.on_camera_option_select, style="TOP.TMenubutton") self.cameras_option.grid(row=0, column=1, padx=[0, 10]) self._biometry_image = PhotoImage(file="resources/biometrical.gif") biometry_button = Button(top_frame, image=self._biometry_image, compound=LEFT, text="Recognize", command=self.on_recognize_button_click) biometry_button.grid(row=0, column=2, padx=[0, 10]) self._open_image = PhotoImage(file="resources/folder_open.gif") open_button = Button(top_frame, image=self._open_image, compound=LEFT, text="Open", command=self.on_open_button_click) open_button.grid(row=0, column=3, padx=[0, 10]) self._config_image = PhotoImage(file="resources/config.gif") config_button = Button(top_frame, image=self._config_image, compound=LEFT, text="Config", command=self.on_config_button_click) config_button.grid(row=0, column=4, padx=[0, 10]) self._update_image = PhotoImage(file="resources/download.gif") update_button = Button(top_frame, image=self._update_image, compound=LEFT, text="Update", command=self.on_update_button_click) update_button.grid(row=0, column=5, padx=[0, 10]) self._close_image = PhotoImage(file="resources/close.gif") close_button = Button(top_frame, image=self._close_image, compound=LEFT, text="Close", command=self.on_window_close) close_button.grid(row=0, column=6, padx=[0, 10]) bottom_frame = Frame(self, padding=10, style="BOT.TFrame", relief=SUNKEN) bottom_frame.grid(row=1, column=0, padx=10, pady=[0, 10], sticky="nsew") self.canvas = Canvas(bottom_frame, bg="black") self.canvas.pack(fill=BOTH, expand=True) # Set the default camera. self.selected_camera_var.set(cams_list[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()
class Dicom(Module): def __init__(self, app): info(' - initializing module: Dicom') self.app = app if LIBS_INSTALLED: # grid load button self.frame_holder = Frame(self.app.LEFT) #, pady=7) self.frame_holder.grid(row=2) self.frame = Frame(self.frame_holder) self.frame.pack(expand=True) self.method = StringVar(self.app) self.mode = None self.reader = None # zoom buttons self.zbframe = Frame(self.app.LEFT) self.zbframe.grid(row=6, column=0) # zoom frame (contains our tracing canvas) self.zframe = ZoomFrame(self.app.RIGHT, 1.3, app) # zoom in, zoom out, reset zoom buttons #self.header = Header(self.zbframe, text="Zoom") self.zoomResetBtn = Button(self.zbframe, text='⊜', command=self.zoomReset, width=1.5, style="symbol.TButton", takefocus=0) #, pady=7 ) self.zoomInBtn = Button(self.zbframe, text='⊕', command=self.zoomIn, width=1.5, style="symbol.TButton", takefocus=0) self.zoomOutBtn = Button(self.zbframe, text='⊝', command=self.zoomOut, width=1.5, style="symbol.TButton", takefocus=0) # reset zoom keyboard shortcut if util.get_platform() == 'Linux': self.app.bind('<Control-0>', self.zoomReset) else: self.app.bind('<Command-0>', self.zoomReset) self.reset() self.grid() def zoomReset(self, fromButton=False): ''' reset zoom frame canvas and rebind it ''' if self.isLoaded(): # creates a new canvas object and we redraw everything to it self.zframe.resetCanvas() # self.zframe.canvas.bind('<Button-1>', self.app.onClickZoom ) # self.zframe.canvas.bind('<ButtonRelease-1>', self.app.onRelease ) # self.zframe.canvas.bind('<Motion>', self.app.onMotion ) # we want to go here only after a button press if fromButton: self.app.framesUpdate() def zoomIn(self): self.zframe.zoomIn() def zoomOut(self): self.zframe.zoomOut() def update(self, _frame=None): ''' change the image on the zoom frame ''' if self.reader and self.reader.loaded: self.zframe.setImage(self.reader.getFrame(_frame or self.app.frame)) def load(self, event=None): ''' brings a dicom file into memory if it exists ''' if LIBS_INSTALLED: if self.reader and not self.reader.loaded: self.reader.load() self.app.frame = 1 self.update() self.loadBtn['state'] = 'disabled' def chooseMethod(self, event=None): if self.mode: cls = LABEL_TO_READER[self.mode][self.method.get()] if self.mode == 'dicom': dcm = self.app.Data.checkFileLevel('.dicom') if dcm: if cls == DicomPNGReader and self.app.Data.getFileLevel( 'processed'): self.reader = cls(dcm, self.app.Data.path) else: self.reader = cls(dcm) else: self.reader = None elif self.mode == 'ult': ult = self.app.Data.checkFileLevel('.ult') meta = self.app.Data.checkFileLevel('US.txt') if ult and meta: self.reader = cls(ult, meta) else: self.reader = None self.zframe.resetImageDimensions() if not self.reader: self.loadBtn['state'] = 'disabled' elif self.reader.loaded: self.loadBtn['state'] = 'disabled' self.update() else: self.loadBtn['state'] = 'normal' def isLoaded(self): return self.reader and self.reader.loaded def getFrames(self, framenums): return [self.reader.getFrame(int(x)) for x in framenums] def getFrameTimes(self): if self.reader: return self.reader.getFrameTimes() elif self.mode == 'dicom': rd = DicomReader( self.app.Data.unrelativize( self.app.Data.getFileLevel('.dicom'))) return rd.getFrameTimes() elif self.mode == 'ult': rd = ULTScanLineReader( self.app.Data.unrelativize(self.app.Data.getFileLevel('.ult')), self.app.Data.unrelativize( self.app.Data.getFileLevel('US.txt'))) return rd.getFrameTimes() else: return [0] def reset(self): ''' new files should default to not showing dicom unless it has already been processed ''' # hide frame navigation widgets # self.grid_remove() self.zframe.shown = False self.zframe.setImage(None) self.frame.destroy() self.frame = Frame(self.frame_holder) self.frame.pack(expand=True) self.reader = None if self.app.Data.getFileLevel('.dicom'): self.mode = 'dicom' elif self.app.Data.getFileLevel('.ult'): self.mode = 'ult' else: self.mode = None self.method.set('') options = [x.label for x in READERS[self.mode]] or ['[no ultrasound]'] self.methodMenu = OptionMenu(self.frame, self.method, '---', *options, command=self.chooseMethod) self.methodMenu.grid(row=0) self.loadBtn = Button(self.frame, text='Load frames', command=self.load, takefocus=0, state='disabled') self.loadBtn.grid(row=1) if len(READERS[self.mode]) == 1: self.method.set(options[0]) self.chooseMethod() def grid(self): ''' Grid frame navigation, zoom reset, and Control (Undo/Redo) widgets ''' self.app.framesHeader.grid(row=0) self.app.framesPrevBtn.grid(row=0, column=0) self.app.framesEntryText.grid(row=0, column=1) self.app.framesEntryBtn.grid(row=0, column=2) self.app.framesNextBtn.grid(row=0, column=3) #self.header.grid(row=0, column=0, columnspan=5) self.zoomInBtn.grid(row=0, column=3) self.zoomResetBtn.grid(row=0, column=2) self.zoomOutBtn.grid(row=0, column=1) self.app.Control.grid() def grid_remove(self): ''' Remove widgets from grid ''' self.app.framesHeader.grid_remove() self.app.framesPrevBtn.grid_remove() self.app.framesEntryText.grid_remove() self.app.framesEntryBtn.grid_remove() self.app.framesNextBtn.grid_remove() self.zoomInBtn.grid_remove() self.zoomResetBtn.grid_remove() self.zoomOutBtn.grid_remove() self.app.Control.grid_remove()
class VoxGrab(Frame): def __init__(self, master=None): # Inherit from frame Frame.__init__(self, master) self.master = master self.queue = queue.Queue() # String vars self.directory = StringVar() self.status = StringVar() self.language = StringVar() self.language.set('EN') self.status.set("Please choose a folder") # Pseudo booleans self.check_flag = IntVar() self.check_flag.set(1) self.files = [] # Get languages try: self.languages = SubtitleDownloader.get_languages() # First element must be null, because tkinter makes no sense self.languages.insert(0, None) except Exception as e: msg = "Error when fetching languages, defaulting to English\n" \ + str(e) messagebox.showerror("Connection error", msg) self.languages = ['en'] # Create widgets # The "important" widgets needed later self.status_label = Label(self.master, textvariable=self.status) self.progress_bar = ttk.Progressbar(self.master, orient="horizontal", mode="determinate", length=620) self.file_area = Frame(self.master) self.folder_fame = Frame(self.master) self.button_frame = Frame(self.master) self.language_selector = OptionMenu(self.button_frame, self.language, *self.languages) self.canvas = Canvas(self.file_area, borderwidth=0, background=COLORS['grey'], width=600, height=400) self.file_frame = Frame(self.canvas) self.create_widgets() def create_widgets(self): """Create widgets, saves init from becoming ridiculous""" # Create labels title_label = Label(self.master, text='VoxGrab\nsubtitle downloader', font=16) # Create folder text input frame Entry(self.folder_fame, width=80, textvariable=self.directory).grid(column=0, row=1, padx=0, sticky=W) ttk.Button(self.folder_fame, text='Load files', command=self.load_files).grid(column=1, row=1, padx=10) # Create scrolling area and scroll bar scrollbar = Scrollbar(self.file_area, orient='vertical', command=self.canvas.yview) # Add title labels for columns Label(self.file_frame, text="File name", width="70", borderwidth="1", relief="solid").grid(row=0, column=0) Label(self.file_frame, text="Status", width="14", borderwidth="1", relief="solid").grid(row=0, column=1) # Configure, create & pack self.canvas.configure(yscrollcommand=scrollbar.set) self.canvas.create_window((4, 4), window=self.file_frame, anchor='nw', tags='self.file_frame') self.canvas.pack(side=LEFT) scrollbar.pack(side=RIGHT, fill=Y) # Create button pane Checkbutton(self.button_frame, text='Skip downloaded subs', variable=self.check_flag, justify=LEFT).grid(column=0, row=1, padx=10, sticky=W) Label(self.button_frame, text='Language:').grid(column=1, row=1) self.language_selector.grid(column=2, row=1, sticky=W) ttk.Button(self.button_frame, text='Choose folder', command=self.prompt_directory).grid(column=4, row=1, padx=10, sticky=E) ttk.Button(self.button_frame, text="Download subs", command=self.download_subs).grid(column=5, row=1, padx=10, sticky=E) self.button_frame.grid_columnconfigure(3, minsize=120) # Pack it all title_label.pack(pady=5) self.file_area.pack(padx=15, pady=5) self.progress_bar.pack() self.status_label.pack(pady=5) self.folder_fame.pack(pady=5) self.button_frame.pack(pady=5) # Bind scrolling self.file_frame.bind("<Configure>", self.onFrameConfigure) self.file_frame.bind('<Enter>', self._bound_to_mousewheel) self.file_frame.bind('<Leave>', self._unbound_to_mousewheel) self.master.bind('<Return>', self.load_files) def onFrameConfigure(self, event): """Reset the scroll region to encompass the inner file_frame""" self.canvas.configure(scrollregion=self.canvas.bbox("all")) def _bound_to_mousewheel(self, event): """Bind mousewheel to scroll function""" self.canvas.bind_all("<MouseWheel>", self._on_mousewheel) def _unbound_to_mousewheel(self, event): """Unbind mousewheel""" self.canvas.unbind_all("<MouseWheel>") def _on_mousewheel(self, event): """Scrolling function""" self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units") def prompt_directory(self): """Prompt for directory, load files and populate gui""" self.directory.set(filedialog.askdirectory()) self.load_files() def load_files(self, *args): try: self.files = self.sort_files(os.listdir(path=self.directory.get())) self.populate() if len(self.files) > 0: self.status.set("Click Download") else: self.status.set("No media in folder") except FileNotFoundError: self.status.set("That's not a folder") def clear_download_frame(self): """Clears file_frame""" for widget in self.file_frame.winfo_children(): widget.destroy() def populate(self): """Populate/refresh file_frame""" self.clear_download_frame() # Re-create title labels for columns Label(self.file_frame, text="File name", width="70", borderwidth="1", relief="solid").grid(row=0, column=0) Label(self.file_frame, text="Status", width="14", borderwidth="1", relief="solid").grid(row=0, column=1) for i, file in enumerate(self.files): Label(self.file_frame, text=file["fileName"], width=70, borderwidth="1", relief="solid").grid(row=i+1, column=0) Label(self.file_frame, text=file["status"], width="14", borderwidth="1", relief="solid", bg=file["color"]).grid(row=i+1, column=1) file["row"] = i+1 @staticmethod def sort_files(files): """Sort out non media files""" media_files = [] for file in files: media_re = re.search(r"^[\s\S]*?\.(mp4|avi|mkv|m4v)$", file) if media_re: context = {"fileName": file, "status": "Waiting", "color": COLORS["azure"]} media_files.append(context) else: pass return media_files def download_subs(self): """ Attempt to download subs to all files in self.files and set status label """ if len(self.files) > 0: # Prepare downloader os.chdir(self.directory.get()) downloader = SubtitleDownloader(self.check_flag.get(), lang=self.language.get()) for _file in self.files: self.queue.put(_file) parent_thread = threading.Thread(target=self._parent, args=(downloader, )) parent_thread.start() else: self.status.set('No subtitles to download') def _parent(self, downloader): """ Parent thread for maneging workers. Allows for the UI to be update once the download is completed without blocking the GUI thread :param downloader: SubtitleDownloader to be handed over to workers :return: None """ threads = [] # Prepare the GUI self.progress_bar.configure(maximum=len(self.files)) self.status.set('Downloading subtitles.') for child in (self.folder_fame.winfo_children() + self.button_frame.winfo_children()): child.configure(state=DISABLED) # Start threads for n in range(min(10, len(self.files))): thread = threading.Thread(target=self._worker, args=(downloader,)) thread.start() threads.append(thread) # Wait for them to finish for thread in threads: thread.join() # Update GUI for child in (self.folder_fame.winfo_children() + self.button_frame.winfo_children()): child.configure(state=NORMAL) self.status.set('Done!') def _worker(self, downloader): """ Worker thread downloading subtitles also updates the file_frame labels and progress bar :param downloader: SubtitleDownloader for API interaction :return: None """ while True: # Get a move file from queue try: _file = self.queue.get(block=False) except queue.Empty: return # Download sub downloader.download_sub(_file) # Replace the corresponding label label_config = { 'text': _file['status'], 'width': 14, 'borderwidth': '1', 'relief': 'solid', 'bg': _file['color'] } Label(self.file_frame, **label_config).grid(row=_file["row"], column=1) self.progress_bar.step()
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 ManualIntegrationPage(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.controller = parent title = Label(self, text="Manual Integration", font=("Arial", 14, "bold")) title.grid(row=0, column=0, columnspan=6) self.f = Figure(figsize=(5, 5), dpi=100) self.a = self.f.add_subplot(111) Label(self, text="Match to Element", font=("Arial", 14)).grid(row=1, column=5) Label(self, text="Lower Bound: ").grid(row=7, column=0) self.lowerBound = Entry(self) self.lowerBound.grid(row=7, column=1) Label(self, text="Upper Bound: ").grid(row=7, column=2) self.upperBound = Entry(self) self.upperBound.grid(row=7, column=3) integrateButton = Button(self, text="Integrate", command=self.submit) integrateButton.grid(row=7, column=4) Button(self, text="Back", command=self.back).grid(row=8, column=0) self.curMenu = None def populate_values(self, energies, cps): self.energies = energies self.cps = cps self.a.cla() self.a.plot(energies, cps, "b-") self.canvas = FigureCanvasTkAgg(self.f, self) self.canvas.draw() self.canvas.get_tk_widget().grid(row=1, column=0, columnspan=5, rowspan=5) def add_peak_selector(self, poss): self.poss = poss if self.curMenu != None: self.curMenu.destroy() self.selected = StringVar(self.controller) self.selected.set("Select Element") opts = ["Select Element"] + [p[0] + ": " + str(p[1]) for p in poss] #Stupid tkinter workaround self.curMenu = OptionMenu(self, self.selected, *opts) self.curMenu.grid(row=2, column=5) def back(self): self.controller.show_frame(ReviewFitPage) def submit(self): try: lowBound = float(self.lowerBound.get()) highBound = float(self.upperBound.get()) except ValueError: messagebox.showinfo("Error", "Use numbers for the bounds please!") return None if lowBound > highBound: messagebox.showinfo( "Error", "Lower bound cannot be greater than upper bound!") return None if lowBound < self.energies[0] or highBound > self.energies[-1]: messagebox.showinfo("Error", "Bounds must be within data bound") return None if self.selected.get() == "Select Peak": messagebox.showinfo("Error", "Select a peak match!") return None #do integration #TODO: Infinite loop here i think i = 0 while self.energies[i] < lowBound: i += 1 j = i while self.energies[j] < highBound: j += 1 #trapezoidal sum startEnergy = self.energies[i] endEnergy = self.energies[j] n = j - i + 1 area = (self.energies[j] - self.energies[i]) / (2 * (j - i + 1)) * ( sum(self.cps[i:j + 1]) + sum(self.cps[i + 1:j])) peak = [] element, loc = self.selected.get().split(": ") for i in self.poss: if i[0] == element and str(i[1]) == loc: peak = i self.controller.add_mi_peak(peak, area, startEnergy, endEnergy, n) self.controller.increment_peak_counter() self.curMenu.destroy()
class Parameters_wind(object): #Here y= row and x = column def __init__(self, master): self._rules = "RL" self._Game = [] self._indice = 0 frame = Frame(master) frame.grid() tabControl = ttk.Notebook(master) tabControl.configure(width=420, height=600) self.main_tab = ttk.Frame(tabControl) tabControl.add(self.main_tab, text="Settings") tabControl.grid() self.about_tab = ttk.Frame(tabControl) tabControl.add(self.about_tab, text="About") tabControl.grid() self.dimension = IntVar() self.dimension.set(value=50) self.chkValue = BooleanVar() self.chkValue.set(True) self.chkValue_two = BooleanVar() self.chkValue_two.set(False) self.nbr_of_ant = IntVar() self.nbr_of_ant.set(value=1) self.speed_opts = ['0', '1000', '500', '250', '100', '50', '10', '0'] self.speed = StringVar() self.black_case_nbr = IntVar() self.black_case_nbr.set(value=0) self.about_page() self.main_page() def main_page(self): self.label_dimension = Label( self.main_tab, text="How many row and column do you want ?") self.label_dimension.grid(column=0, row=0, sticky='w') self.scale_dimension = Scale(self.main_tab, orient='horizontal', from_=25, to=200, variable=self.dimension, tickinterval=25, length=200) self.scale_dimension.grid(column=0, row=1, padx=5, pady=5) self.frame_dimension = Labelframe(self.main_tab, text="Order of ideas :", height=60, width=300) self.frame_dimension.grid(column=0, row=2, sticky='w') dimension_frame_label = [ "<50 this is a bit small", "50<x<150 ideal dimension", ">150 quite such huge" ] for i in range(len(dimension_frame_label)): texte = dimension_frame_label[i] self.dimension_frame_label = Label(self.frame_dimension, text=f"{texte}") self.dimension_frame_label.grid(column=0, row=i, sticky='w') self.dimension_frame_label.grid(column=0, row=2, sticky='w') self.label_ant = Label(self.main_tab, text="How many ant(s) do you want ?") self.label_ant.grid(column=0, row=3, sticky='w') self.scale_ant = Scale(self.main_tab, orient='horizontal', from_=1, to=10, variable=self.nbr_of_ant, tickinterval=2, length=200) self.scale_ant.grid(column=0, row=4, padx=5, pady=5) self.speed_label = Label(self.main_tab, text="Delay in millisecond :") self.speed_label.grid(column=0, row=5, sticky='w') self.speed_menu = OptionMenu(self.main_tab, self.speed, *self.speed_opts) self.speed_menu.grid(column=1, row=5, sticky='w') self.black_case_label = Label(self.main_tab, text="Percentage of black cells :") self.black_case_label.grid(column=0, row=6, sticky='w') self.black_case = Scale(self.main_tab, orient='horizontal', from_=0, to=99, variable=self.black_case_nbr, tickinterval=10, length=200) self.black_case.grid(column=0, row=7, padx=5, pady=5) self.frame_rules = Labelframe(self.main_tab, text="Rules setting:", height=100, width=400) self.frame_rules.grid(column=0, row=8, sticky='w') self.label_rules = Label(self.frame_rules, text="Rules :" + str(self._rules)) self.label_rules.grid(column=0, row=0, sticky='w', columnspan=3) self.button_F = Button(self.frame_rules, text="F", command=self.F) self.button_F.grid(column=1, row=1, padx=5, pady=5) self.button_L = Button(self.frame_rules, text="L", command=self.L) self.button_L.grid(column=0, row=2, padx=5, pady=5) self.button_clean = Button(self.frame_rules, text="Clean", command=self.clean) self.button_clean.grid(column=1, row=2, padx=5, pady=5) self.button_R = Button(self.frame_rules, text="R", command=self.R) self.button_R.grid(column=2, row=2, padx=5, pady=5) self.button_B = Button(self.frame_rules, text="B", command=self.B) self.button_B.grid(column=1, row=3, padx=5, pady=5) self.chk = Checkbutton(self.main_tab, text='Grid', var=self.chkValue) self.chk.grid(column=0, row=9) self.chk_two = Checkbutton(self.main_tab, text='Desctructive collision', var=self.chkValue_two) self.chk_two.grid(column=1, row=9) self.button_simulator = Button(self.main_tab, text="Go to simulation auto", command=self.simulation_ants) self.button_simulator.grid(column=0, row=10) self.button_simulator_steps = Button( self.main_tab, text="Go to simulation step by step", command=self.simulation_steps) self.button_simulator_steps.grid(column=1, row=10, pady=15) def about_page(self): self.ligne = 0 about_label = [ "Students in the project :", " -Esteban Mathia", " -Victor Minne", " -Tom Cleenewerck" ] for i in range(len(about_label)): texte = about_label[i] self.about_label = Label(self.about_tab, text=f"{texte}") self.about_label.grid(column=0, row=self.ligne, sticky='w') self.ligne += 1 esteban = [ "Esteban :", " +33675549372", " [email protected]" ] victor = ["Victor :", " +33611815452", " [email protected]"] tom = ["Tom :", " +33750370032", " [email protected]"] info_contribuator = [esteban, victor, tom] for i in range(len(info_contribuator)): for j in range(len(info_contribuator[i])): texte = info_contribuator[i][j] self.about_label = Label(self.about_tab, text=f"{texte}") self.about_label.grid(column=0, row=self.ligne, sticky='w') self.ligne += 1 def F(self): if len(self._rules) < 12: self._rules += "F" else: messagebox.showinfo("Info", "You arrive to maximum rules") self.actu_rules() def L(self): if len(self._rules) < 12: self._rules += "L" else: messagebox.showinfo("Info", "You arrive to maximum rules") self.actu_rules() def R(self): if len(self._rules) < 12: self._rules += "R" else: messagebox.showinfo("Info", "You arrive to maximum rules") self.actu_rules() def B(self): if len(self._rules) < 12: self._rules += "B" else: messagebox.showinfo("Info", "You arrive to maximum rules") self.actu_rules() def clean(self): self._rules = "" self.actu_rules() def actu_rules(self): self.label_rules.config(text="Rules :" + str(self._rules)) def simulation_ants(self): threading._start_new_thread(self.new_board, ()) self._Game.append("") time.sleep(0.2) self._indice += 1 def new_board(self): row = self.dimension.get() column = self.dimension.get() number_of_ant = self.nbr_of_ant.get() speed = int(self.speed.get()) / 1000 percentage = self.black_case_nbr.get() border = self.chkValue.get() collision = self.chkValue_two.get() if len(self._rules) > 0: self._Game[self._indice] = Board_multiple_ants( collision, self._rules, border, self._indice, row, column, percentage, number_of_ant, speed) else: messagebox.showwarning( "Warning", "The Rules are incorrect, please complete it") def simulation_steps(self): threading._start_new_thread(self.new_board_steps, ()) self._Game.append("") time.sleep(0.2) self._indice += 1 def new_board_steps(self): row = self.dimension.get() column = self.dimension.get() number_of_ant = self.nbr_of_ant.get() percentage = self.black_case_nbr.get() border = self.chkValue.get() collision = self.chkValue_two.get() if len(self._rules) > 0: self._Game[self._indice] = Simulator_steps(collision, self._rules, self._indice, row, column, percentage, number_of_ant, border) else: messagebox.showwarning( "Warning", "The Rules are incorrect, please complete it")
def create_widgets(self): padx = 5 pady = 5 Label(self, text="Watermark options", font=14).pack(anchor=W) # --------- Position options --------- pos_options = Frame(self) Label(pos_options, text="Position").pack(anchor=W) # -- Padding -- validate = (self.register(self.validate_int), '%P') padding_frame = Frame(pos_options) # Horizontal padding Label(padding_frame, text="Pad x").grid(column=0, row=0) Entry(padding_frame, textvariable=self.padx, validate="key", width=5, validatecommand=validate).grid(column=1, row=0, padx=padx) OptionMenu(padding_frame, self.unit_x, *self.unit_options).grid(column=3, row=0) # Vertical padding Label(padding_frame, text="Pad y").grid(column=0, row=1) Entry(padding_frame, textvariable=self.pady, validate="key", width=5, validatecommand=validate).grid(column=1, row=1, padx=padx, pady=pady) OptionMenu(padding_frame, self.unit_y, *self.unit_options).grid(column=3, row=1) padding_frame.pack(side=LEFT) pos_frame = Frame(pos_options) radio_pad = 5 # -- Position -- Radiobutton(pos_frame, text="Top left", variable=self.position, value="NW").grid(column=0, row=0, sticky=W, padx=radio_pad, pady=radio_pad) Radiobutton(pos_frame, text="Top right", variable=self.position, value="NE").grid(column=1, row=0, sticky=W, padx=radio_pad, pady=radio_pad) Radiobutton(pos_frame, text="Bottom left", variable=self.position, value="SW").grid(column=0, row=1, padx=radio_pad, pady=radio_pad) Radiobutton(pos_frame, text="Bottom right", variable=self.position, value="SE").grid(column=1, row=1, padx=radio_pad, pady=radio_pad) pos_frame.pack(side=LEFT, padx=30) pos_options.pack(anchor=W) # ---------- Opacity options --------- Label(self, text="Opacity and size").pack(anchor=W) opacity_frame = Frame(self) Label(opacity_frame, text="Opacity").pack(side=LEFT, anchor=S) Scale(opacity_frame, from_=0, to=100, orient=HORIZONTAL, variable=self.opacity).pack(side=LEFT, anchor=N, padx=5) Entry(opacity_frame, textvariable=self.opacity, width=4, validate="key", validatecommand=validate).pack(side=LEFT, anchor=S, pady=3) Label(opacity_frame, text="%").pack(side=LEFT, anchor=S, pady=3) opacity_frame.pack(anchor=W) # ----------- Size options ----------- Checkbutton(self, text="Auto resize watermark", variable=self.scale_watermark, onvalue=True, offvalue=False).pack(anchor=W, pady=(5, 0))
def main(): Tk().withdraw() crime_data_file = askopenfilename(filetypes=[("Comma Separated Values", "*.csv")], title="Select city crime data file") crimes = read_crimes(crime_data_file) vector_crime_map = VectorCrimeMap(crimes) window = Tk() window.title("BMORE SAFE") Label(window, text="starting coordinates (Latitude,Longitude").grid(row=0) Label(window, text="ending coordinates (Latitude,Longitude)").grid(row=1) init_lat_entry = Entry(window) init_lon_entry = Entry(window) final_lat_entry = Entry(window) final_lon_entry = Entry(window) init_lat_entry.grid(row=0, column=1) init_lon_entry.grid(row=0, column=2) final_lat_entry.grid(row=1, column=1) final_lon_entry.grid(row=1, column=2) init_latlon_var = StringVar(window) init_latlon_var.set("Preset coords...") final_latlon_var = StringVar(window) final_latlon_var.set("Preset coords...") preset_destinations = { "Homewood Campus", "Medical Campus", "National Aquarium", "BWI Airport", "Cherry Hill" } preset_destination_coordinate_dict = { "Homewood Campus": LatLon(39.329903, -76.620522), "Medical Campus": LatLon(39.299681, -76.593301), "National Aquarium": LatLon(39.286736, -76.608363), "BWI Airport": LatLon(39.177213, -76.668371), "Cherry Hill": LatLon(39.2548293, -76.634412) } init_preset_destinations_dropdown = OptionMenu(window, init_latlon_var, "Preset coords...", *preset_destinations) final_preset_destinations_dropdown = OptionMenu(window, final_latlon_var, "Preset coords...", *preset_destinations) def _set_entry_text(entry, text): entry.delete(0, END) entry.insert(0, str(text)) def _on_change_init_destination_from_dropdown(*args): latlon = preset_destination_coordinate_dict[init_latlon_var.get()] _set_entry_text(init_lat_entry, latlon.lat) _set_entry_text(init_lon_entry, latlon.lon) def _on_change_final_destination_from_dropdown(*args): latlon = preset_destination_coordinate_dict[final_latlon_var.get()] _set_entry_text(final_lat_entry, latlon.lat) _set_entry_text(final_lon_entry, latlon.lon) init_latlon_var.trace("w", _on_change_init_destination_from_dropdown) final_latlon_var.trace("w", _on_change_final_destination_from_dropdown) init_preset_destinations_dropdown.grid(row=0, column=3) final_preset_destinations_dropdown.grid(row=1, column=3) def _process_latlon_input(): init_latlon = LatLon(float(init_lat_entry.get()), float(init_lon_entry.get())) final_latlon = LatLon(float(final_lat_entry.get()), float(final_lon_entry.get())) get_request_response = get_route_json(init_latlon, final_latlon) route_json = json.loads(get_request_response) routes = parse_route_json(route_json) for route in routes: route.crime_score = vector_crime_map.score_route(route) min_crime_score = math.inf min_crime_route = routes[0] for route in routes: if route.crime_score < min_crime_score: min_crime_score = min_crime_route.crime_score min_crime_route = route directions = "" direction_number = 1 for narrative in min_crime_route.narratives: directions += str(direction_number) + ". " + narrative + "\n\n" direction_number += 1 draw_routes(routes).show() showinfo(title="Safest Directions", message=directions) Button(window, text="Go", command=_process_latlon_input).grid(row=3, column=0) mainloop()
def main_page(self): self.label_dimension = Label( self.main_tab, text="How many row and column do you want ?") self.label_dimension.grid(column=0, row=0, sticky='w') self.scale_dimension = Scale(self.main_tab, orient='horizontal', from_=25, to=200, variable=self.dimension, tickinterval=25, length=200) self.scale_dimension.grid(column=0, row=1, padx=5, pady=5) self.frame_dimension = Labelframe(self.main_tab, text="Order of ideas :", height=60, width=300) self.frame_dimension.grid(column=0, row=2, sticky='w') dimension_frame_label = [ "<50 this is a bit small", "50<x<150 ideal dimension", ">150 quite such huge" ] for i in range(len(dimension_frame_label)): texte = dimension_frame_label[i] self.dimension_frame_label = Label(self.frame_dimension, text=f"{texte}") self.dimension_frame_label.grid(column=0, row=i, sticky='w') self.dimension_frame_label.grid(column=0, row=2, sticky='w') self.label_ant = Label(self.main_tab, text="How many ant(s) do you want ?") self.label_ant.grid(column=0, row=3, sticky='w') self.scale_ant = Scale(self.main_tab, orient='horizontal', from_=1, to=10, variable=self.nbr_of_ant, tickinterval=2, length=200) self.scale_ant.grid(column=0, row=4, padx=5, pady=5) self.speed_label = Label(self.main_tab, text="Delay in millisecond :") self.speed_label.grid(column=0, row=5, sticky='w') self.speed_menu = OptionMenu(self.main_tab, self.speed, *self.speed_opts) self.speed_menu.grid(column=1, row=5, sticky='w') self.black_case_label = Label(self.main_tab, text="Percentage of black cells :") self.black_case_label.grid(column=0, row=6, sticky='w') self.black_case = Scale(self.main_tab, orient='horizontal', from_=0, to=99, variable=self.black_case_nbr, tickinterval=10, length=200) self.black_case.grid(column=0, row=7, padx=5, pady=5) self.frame_rules = Labelframe(self.main_tab, text="Rules setting:", height=100, width=400) self.frame_rules.grid(column=0, row=8, sticky='w') self.label_rules = Label(self.frame_rules, text="Rules :" + str(self._rules)) self.label_rules.grid(column=0, row=0, sticky='w', columnspan=3) self.button_F = Button(self.frame_rules, text="F", command=self.F) self.button_F.grid(column=1, row=1, padx=5, pady=5) self.button_L = Button(self.frame_rules, text="L", command=self.L) self.button_L.grid(column=0, row=2, padx=5, pady=5) self.button_clean = Button(self.frame_rules, text="Clean", command=self.clean) self.button_clean.grid(column=1, row=2, padx=5, pady=5) self.button_R = Button(self.frame_rules, text="R", command=self.R) self.button_R.grid(column=2, row=2, padx=5, pady=5) self.button_B = Button(self.frame_rules, text="B", command=self.B) self.button_B.grid(column=1, row=3, padx=5, pady=5) self.chk = Checkbutton(self.main_tab, text='Grid', var=self.chkValue) self.chk.grid(column=0, row=9) self.chk_two = Checkbutton(self.main_tab, text='Desctructive collision', var=self.chkValue_two) self.chk_two.grid(column=1, row=9) self.button_simulator = Button(self.main_tab, text="Go to simulation auto", command=self.simulation_ants) self.button_simulator.grid(column=0, row=10) self.button_simulator_steps = Button( self.main_tab, text="Go to simulation step by step", command=self.simulation_steps) self.button_simulator_steps.grid(column=1, row=10, pady=15)
class TimelapseGUI(): # CLASS CONSTANTS READY_TEXT = "Ready!" ICON_NAME = "assets/favicon.png" MIN_WIDTH = 500 MIN_HEIGHT = 300 CHOICES = [ 'Choose Speed', '2x', '5x', '10x', '20x', '30x', '50x', '100x', '200x', '300x', '500x', '1000x', ] SUPPORTED_FORMATS = [ '.mp4', '.webm', '.mpg', '.avi', '.mov', '.m4v', '.flv', '.mkv' ] def __init__(self): """ __init__ Initializes the GUI elements """ # variables self.files = None self.file_status = None self.var_open_files = None self.progress = None # Root Window Properties self.root = Tk() self.root.title("Timelapse Creator") self.root.minsize(self.MIN_WIDTH, self.MIN_HEIGHT) # This part is to make sure that the program runs with or without n icon file. try: if os.path.exists(self.ICON_NAME): self.icon = PhotoImage(file=self.ICON_NAME) self.root.iconphoto(False, self.icon) elif os.path.exists(os.path.split(self.ICON_NAME)[-1]): self.icon = PhotoImage(file=os.path.split(self.ICON_NAME)[-1]) self.root.iconphoto(False, self.icon) except Exception as e: print(f"Could not load Icon due to Error: {e}") # Buttons and Widgets self.config_frames() self.config_buttons() self.config_progress_bar() self.config_label() def config_frames(self): """ config_frames Set up the different sections of the GUI window """ # BUTTON SPACE self.buttons_frame = Frame(self.root) self.buttons_frame.grid(row=0, column=0, columnspan=3, padx=10, pady=10, sticky=E + W) # PROGRESS BAR SPACE self.progress_frame = Frame(self.root) self.progress_frame.grid(row=1, column=0, columnspan=3, padx=10, pady=10, sticky=E + W) # Configure how many rows and columns are there in and progress_frame self.root.columnconfigure(0, weight=1) self.root.rowconfigure(1, weight=1) self.progress_frame.columnconfigure(0, weight=1) self.progress_frame.rowconfigure(0, weight=1) def config_buttons(self): """ config_buttons Define the interactive Buttons used for the GUI App """ # Open File Browser Button self.btn_open_files = Button(self.buttons_frame, command=self.browseFiles, text='Select Videos') self.btn_open_files.grid(row=0, column=0, padx=(10), pady=10) # Dropdown Selector button self.var_open_files = StringVar(self.buttons_frame) self.dropdown_button = OptionMenu(self.buttons_frame, self.var_open_files, *self.CHOICES) self.dropdown_button.grid(row=0, column=1, padx=(10), pady=10) # Convert Button self.btn_convert = Button(self.buttons_frame, text='Convert', command=self.convert_video) self.btn_convert.grid(row=0, column=2, padx=(10), pady=10) def config_progress_bar(self): """ config_progress_bar Configure the Progress bar """ self.progress = Progressbar(self.progress_frame, orient=HORIZONTAL, length=100, mode='determinate') self.progress.grid(row=1, column=0, sticky=E + W) def config_label(self): """ config_label Add the Dynamic labels for progress tracking """ self.file_status = Label(self.progress_frame, text=self.READY_TEXT) self.file_status.grid(row=0, column=0, padx=(10), pady=10) self.file_status_percent = Label(self.progress_frame, text="0%") self.file_status_percent.grid(row=1, column=0, padx=(0), pady=0) def run(self): """ run Run the GUI Loop. """ self.root.mainloop() def file_format_generator(self, formats: list): """ file_format_generator Generates the required file format - helper function Takes a List of strings as input, adds their upper case versions as well Converts them to a space separated string, and returns the same Args: formats (list): comma separated strings of file extensions in lower case Returns: string: space separated file extensions along with corresponding upper case format """ formats = formats + [value.upper() for value in formats] return " ".join(formats) def browseFiles(self): """ browseFiles Creates the File Selector dialogbox Returns: boolean: True if valid file is selected, False if invalid """ self.files = filedialog.askopenfilenames( # initialdir="/media/Data/Downloads/", title="Videos", filetypes=(("Video Files", self.file_format_generator(self.SUPPORTED_FORMATS)), )) # Check file validity valid = bulk_validate_video(self.files) if not valid: messagebox.showerror( title="Invalid File", message="The File that you entered is invalid. Please retry!") return False return True def convert_video(self): """ convert_video Main video converter function Uses OpenCV to read and write the video While skipping frames based on the given input Returns: boolean: Returns True or False based on success or failure """ # Warning Box for if proper files have not been selected if not self.files: messagebox.showwarning( title="File Not Selected", message= "You have not selected any file. Please Click on \"Select Videos\"" ) return False # Extract the multiplier number fps_multiplier = self.var_open_files.get() if not fps_multiplier: return False # If invalid multiplier selected, raise warning try: fps_multiplier = int(fps_multiplier[:-1]) except Exception as e: messagebox.showwarning( title="Select Speed", message= "Please Select Speed of the video from the dropdown menu") return True # Disable the button during converstion to avoid multiple inputs self.btn_convert["state"] = "disabled" # Start the main conversion in a different thread to avoid UI freeze _thread.start_new_thread(bulk_video_converter, (self.files, fps_multiplier, None, self.file_status, self.file_status_percent, self.progress, self.root, self.btn_convert))
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()