def __init__(self, master, pakli, kep, nev, ertek, fuggveny, megtekint): Toplevel.__init__(self) self.master = master self.pakli = pakli self.nev = nev self.ertek = ertek self.fuggveny = fuggveny self.bezar = self.destroy cim = self.master.card_texts[self.nev][0] if self.nev == 'treasure': szoveg = self.master.card_texts[self.nev][1] % ertek else: szoveg = self.master.card_texts[self.nev][1] self.title(s.language.event_card if self.pakli == "event" else s.language.treasure_card) cimStilus = 'helvetica 14 bold' self.kartyalap = Frame(self, relief=GROOVE, bd=2, bg='ivory') Label(self.kartyalap, image=Gallery.get(kep)).pack() Separator(self.kartyalap, orient=HORIZONTAL).pack(fill=X) Label(self.kartyalap, wraplength=216, text=cim, font=cimStilus).pack(fill=X) Separator(self.kartyalap, orient=HORIZONTAL).pack(fill=X) self.szovegfelirat = Label(self.kartyalap, wraplength=216, text=szoveg) self.szovegfelirat.pack(fill=X) self.kartyalap.pack(pady=5, padx=5) if megtekint: pass else: exec(self.fuggveny) self.protocol("WM_DELETE_WINDOW", self.bezar) self.transient(self.master) self.resizable(False, False)
def initItems(self): """Initialize all widgets here""" # First way to create a frame frame = Frame(self) frame['padding'] = (5, 10) frame['borderwidth'] = 2 frame['relief'] = 'sunken' frame.pack(fill='both') lbl = Label(frame, text='sunken!') lbl.pack() lbl2 = Label(frame, text='_2!') lbl2.pack() # The second way to create a frame frame2 = Frame(self, borderwidth=2, relief='raised') # or constant tkinter.RAISED frame2.pack(fill='both') Label(frame2, text='raised').grid(row=1, column=1, sticky='w') Label(frame2, text='2col 2row').grid(row=2, column=2, sticky='we') Label(frame2, text='3col 3row', relief='raised', anchor='center', wraplength=50, width='7').grid(row=3, column=3, columnspan=2, sticky='we') Label(frame2, text='5col 5row').grid(row=4, column=5, sticky='e') # The first way to create a separator - with Frame sep1 = Frame(self, height=2, borderwidth=1, relief='sunken') sep1.pack(fill=X, padx=5, pady=10) Label(self, text='Between the separators').pack() # The second way to create a Separator - with tkinter.ttk.Separator sep = Separator(self, orient=tkinter.HORIZONTAL) sep.pack(fill=X, padx=5, pady=10)
def init_ui(self): self.segmentation_config_frame = SegmentationConfigFrame(self, self.configuration) Label(self, text="Segmentation").grid(row=0, column=0, sticky="w") self.segmentation_config_frame.grid(row=0, column=1, sticky="w") Separator(self, orient=HORIZONTAL).grid(row=1, column=0, sticky="ew", columnspan=2) self.spm_config_frame = SpmConfigFrame(self, self.configuration) Label(self, text="Color detection").grid(row=2, column=0, sticky="w") self.spm_config_frame.grid(row=2, column=1, sticky="w") Separator(self, orient=HORIZONTAL).grid(row=3, column=0, sticky="ew", columnspan=2) self.texture_config_frame = TextureConfigFrame(self, self.configuration) Label(self, text="Texture detection").grid(row=4, column=0, sticky="w") self.texture_config_frame.grid(row=4, column=1, sticky="w") Separator(self, orient=HORIZONTAL).grid(row=5, column=0, sticky="ew", columnspan=2) self.size_config_frame = SizeConfigFrame(self, self.configuration) Label(self, text="Image size").grid(row=6, column=0, sticky="w") self.size_config_frame.grid(row=6, column=1, sticky="w") Separator(self, orient=HORIZONTAL).grid(row=7, column=0, sticky="ew", columnspan=2) self.detection_path_frame = DetectionPathFrame(self, self.configuration) Label(self, text="Input image").grid(row=8, column=0, sticky="w") self.detection_path_frame.grid(row=8, column=1, sticky="w") Separator(self, orient=VERTICAL).grid(row=0, column=2, sticky="ns", rowspan=9)
def __init__(self, master, **kwargs): Frame.__init__(self, master) self.autoscroll_check = Checkbutton(self, text='Autoscroll', takefocus=False) self.autoscroll_check.pack(side=LEFT, anchor=W, padx=8) Separator(self, orient=VERTICAL).pack(side=LEFT, fill=Y, pady=2) Label(self, text='Size:').pack(side=LEFT, padx=(8, 3)) self.font_down_button = Button(self, text='-', width=3, takefocus=False) self.font_down_button.pack(side=LEFT) self.font_size_label = Label(self, text='24', padding=(6, 2, 6, 2), relief=SOLID, borderwidth=1) self.font_size_label.pack(side=LEFT, padx=4) self.font_up_button = Button(self, text='+', width=3, takefocus=False) self.font_up_button.pack(side=LEFT, padx=(0, 8)) Separator(self, orient=VERTICAL).pack(side=LEFT, fill=Y, pady=2) Label(self, text='Speed:').pack(side=LEFT, padx=(8, 3)) self.speed_control_frame = SpeedControlFrame(self) self.speed_control_frame.pack(side=LEFT, padx=(0, 8)) Separator(self, orient=VERTICAL).pack(side=LEFT, fill=Y, pady=2) self.always_on_top_check = Checkbutton(self, text='Top', takefocus=False) self.always_on_top_check.pack(side=LEFT, padx=(8, 0))
def __init__(self, parent, **optional_arguments): tkinter.LabelFrame.__init__(self, parent, text=optional_arguments['text']) self.colors = None # setup default parameters and then process optional arguments self.field_count = default_field_count self.process_optional_arguments(optional_arguments) # setup the table showing initial balance, current balance, and expenditure totals self.totals_table: TableWidget = None self.load_total_amounts() # sets up a separator between the two tables separator = Separator(self) separator.grid(row=0, column=1, sticky="NS") # setup the table showing spending by category self.category_table: TableWidget = None self.load_spending_by_category() # setup the pie chart self.pie_chart = PieChart(self) self.pie_chart.grid(row=1, columnspan=3) self.load_table_data(None, None, None)
def __init__(self, main): super(ElementsFrame, self).__init__(main.screen) s = Style() s.configure('my.TButton', font=('Arial', 16)) self.main = main self.ask = None # RESPECT PEP8 self.title = Label(self, text=main.lang.get_translate( "elements_title", "Elements"), font=('Arial', '16')) add_element = Button(self, text=main.lang.get_translate( "elements_add", "Add Element"), style="my.TButton", command=self.add_elements) self.columnconfigure(0, weight=1) self.title.grid(row=0, column=0) Separator(self, orient=HORIZONTAL).grid(row=1, column=0, sticky="EW") add_element.grid(row=2, column=0, sticky="NESW", pady=5) Separator(self, orient=HORIZONTAL).grid(row=3, column=0, sticky="EW") self.elements_widgets = {} self.current_row = 4
class TkFrameInfo(Frame): def __init__(self, w, text: str, lbl_width: int, info_width: int, info_bg: str, *args, **kwargs): super().__init__(w, *args, **kwargs) self.lbl = Label(self, width=lbl_width, text=text) self.lbl.grid(row=0, column=0) self.info = Entry(self, width=info_width, readonlybackground=info_bg, borderwidth=0, justify="left", state="readonly") self.info.grid(row=0, column=1) self.sep = Separator(self, orient="horizontal") self.sep.grid(row=1, column=0, columnspan=2, sticky="new") def insert(self, text): self.info["state"] = "normal" self.info.delete(0, "end") self.info.insert(0, text) self.info["state"] = "readonly" def get(self) -> str: return self.info.get()
def create_widgets(self): ''' Creates widgets of this object. ''' yScrollbar = Scrollbar(self, orient=VERTICAL) yScrollbar.grid(row=2, column=3, sticky=N+S) canvas = StyledCanvas(self, height=HEIGHT_WITHOUT_CHECKBOXES, yscrollcommand=yScrollbar.set) self.canvas = canvas canvas.grid(row=2, column=0, columnspan=3, sticky=N+E+W) self._config_columns(self) canvas.columnconfigure(0, weight=1) if self.add_headers: non_discr_lbl = Label(self, text='Non-\ndiscretionary') non_discr_lbl.grid(row=0, column=1, padx=3, pady=1) weakly_disp_lbl = Label(self, text='Weakly\ndisposable') weakly_disp_lbl.grid(row=0, column=2, padx=3, pady=1) sep = Separator(self) sep.grid(row=1, column=0, columnspan=3, sticky=E+W, pady=10, padx=3) self.frame_with_boxes = Frame(canvas) self._config_columns(self.frame_with_boxes) self.frame_with_boxes.grid(sticky=N+S+W+E, pady=15, padx=3) canvas.create_window(0, 0, window=self.frame_with_boxes, anchor=N+W) canvas.update_idletasks() canvas['scrollregion'] = (0, 0, 0, HEIGHT_WITHOUT_CHECKBOXES) yScrollbar['command'] = canvas.yview MouseWheel(self).add_scrolling(canvas, yscrollbar=yScrollbar)
def create_widgets(self): self.refresh_btn = Button(self, text='Refresh') self.sep1 = Separator(self) self.process_btn = Button(self, text='Process All') self.refresh_btn.pack(side=LEFT) self.sep1.pack(side=LEFT) self.process_btn.pack(side=LEFT)
def config_Style(self): Separator(root, orient='horizontal').grid(row=1, column=0, columnspan=7, sticky='esw') Separator(root, orient='horizontal').grid(row=0, column=0, columnspan=7, sticky='esw')
def __init__(self, parent, main): Frame.__init__(self, parent) self.main = main self.next_frame = None self.prev_frame = None self.main_frame = ScrollFrame(self, self) self.main_frame.grid(row=0, column=0, sticky='nswe') variable_frame = Frame(self.main_frame.viewPort) variable_frame.grid(column=0, row=0, sticky='nswe', padx=20, pady=5) Label(variable_frame, text=LANGUAGES[settings.LANGUAGE]['stp3'], font='Arial 14 bold').grid(row=0, column=0, pady=2, sticky='w') variable_frame.columnconfigure(0, weight=0, minsize=150) variable_frame.columnconfigure(1, weight=1, minsize=200) Label(variable_frame, text=LANGUAGES[settings.LANGUAGE]['e_v'], font='Arial 11').grid(row=1, column=0, pady=20, sticky='w') Separator(variable_frame, orient=HORIZONTAL).grid(row=2, sticky='we', columnspan=3) Label(variable_frame, text=LANGUAGES[settings.LANGUAGE]['tmp'] + ' (K):').grid(row=3, column=0, sticky='w') self.temperature_entry = Spinbox(variable_frame, from_=0, to=100000, increment=0.1, bd=1, relief=SOLID) self.temperature_entry.grid(row=3, column=1, padx=2, sticky='w', pady=10) self.temp_advertise = Label(variable_frame, text='', font='Arial 10') self.temp_advertise.grid(row=3, column=2, sticky='w') Label(variable_frame, text=LANGUAGES[settings.LANGUAGE]['volume'] + ' (angstrom^3):').grid(row=4, column=0, sticky='w') self.volume_entry = Spinbox(variable_frame, increment=1, bd=1, relief=SOLID) self.volume_entry.grid(row=4, column=1, padx=2, sticky='w') Label(variable_frame, text=LANGUAGES[settings.LANGUAGE]['timestep'] + ' (fs):').grid(row=5, column=0, sticky='w') self.DT_FS_entry = Spinbox(variable_frame, increment=0.1, bd=1, relief=SOLID) self.DT_FS_entry.grid(row=5, column=1, padx=2, sticky='w', pady=10) Label(variable_frame, text=LANGUAGES[settings.LANGUAGE]['fl_v'], font='Arial 11').grid(row=6, column=0, pady=20, sticky='w') Separator(variable_frame, orient=HORIZONTAL).grid(row=7, sticky='we', columnspan=3) Label(variable_frame, text=LANGUAGES[settings.LANGUAGE]['fl_w'] + ' (THz):').grid(row=8, column=0, sticky='w') self.filter_width_entry = Spinbox(variable_frame, from_=0.1, to=10.0, increment=0.1, bd=1, relief=SOLID) self.filter_width_entry.grid(row=8, column=1, padx=2, sticky='w', pady=10) variable_frame.rowconfigure(9, weight=1) button_frame = Frame(variable_frame) button_frame.grid(row=9, column=0, sticky='ws', pady=20) Button(button_frame, text=LANGUAGES[settings.LANGUAGE]['back'], bd=1, relief=SOLID, font='Arial 12', command=lambda: self.back(), width=10).grid(row=0, column=0, sticky='we') Button(button_frame, text=LANGUAGES[settings.LANGUAGE]['next'], bd=1, relief=SOLID, font='Arial 12', command=lambda: self.next(), width=10).grid(row=0, column=1, padx=5, sticky='we')
def create_message(root): root.cryptLabel = Label(root, text="AES Cryptography", bg=bgcolor) root.messageLabel = Label(root, text="Input Message ", bg=bgcolor) root.encryptLabel = Label(root, text="Encrypted message ", bg=bgcolor) root.decryptLabel = Label(root, text="Decrypted message ", bg=bgcolor) root.messageEntry = Entry(root) root.messageEntry.insert(END, 'Enter your message here') root.encryptEntry = Entry(root) root.encryptEntry.insert(END, '') root.decryptEntry = Entry(root) root.decryptEntry.insert(END, '') encryptButton = Button(root, text="Encrypt", bg=bgcolor, command=handle_encrypt) decryptButton = Button(root, text="Decrypt", bg=bgcolor, command=handle_decrypt) emptyLabel1 = Label(root, text="", bg=bgcolor) root.finalLabel = Label(root, text="", bg=bgcolor) horSeparator = Separator(root, orient="horizontal") root.cryptLabel.grid(row=20, columnspan=5) root.messageLabel.grid(row=21, column=0, sticky="W") root.encryptLabel.grid(row=22, column=0, sticky="W") root.decryptLabel.grid(row=23, column=0, sticky="W") root.messageEntry.config(highlightbackground=bgcolor) root.encryptEntry.config(highlightbackground=bgcolor, state='readonly') root.decryptEntry.config(highlightbackground=bgcolor, state='readonly') root.messageEntry.grid(row=21, column=1, columnspan=3, sticky="NEWS") root.encryptEntry.grid(row=22, column=1, columnspan=3, sticky="NEWS") root.decryptEntry.grid(row=23, column=1, columnspan=3, sticky="NEWS") encryptButton.config(highlightbackground=bgcolor) decryptButton.config(highlightbackground=bgcolor) encryptButton.grid(row=21, column=4) decryptButton.grid(row=22, column=4) emptyLabel1.grid(row=24, columnspan=5) root.finalLabel.grid(row=25, columnspan=5) horSeparator.grid(row=26, columnspan=5, sticky="EW")
def create_widgets(self): self.spread1 = Spread(self) self.sep1 = Separator(self) self.spread2 = Spread(self) self.sep2 = Separator(self) self.spread3 = Spread(self) self.spread1.pack(side=TOP, fill=X) self.sep1.pack(side=TOP, fill=X) self.spread2.pack(side=TOP, fill=X) self.sep2.pack(side=TOP, fill=X) self.spread3.pack(side=TOP, fill=X)
def __create_header(self, parent): sep = Separator(parent, orient=HORIZONTAL) sep.grid(row=1, column=0, columnspan=6, sticky=W + E) label = Label(parent, text="Seleccione un tipo de analisis", width=20).grid(row=2, column=0, columnspan=2, pady=10) self.elements.append(label) for i in range(0, len(button_headers)): __full_option = partial(self.__full_option, i) button = Button(parent, text=button_headers[i], command=__full_option, width=10, activebackground='red').grid(row=2, column=i + 2, padx=5, pady=5) self.elements.append(button)
def __init__(self, master): super().__init__(master) self.master.title("Chat Player") self.pack(fill=BOTH, expand=True) # Variables self.font_size_var: IntVar = IntVar(value=DEFAULT_FONT_SIZE) self.time_display_var: StringVar = StringVar(value='0:00:00') self.speed_display_var: StringVar = StringVar(value='1.00') self.seconds_elapsed_var: DoubleVar = DoubleVar(value=0) self.autoscroll_var: BooleanVar = BooleanVar(value=True) self.paused_var: BooleanVar = BooleanVar(value=True) self.always_on_top_var: BooleanVar = BooleanVar(value=False) self.pause_button_text_var: StringVar = StringVar(value='⏵') self.search_regex_var: BooleanVar = BooleanVar(value=False) self.search_case_sensitive_var: BooleanVar = BooleanVar(value=False) self.search_count_var: IntVar = IntVar() # Style self.chat_font = Font(family="Helvetica", size=self.font_size_var.get()) # Gui # self.chat_frame_container = Scrollable(self, outer_kwargs={'padding': 0}) # self.chat_frame_container.pack(side=TOP, fill=BOTH, expand=True) # self.chat_frame = self.chat_frame_container.frame self.chat_text = ChatText(self, undo=False, wrap=WORD, padx=6) self.chat_text.search_frame.regex_check.configure(variable=self.search_regex_var) self.chat_text.search_frame.case_check.configure(variable=self.search_case_sensitive_var) self.options_frame = OptionsFrame(self, pad=2) self.options_frame.autoscroll_check.configure(variable=self.autoscroll_var) self.options_frame.font_size_label.configure(textvariable=self.font_size_var) self.speed_control_frame = self.options_frame.speed_control_frame self.speed_control_frame.speed_label.configure(textvariable=self.speed_display_var) self.time_frame = TimeFrame(self, height=150) self.time_frame.play_pause_button.configure(textvariable=self.pause_button_text_var) self.time_frame.time_elapsed_label.configure(textvariable=self.time_display_var) self.time_frame.time_scale.configure(variable=self.seconds_elapsed_var) self.time_frame.pack(side=BOTTOM, fill=X, anchor=S) Separator(self, orient=HORIZONTAL).pack(side=BOTTOM, anchor=W, fill=X) self.options_frame.pack(side=BOTTOM, fill=X, anchor=S) self.options_frame.always_on_top_check.configure(variable=self.always_on_top_var) Separator(self, orient=HORIZONTAL).pack(side=BOTTOM, fill=X, anchor=W) # Separator(self, orient=HORIZONTAL).pack(side=TOP, anchor=N, fill=X, pady=(5, 0), ipady=0) self.chat_text.pack(side=TOP, fill=BOTH, expand=True) self.master.attributes('-topmost', True) self.master.attributes('-topmost', False)
def open(db_manager_instance): global db db = db_manager_instance filter_lb_list = [] window = Toplevel() window.grab_set() window.title("Filter Settings") window.minsize(750, 450) main_frame = Frame(window) title_lbl = Label(main_frame, text="Add or Remove Filters", font=("Calibri", 14)) # Creates a frame that contains the three filters and their components filter_frame = Frame(main_frame) prefix_frame = create_filter_frame(filter_frame, Database.PREFIX, filter_lb_list) phrase_frame = create_filter_frame(filter_frame, Database.PHRASE, filter_lb_list) suffix_frame = create_filter_frame(filter_frame, Database.SUFFIX, filter_lb_list) padding_x = 25 prefix_frame.grid(column=0, row=0, padx=padding_x) Separator(filter_frame, orient=VERTICAL).grid(column=1, row=0, sticky='wns') phrase_frame.grid(column=1, row=0, padx=padding_x) Separator(filter_frame, orient=VERTICAL).grid(column=2, row=0, sticky='wns') suffix_frame.grid(column=2, row=0, padx=padding_x) # Creates a frame containing the save and cancel buttons save_cancel_frame = Frame(main_frame) cancel_btn = Button(save_cancel_frame, text="Cancel", width=10, command=window.destroy) save_btn = Button(save_cancel_frame, text="Save", width=10, command=lambda: save_changes(filter_lb_list)) cancel_btn.grid(column=0, row=0, padx=20) save_btn.grid(column=1, row=0, padx=20) title_lbl.grid(column=0, row=0, pady=10) filter_frame.grid(column=0, row=1) save_cancel_frame.grid(column=0, row=2, pady=30) main_frame.place(anchor="center", relx="0.5", rely="0.50")
def __init__(self): self.version = (1, 0, 0) self.screen = Tk() self.paths = { "PyModder": os.path.dirname(__file__), "Mods": os.path.join(os.path.dirname(__file__), "Mods"), "Core": os.path.join(os.path.dirname(__file__), "Core"), "Images": os.path.join(os.path.dirname(__file__), "Core", "Images"), "Lang": os.path.join(os.path.dirname(__file__), "Core", "Lang"), "Logs": os.path.join(os.path.dirname(__file__), "Core", "Logs") } if os.path.exists(os.path.join(self.paths["Logs"], "last.log")): os.remove(os.path.join(self.paths["Logs"], "last.log")) self.logger = Logger("PyModder", True, os.path.join(self.paths["Logs"], "last.log")) self.logger.info("PyModder V %s launched.", ".".join(str(i) for i in self.version)) self.conf = Config(os.path.join(self.paths["Core"], "config.json")) self.lang = Lang(os.path.join(self.paths["Lang"], self.conf.get("lang", "en")+".lang")) self.screen.state("zoomed") self.menu = MenuBar(self) self.elements = ElementsFrame(self) self.properties = PropertiesFrame(self) self.project = self.load_project(self.conf.get("last_project", "")) self.launcher = Launcher(self) self.conf.set("last_project", self.project.name) self.conf.save() self.screen.columnconfigure(1, weight=1) self.screen.columnconfigure(3, weight=3) self.screen.rowconfigure(3, weight=1) Separator(self.screen, orient=VERTICAL).grid(row=0, column=0, sticky="NS") Separator(self.screen, orient=HORIZONTAL).grid(row=0, column=0, columnspan=5, sticky="EW") self.menu.grid(row=1, column=1, columnspan=3, sticky="NESW") Separator(self.screen, orient=HORIZONTAL).grid(row=2, column=0, columnspan=5, sticky="EW") self.elements.grid(row=3, column=1, sticky="NESW") Separator(self.screen, orient=VERTICAL).grid(row=3, column=2, sticky="NS") self.properties.grid(row=3, column=3, sticky="NESW") Separator(self.screen, orient=VERTICAL).grid(row=0, column=4, sticky="NS") self.logger.info("PyModder loaded.") self.screen.protocol("WM_DELETE_WINDOW", self.close) self.screen.mainloop()
def button_box(self): separ = Separator(self, orient="horizontal") separ.pack(expand=1, fill="x") box = Frame(self) b = Button(box, text=self.btn_ok_text, width=10, command=self.accept, default="active") b.pack(side="left", padx=5, pady=5) b = Button(box, text=self.btn_cancel_text, width=10, command=self.destroy) b.pack(side="right", padx=5, pady=5) self.bind("<Return>", self.accept) self.bind("<Escape>", self.destroy) box.pack()
class Toolbar(Frame): def __init__(self, master=None): super().__init__(master, padx=5, pady=5, bg='blue') self.create_widgets() def create_widgets(self): self.refresh_btn = Button(self, text='Refresh') self.sep1 = Separator(self) self.process_btn = Button(self, text='Process All') self.refresh_btn.pack(side=LEFT) self.sep1.pack(side=LEFT) self.process_btn.pack(side=LEFT)
def luo_pystyerotin(kehys, marginaali=2): """ Luo pystysuoran erottimen, jolla voidaan esim. erottaa selkeämmin käyttöliittymän osia toisistaan. Funktiolle voidaan lisäksi antaa toinen argumentti, joka kertoo paljonko ylimääräistä tyhjää laitetaan viivan molemmin puolin. :param widget kehys: kehys, johon erotin sijoitetaan :param int marginaali: ylimääräisen tyhjän määrä pikseleinä """ erotin = Separator(kehys, orient="vertical") erotin.pack(side=tk.TOP, fill=tk.BOTH, pady=marginaali)
def create_param(root): root.paramLabel = Label(root, text="Machine Parameters", bg=bgcolor) root.kLabel = Label(root, text="K ", bg=bgcolor) root.nLabel = Label(root, text="N ", bg=bgcolor) root.lLabel = Label(root, text="L ", bg=bgcolor) root.delayLabel = Label(root, text="Time Delay(sec) ", bg=bgcolor) root.kEntry = Entry(root) root.kEntry.insert(END, '3') root.nEntry = Entry(root) root.nEntry.insert(END, '10') root.lEntry = Entry(root) root.lEntry.insert(END, '4') root.delayEntry = Entry(root) root.delayEntry.insert(END, '0') syncButton = Button(root, text="Synchronize weights", bg=bgcolor, command=handle_sync) emptyLabel2 = Label(root, text="", bg=bgcolor) horSeparator = Separator(root, orient="horizontal") root.paramLabel.grid(row=0, columnspan=5) root.kLabel.grid(row=1, column=0, sticky="W") root.nLabel.grid(row=1, column=2, sticky="W") root.lLabel.grid(row=2, column=0, sticky="W") root.delayLabel.grid(row=2, column=2, sticky="W") root.kEntry.config(highlightbackground=bgcolor) root.nEntry.config(highlightbackground=bgcolor) root.lEntry.config(highlightbackground=bgcolor) root.delayEntry.config(highlightbackground=bgcolor) root.kEntry.grid(row=1, column=1) root.nEntry.grid(row=1, column=3) root.lEntry.grid(row=2, column=1) root.delayEntry.grid(row=2, column=3) syncButton.config(highlightbackground=bgcolor) syncButton.grid(row=1, column=4, rowspan=2) emptyLabel2.grid(row=3, columnspan=5) horSeparator.grid(row=4, columnspan=5, sticky="EW")
def __init__(self, parent): LabelFrame.__init__(self, parent, text="Results", width=825, height=485) # Terrible kludgy hack to force the app to stay the right size # Need to work out how to remove self.grid_propagate(False) self.resultsDict = None self.modelType = None self.currentSegment = 0 # Stats frame self.statsFrame = StatsFrame(self, self.padX, self.padY) self.statsFrame.calculate_B.bind("<Button-1>", self._parametersChanged) self.statsFrame.reset_B.bind("<Button-1>", self._parametersReset) def onComboBoxSelect(e): self.currentSegment = e.widget.current() self._updateDisplay(True) self.statsFrame.expSeg_CB.bind("<<ComboboxSelected>>", onComboBoxSelect) # Error frame self.errorSurfaceFrame = ErrorSurfaceFrame(self) self.errorSurfaceFrame.errorSurfaceB.bind("<Button-1>", self._displayErrorSurface) # Graph notebook self.errorSurfaceSeperator = Separator(self, orient=tkinter.HORIZONTAL) self.graphNotebook = ImprovedNotebook(self) self.modelGraphFrame = GraphFrame(self.graphNotebook, dim=2) self.modelGraphFrame.axes.set_ylabel(r'$thickness(m)$') self.regressionGraphFrame = GraphFrame(self.graphNotebook, dim=2) self.regressionGraphFrame.axes.set_ylabel(r'$\log{(thickness(m))}$') self.errorSurfaceGraphFrame = GraphFrame(self.graphNotebook, dim=3) self.errorSurfaceGraphFrame.axes.set_zlabel(r'$error$') self.graphNotebook.addFrame(self.modelGraphFrame, text="Model")
def __init__(self, parent, theme_name: str): # initializes this frame and its sub frames tkinter.Frame.__init__(self, parent) self.model: FinanceManagerModel = None self.color_manager: ColorManager = None self.fd: FileDisplay = FileDisplay(self) self.fd.set_listener(self) self.fd.grid(row=0, column=0, sticky=tkinter.NS) separator1 = Separator(self, orient="vertical") separator1.grid(row=0, column=1, sticky='ns') self.tv: TableVisualizer = TableVisualizer(self) self.tv.add_listener(self) self.tv.grid(row=0, column=2, sticky=tkinter.NS) separator2 = Separator(self, orient="vertical") separator2.grid(row=0, column=3, sticky='ns') self.dv: DataVisualizer = DataVisualizer(self, text="Data Visualizer") self.dv.grid(row=0, column=4, sticky=tkinter.NS) if theme_name == "dark": self.set_color_manager( ColorManager(ColorTheme.get_dark_theme_dict())) else: self.set_color_manager( ColorManager(ColorTheme.get_default_theme_dict()))
def __init__(self, master): super().__init__(master) self.transient(master) self.title('About Notepad') self.resizable(False, False) self.wm_attributes('-topmost', 'true', '-toolwindow', 'true') self.protocol("WM_DELETE_WINDOW", self.close) self.focus_set() # image and application name self.img = tk.PhotoImage(file='images/Notepad_32.png') self.top_frame = tk.Frame(self) lbl1 = tk.Label(self.top_frame, image=self.img, anchor=tk.W) lbl2 = tk.Label(self.top_frame, text='Notepad', font=('Arial Black', 16, 'bold'), fg='#444') sep = Separator(self, orient=tk.HORIZONTAL) # license text widget self.gnu = tk.Frame(self) self.yscroll = tk.Scrollbar(self.gnu, orient='vertical', command=self.yscroll_callback) self.text = tk.Text(self.gnu, wrap='word', width=50, height=10, yscrollcommand=self.yscroll.set) mylicense = pathlib.Path('license.txt').read_text() self.text.insert(tk.END, mylicense) lbl3 = tk.Label(self, text='GNU General Public License') # pack widgets to window lbl1.pack(side=tk.LEFT, padx=(15, 5), pady=15) lbl2.pack(side=tk.LEFT, padx=(5, 15), pady=15) self.top_frame.pack(side=tk.TOP, fill=tk.X, expand=tk.YES) sep.pack(side=tk.TOP, fill=tk.X, expand=tk.YES) lbl3.pack(pady=(10, 0)) self.text.pack(side=tk.LEFT, padx=(15, 0), pady=15, ipadx=10, ipady=10) self.yscroll.pack(side=tk.RIGHT, fill=tk.Y, padx=(0, 15), pady=15, expand=tk.YES) self.gnu.pack(pady=(0, 0)) # make text widget 'read-only' self.text.configure(state=tk.DISABLED)
def _create_control_panel(self): self.control_panel = tk.Frame(self.root) self.control_panel.pack(side="left", expand="no", fill="both") self.cave_control_panel = KFrame(self.control_panel) self.image_control_panel = KFrame(self.control_panel) self.image_enhance_panel = KFrame(self.control_panel) self.cave_control_panel.pack(side="top", expand="no", fill="both") Separator(self.control_panel, orient=tk.HORIZONTAL).pack(side="top", fill="x", pady=1) self.image_control_panel.pack(side="top", expand="no", fill="both") Separator(self.control_panel, orient=tk.HORIZONTAL).pack(side="top", fill="x", pady=1) self.image_enhance_panel.pack(side="bottom", expand="no", fill="both")
def __init__(self, main): super(MenuBar, self).__init__(main.screen) self.main = main self.icons = { "Parameters": PhotoImage(file=os.path.join(main.paths["Images"], "parameters_icon.png")), "Open": PhotoImage(file=os.path.join(main.paths["Images"], "open_icon.png")), "New": PhotoImage(file=os.path.join(main.paths["Images"], "new_icon.png")), "Save": PhotoImage(file=os.path.join(main.paths["Images"], "save_icon.png")), "Launch": PhotoImage(file=os.path.join(main.paths["Images"], "launch_icon.png")), "Build": PhotoImage(file=os.path.join(main.paths["Images"], "build_icon.png")) } self.param_btn = Button(self, image=self.icons["Parameters"], command=self.open_param) self.open_btn = Button(self, image=self.icons["Open"]) self.save_btn = Button(self, image=self.icons["Save"], command=self.save) self.new_btn = Button(self, image=self.icons["New"], command=self.new) self.launch_btn = Button(self, image=self.icons["Launch"], command=self.launch) self.build_btn = Button(self, image=self.icons["Build"], command=self.build) ToolTip(self.param_btn, main.lang.get_translate("parameters_tooltip", "Parameters")) ToolTip(self.open_btn, main.lang.get_translate("open_tooltip", "Open")) ToolTip(self.save_btn, main.lang.get_translate("save_tooltip", "Save")) ToolTip(self.new_btn, main.lang.get_translate("new_tooltip", "New")) ToolTip(self.launch_btn, main.lang.get_translate("launch_tooltip", "Launch")) ToolTip(self.build_btn, main.lang.get_translate("build_tooltip", "Build")) self.separators = { "file_exe": Separator(self, orient=VERTICAL), "exe_param": Separator(self, orient=VERTICAL), "left": Separator(self, orient=VERTICAL), "right": Separator(self, orient=VERTICAL) } for i in range(8): if i in (3, 6): self.columnconfigure(i, weight=0) else: self.columnconfigure(i, weight=1) self.new_btn.grid(row=0, column=0, sticky="NSEW", padx=5, pady=5) self.open_btn.grid(row=0, column=1, sticky="NSEW", padx=5, pady=5) self.save_btn.grid(row=0, column=2, sticky="NSEW", padx=5, pady=5) self.separators["file_exe"].grid(row=0, column=3, sticky="NS") self.launch_btn.grid(row=0, column=4, sticky="NSEW", padx=5, pady=5) self.build_btn.grid(row=0, column=5, sticky="NSEW", padx=5, pady=5) self.separators["exe_param"].grid(row=0, column=6, sticky="NS") self.param_btn.grid(row=0, column=7, sticky="NSEW", padx=5, pady=5)
def create_content(self, **kw): self.rowconfigure(2, weight=1) self.columnconfigure(0, weight=1) self.minsize(50, 50) self.hide_completed = CONFIG.getboolean('Tasks', 'hide_completed') # --- elements label = Label(self, text=_('Tasks').upper(), style='title.Tasks.TLabel', anchor='center') label.grid(row=0, columnspan=2, pady=4, sticky='ew') Separator(self, style='Tasks.TSeparator').grid(row=1, columnspan=2, sticky='we') self.display = Text(self, width=20, height=10, relief='flat', cursor='arrow', wrap='word', highlightthickness=0, state='disabled', spacing1=5, tabs=('35', 'right', '45', 'left')) self.display.grid(sticky='nsew', row=2, column=0, padx=2, pady=2) scroll = AutoScrollbar(self, orient='vertical', style='Tasks.Vertical.TScrollbar', command=self.display.yview) scroll.grid(row=2, column=1, sticky='ns', pady=(2, 16)) self.display.configure(yscrollcommand=scroll.set) self.display_tasks() corner = Sizegrip(self, style="Tasks.TSizegrip") corner.place(relx=1, rely=1, anchor='se') # --- bindings self.bind('<3>', lambda e: self.menu.tk_popup(e.x_root, e.y_root)) label.bind('<ButtonPress-1>', self._start_move) label.bind('<ButtonRelease-1>', self._stop_move) label.bind('<B1-Motion>', self._move)
def makeGrid(self): configs = Frame(self) configs.pack(side=TOP, expand=YES, fill=BOTH) self.entFields = [] for i, (var, name) in enumerate(self.variables().items()): # print(i, var) if name == 'separator': Separator(configs, orient=HORIZONTAL).grid(row=i, sticky=EW, columnspan=2) else: lab = Label(configs, text=name, justify=LEFT, anchor=W) lab.bind('<Button-3>', self.onHelp) if var == 'sslServerMode': self.sslMode = BooleanVar() self.sslMode.set(True if self.config[var] == 'True' else False) ent = Checkbutton(configs, text='SSL', anchor=W) ent.config(variable=self.sslMode, command=self.sslOn) else: ent = Entry(configs) ent.insert(0, self.config[var]) self.entFields.append((ent, lab)) lab.grid(row=i, column=0, sticky=EW) ent.grid(row=i, column=1, sticky=EW) configs.rowconfigure(i, weight=1) configs.columnconfigure(1, weight=1)
def create_widgets(self): entry = ReactiveTextEntry(self) entry.grid(row=1, column=0) entry.bind('<<TextModified>>', self.onModification) Separator(self, orient='vertical').grid(row=0, column=1, sticky='ns') self.preview = ScrolledText(self) self.preview.grid(row=1, column=2)
def __init__(self, parent, model: Model, graph: BuildGraph, *args, graph_change_callback=None, **kwargs): super().__init__(parent, *args, **kwargs) self.model = model self.graph = graph self.link_types = sorted(str(label) for label in self.model.link_types) self.graph_change_callback = graph_change_callback self.token_listing = ['%s [%s]' % (token.spelling, index) for index, token in enumerate(graph.tokens)] assert len(self.token_listing) == len(graph.tokens) self.token_labels = [Label(self, text='%s [%s]' % (token.spelling, index)) for index, token in enumerate(graph.tokens)] assert len(self.token_labels) == len(graph.tokens) self.separators = [Separator(self, orient=HORIZONTAL) for _ in graph.tokens] assert len(self.separators) == len(graph.tokens) link_sets = [] for source in range(len(graph.tokens)): link_set = set() for sink in graph.get_sinks(source): for label in graph.get_labels(source, sink): link_set.add((str(label), sink)) link_sets.append(link_set) assert len(link_sets) == len(graph.tokens) self.link_selector_maps = [] # type: List[Dict[Tuple[Optional[Property], int], Tuple]] for source, link_set in enumerate(link_sets): link_selector_map = {} for label, sink in link_set: label_drop_down = Combobox(self, values=self.link_types) label_drop_down.current(self.link_types.index(label)) label_drop_down.bind("<<ComboboxSelected>>", (lambda *a, r=(source, label, sink), v=label_drop_down, **k: self.modify_link(r, label=v.get()))) sink_drop_down = Combobox(self, values=self.token_listing) sink_drop_down.current(sink) sink_drop_down.bind('<<ComboboxSelected>>', (lambda *a, r=(source, label, sink), v=sink_drop_down, **k: self.modify_link(r, sink=self.token_listing.index(v.get())))) remove_button = Button(self, text='-', command=lambda r=(source, label, sink): self.modify_link(r)) link_selector_map[label, sink] = label_drop_down, sink_drop_down, remove_button self.link_selector_maps.append(link_selector_map) assert len(self.link_selector_maps) == len(graph.tokens) self.new_link_selectors = [] # type: List[Tuple[Combobox, Combobox]] for source in range(len(self.graph.tokens)): label_drop_down = Combobox(self, values=[''] + self.link_types) label_drop_down.current(0) label_drop_down.bind('<<ComboboxSelected>>', (lambda *a, r=(source, None, None): self.modify_link(r, new=True))) sink_drop_down = Combobox(self, values=[''] + self.token_listing) sink_drop_down.current(0) sink_drop_down.bind('<<ComboboxSelected>>', (lambda *a, r=(source, None, None): self.modify_link(r, new=True))) self.new_link_selectors.append((label_drop_down, sink_drop_down))
class SourceImages(Frame): def __init__(self, master=None): super().__init__(master, pady=5) self.create_widgets() def create_widgets(self): self.spread1 = Spread(self) self.sep1 = Separator(self) self.spread2 = Spread(self) self.sep2 = Separator(self) self.spread3 = Spread(self) self.spread1.pack(side=TOP, fill=X) self.sep1.pack(side=TOP, fill=X) self.spread2.pack(side=TOP, fill=X) self.sep2.pack(side=TOP, fill=X) self.spread3.pack(side=TOP, fill=X)
def __init__(self, master, **kwargs): Frame.__init__(self, master, **kwargs) Separator(self, orient=HORIZONTAL).pack(side=TOP, fill=X) self.close = Button(self, text='x', width=3, takefocus=False) self.close.pack(side=RIGHT) self.entry = Entry(self) self.entry.pack(side=LEFT, padx=8) self.prev = Button(self, text="<", width=3, takefocus=False) self.prev.pack(side=LEFT) self.next = Button(self, text=">", width=3, takefocus=False) self.next.pack(side=LEFT) Separator(self, orient=VERTICAL).pack(side=LEFT, fill=Y, pady=2, padx=(6, 4)) self.regex_check = Checkbutton(self, text='Regex', takefocus=False) self.regex_check.pack(side=LEFT) self.case_check = Checkbutton(self, text='Case Sensitive', takefocus=False) self.case_check.pack(side=LEFT, padx=5)
def _initconsole(self): separator = Separator(self, orient=HORIZONTAL) separator.grid(row=1, columnspan=3, sticky=W + E, padx=5, pady=5) self.console = Text(self) self.console.grid(row=2, columnspan=3, sticky=W + E, padx=5, pady=5) vsl = Scrollbar(self, orient=VERTICAL) vsl.grid(row=2, column=3, sticky=N + S + W) hsl = Scrollbar(self, orient=HORIZONTAL) hsl.grid(row=3, column=0, columnspan=3, sticky=W + E + N) hsl.config(command=self.console.xview) vsl.config(command=self.console.yview) resbtn = Button(self, text="Search", width=7, comman=self._showsearchresult) resbtn.grid(row=4, column=2, padx=5, pady=5, sticky=E)
def create_widget(self): self.widget = TK.Frame(self.parent.widget) # Add column headings label_canvas = self.widget left = self.h_gap top = self.v_gap for col in self.columns: place_label(canvas=label_canvas, txt=col['text'], left=left, top=top, width=col['width'], height=self.cellheight, bg=col['titlecolor'], anchor=col['anchor']) left += col['width'] + self.h_gap # Add data labels, and string variables for each label self.cells = [] top += self.cellheight + self.v_gap for i,row in enumerate(self.data): # row is a list if i >= self.view_rows: break cell_row = [] left=self.h_gap s = Separator(label_canvas) s.place(x=0, y=top -2, relwidth=1.0) for j, col in enumerate(self.columns): value = TK.StringVar() value.set('{}'.format(self.data[i][j])) place_label(canvas=label_canvas, txt="", left=left, top=top, width=col['width'], height=self.cellheight, bg=col['cellcolor'], anchor=col['labelanchor'], textvariable=value, name=':{}:{}'.format(i,j), clicked=self._dataclick) cell_row.append(value) left += col['width'] + self.h_gap self.cells.append(cell_row) top += self.cellheight + self.v_gap self.top_row = 0 # Add vertical scroll if needed if self.v_scroll: x = self.scroll_left y = self.scroll_top height = self.scroll_height z = len(self.data) - self.view_rows #vertical_scroll = TK.Scale(label_canvas.frame, orient=TK.VERTICAL, vertical_scroll = TK.Scale(label_canvas, orient=TK.VERTICAL, from_=0, to=z, command=self.vert_scroll, showvalue=0) vertical_scroll.place(x=x, y=y, width=23, height=height)
def __init__(self, parent, title=None, text=None): self.had_focus = parent.focus_get() Toplevel.__init__(self, parent) if title: self.title(title) stext = ScrolledText(self, background="gray") stext.pack(padx=5, pady=5) if text is not None: stext.insert("end", text) stext["state"] = "disabled" separ = Separator(self, orient="horizontal") separ.pack(expand=1, fill="x") b = Button(self, text=_("OK"), width=10, command=self.destroy, default="active") self.bind("<Escape>", self.destroy) b.pack() self.protocol("WM_DELETE_WINDOW", self.destroy) b.focus_set() self.grab_set() self.wait_window()
def __init__(self,parent): LabelFrame.__init__(self, parent,text="Results", width=825, height=485) # Terrible kludgy hack to force the app to stay the right size # Need to work out how to remove self.grid_propagate(False) self.resultsDict = None self.modelType = None self.currentSegment = 0 # Stats frame self.statsFrame = StatsFrame(self, self.padX, self.padY) self.statsFrame.calculate_B.bind("<Button-1>", self._parametersChanged) self.statsFrame.reset_B.bind("<Button-1>", self._parametersReset) def onComboBoxSelect(e): self.currentSegment = e.widget.current() self._updateDisplay(True) self.statsFrame.expSeg_CB.bind("<<ComboboxSelected>>", onComboBoxSelect) # Error frame self.errorSurfaceFrame = ErrorSurfaceFrame(self) self.errorSurfaceFrame.errorSurfaceB.bind("<Button-1>", self._displayErrorSurface) # Graph notebook self.errorSurfaceSeperator = Separator(self,orient=tkinter.HORIZONTAL) self.graphNotebook = ImprovedNotebook(self) self.modelGraphFrame = GraphFrame(self.graphNotebook, dim=2) self.modelGraphFrame.axes.set_ylabel(r'$thickness(m)$') self.regressionGraphFrame = GraphFrame(self.graphNotebook, dim=2) self.regressionGraphFrame.axes.set_ylabel(r'$\ln{(thickness(m))}$') self.errorSurfaceGraphFrame = GraphFrame(self.graphNotebook, dim=3) self.errorSurfaceGraphFrame.axes.set_zlabel(r'$error$') self.graphNotebook.addFrame(self.modelGraphFrame, text="Model")
def toolbar_init(self): frame_toolbar = Frame(self.root) frame_toolbar.grid(column=0, row=0, sticky='nsew') # New file button button_new_file = Button(frame_toolbar, image=self.img_new_file, relief='flat', command=self.new_tab) button_new_file.grid(column=0, row=0, sticky='nsew') Tooltip(button_new_file, 'Create new file') # Open file button button_open = Button(frame_toolbar, image=self.img_open, relief='flat', command=self.open_file) button_open.grid(column=1, row=0, sticky='nsew') Tooltip(button_open, 'Open file') # Save file button button_save = Button(frame_toolbar, image=self.img_save, relief='flat', command=self.save_file) button_save.grid(column=2, row=0, sticky='nsew') Tooltip(button_save, 'Save file') # Separator separator_1 = Separator(frame_toolbar, orient='vertical') separator_1.grid(column=3, row=0, sticky='nsew') # Undo button button_undo = Button(frame_toolbar, image=self.img_undo, relief='flat', command=self.undo) button_undo.grid(column=4, row=0, sticky='nsew') Tooltip(button_undo, 'Undo') # Redo button button_redo = Button(frame_toolbar, image=self.img_redo, relief='flat', command=self.redo) button_redo.grid(column=5, row=0, sticky='nsew') Tooltip(button_redo, 'Redo') # Separator separator_2 = Separator(frame_toolbar, orient='vertical') separator_2.grid(column=6, row=0, sticky='nsew') # Cut button button_cut = Button(frame_toolbar, image=self.img_cut, relief='flat', command=self.cut) button_cut.grid(column=7, row=0, sticky='nsew') Tooltip(button_cut, 'Cut') # Copy button button_copy = Button(frame_toolbar, image=self.img_copy, relief='flat', command=self.copy) button_copy.grid(column=8, row=0, sticky='nsew') Tooltip(button_copy, 'Copy') # Paste button button_paste = Button(frame_toolbar, image=self.img_paste, relief='flat', command=self.paste) button_paste.grid(column=9, row=0, sticky='nsew') Tooltip(button_paste, 'Paste') # Separator separator_3 = Separator(frame_toolbar, orient='vertical') separator_3.grid(column=10, row=0, sticky='nsew') # Search button button_search = Button(frame_toolbar, image=self.img_search, relief='flat', command=self.find) button_search.grid(column=11, row=0, sticky='nsew') Tooltip(button_search, 'Search') # Replace button button_replace = Button(frame_toolbar, image=self.img_replace, relief='flat', command=self.find_and_replace) button_replace.grid(column=12, row=0, sticky='nsew') Tooltip(button_replace, 'Replace') return frame_toolbar
class ResultsFrame(LabelFrame): padY = 5 padX = 30 def __init__(self,parent): LabelFrame.__init__(self, parent,text="Results", width=825, height=485) # Terrible kludgy hack to force the app to stay the right size # Need to work out how to remove self.grid_propagate(False) self.resultsDict = None self.modelType = None self.currentSegment = 0 # Stats frame self.statsFrame = StatsFrame(self, self.padX, self.padY) self.statsFrame.calculate_B.bind("<Button-1>", self._parametersChanged) self.statsFrame.reset_B.bind("<Button-1>", self._parametersReset) def onComboBoxSelect(e): self.currentSegment = e.widget.current() self._updateDisplay(True) self.statsFrame.expSeg_CB.bind("<<ComboboxSelected>>", onComboBoxSelect) # Error frame self.errorSurfaceFrame = ErrorSurfaceFrame(self) self.errorSurfaceFrame.errorSurfaceB.bind("<Button-1>", self._displayErrorSurface) # Graph notebook self.errorSurfaceSeperator = Separator(self,orient=tkinter.HORIZONTAL) self.graphNotebook = ImprovedNotebook(self) self.modelGraphFrame = GraphFrame(self.graphNotebook, dim=2) self.modelGraphFrame.axes.set_ylabel(r'$thickness(m)$') self.regressionGraphFrame = GraphFrame(self.graphNotebook, dim=2) self.regressionGraphFrame.axes.set_ylabel(r'$\ln{(thickness(m))}$') self.errorSurfaceGraphFrame = GraphFrame(self.graphNotebook, dim=3) self.errorSurfaceGraphFrame.axes.set_zlabel(r'$error$') self.graphNotebook.addFrame(self.modelGraphFrame, text="Model") def displayNewModel(self, modelType, resultsDict): self.modelType = modelType self.isopachs = resultsDict["isopachs"] self.sqrtAreaKM = [isopach.sqrtAreaKM for isopach in self.isopachs] self.thicknessM = [isopach.thicknessM for isopach in self.isopachs] self.currentParameters = resultsDict self.defaultParameters = deepcopy(self.currentParameters) self.statsFrame.grid(row=0,column=0,padx=10,pady=5,sticky="NESW") self.graphNotebook.grid(row=0,column=1,padx=10, pady=5,sticky="NEW") if self.modelType == Model.EXP: self._displayExp() self.config(text="Results (Exponential)") else: self.errorSurfaceSeperator.grid(row=1, column=0, columnspan=2, padx=20, pady=(20,0), sticky="EW") self.errorSurfaceFrame.grid(row=2, column=0, columnspan=2, padx=10, pady=0, sticky="EW") if self.modelType == Model.POW: self._displayPow() self.config(text="Results (Power law)") elif self.modelType == Model.WEI: self._displayWei() self.config(text="Results (Weibull)") self._updateDisplay(False) def _updateDisplay(self, comboboxUpdate): if not comboboxUpdate: self.modelGraphFrame.clear() self.regressionGraphFrame.clear() thicknessM = [isopach.thicknessM for isopach in self.isopachs] sqrtArea = [isopach.sqrtAreaKM for isopach in self.isopachs] self.modelGraphFrame.plotScatter(sqrtArea,thicknessM,True) self.modelGraphFrame.axes.set_xlabel(r"$\sqrt{Area}$") if self.modelType == Model.EXP: self._updateExp(comboboxUpdate) elif self.modelType == Model.POW: self._updatePow() elif self.modelType == Model.WEI: self._updateWei() def _displayExp(self): fr = self.statsFrame padX = self.padX padY = self.padY fr.expSeg_CB.grid(row=3,column=0,sticky="W",padx=10,pady=padY) vals = ["Segment " + str(i) for i in range(1,self.currentParameters["numberOfSegments"]+1)] fr.expSeg_CB.configure(values=vals) fr.expSeg_CB.current(0) fr.expSegVolume_L.grid(row=4,column=0,padx=10,sticky="W",pady=padY) fr.expSegVolume_E.grid(row=4,column=1,padx=10,sticky="E") fr.equation_L.grid(row=5,column=0,sticky="W",padx=10,pady=padY) fr.equation_E.grid(row=5,column=1,padx=10,sticky="E") fr.equation_L.configure(text="Segment equation:") fr.parameters_L.grid(row=6,column=0,padx=10,pady=padY,sticky="W") fr.expSegStartLimit_L.grid(row=7,column=0,sticky="W",padx=padX,pady=padY) fr.expSegStartLimit_E.grid(row=7,column=1,padx=10,sticky="E") fr.expSegEndLimit_L.grid(row=8,column=0,sticky="W",padx=padX,pady=padY) fr.expSegEndLimit_E.grid(row=8,column=1,padx=10,sticky="E") fr.expSegCoefficent_L.grid(row=9,column=0,sticky="W",padx=padX,pady=padY) fr.expSegCoefficent_E.grid(row=9,column=1,padx=10,sticky="E") fr.expSegExponent_L.grid(row=10,column=0,sticky="W",padx=padX,pady=padY) fr.expSegExponent_E.grid(row=10,column=1,padx=10,sticky="E") # Recalculate buttons fr.calculate_B.grid(row=11,column=0,padx=padX,pady=padY,sticky="W") fr.reset_B.grid(row=11,column=1,padx=10,sticky="E") self.graphNotebook.addFrame(self.regressionGraphFrame, text="Regression") def _displayPow(self): fr = self.statsFrame padX = self.padX padY = self.padY fr.equation_L.grid(row=2,column=0,sticky="W",padx=10,pady=padY) fr.equation_E.grid(row=2,column=1,padx=10,sticky="E") fr.equation_L.configure(text="Equation:") fr.parameters_L.grid(row=3,column=0,padx=10,pady=padY,sticky="W") fr.powCoefficient_L.grid(row=4,column=0,sticky="W",padx=padX,pady=padY) fr.powCoefficient_E.grid(row=4,column=1,padx=10,sticky="E") fr.powExponent_L.grid(row=5,column=0,sticky="W",padx=padX,pady=padY) fr.powExponent_E.grid(row=5,column=1,padx=10,sticky="E") fr.powProximalLimit_L.grid(row=6,column=0,sticky="W",padx=padX,pady=padY) fr.powProximalLimit_E.grid(row=6,column=1,padx=10,sticky="E") fr.powDistalLimit_L.grid(row=7,column=0,sticky="W",padx=padX,pady=padY) fr.powDistalLimit_E.grid(row=7,column=1,padx=10,sticky="E") # Recalculate buttons fr.calculate_B.grid(row=8,column=0,padx=padX,pady=padY,sticky="W") fr.reset_B.grid(row=8,column=1,padx=10,sticky="E") fr.powSuggestedProximalLimit_L.grid(row=9,column=0,sticky="W",padx=10,pady=padY) fr.powSuggestedProximalLimit_E.grid(row=9,column=1,padx=10,sticky="E") self.graphNotebook.addFrame(self.regressionGraphFrame, text="Regression") self.errorSurfaceFrame.update("c", "m", 0.0, 5.0, 0.0, 5.0) def _displayWei(self): fr = self.statsFrame padX = self.padX padY = self.padY fr.equation_L.grid(row=2,column=0,sticky="W",padx=10,pady=padY) fr.equation_E.grid(row=2,column=1,padx=10,sticky="E") fr.equation_L.configure(text="Equation:") fr.parameters_L.grid(row=3,column=0,padx=10,pady=padY,sticky="W") fr.weiLambdaL.grid(row=4,column=0,padx=padX,pady=padY,sticky="W") fr.weiLambdaE.grid(row=4,column=1,padx=10,sticky="E") fr.weiKL.grid(row=5,column=0,padx=padX,pady=padY,sticky="W") fr.weiKE.grid(row=5,column=1,padx=10,sticky="E") fr.weiThetaL.grid(row=6,column=0,padx=padX,pady=padY,sticky="W") fr.weiThetaE.grid(row=6,column=1,padx=10,sticky="E") # Recalculate buttons fr.calculate_B.grid(row=7,column=0,padx=padX,pady=padY,sticky="W") fr.reset_B.grid(row=7,column=1,padx=10,sticky="E") parameterLimits = self.currentParameters["limits"] lambdaLower, lambdaUpper = parameterLimits[0] kLower, kUpper = parameterLimits[1] self.errorSurfaceFrame.update("\u03BB", "k", lambdaLower, lambdaUpper, kLower, kUpper) def _updateExp(self, comboboxUpdate): n = self.currentParameters["numberOfSegments"] coefficients = self.currentParameters["segmentCoefficients"] exponents = self.currentParameters["segmentExponents"] limits = self.currentParameters["segmentLimits"] ########### ## Stats ## ########### fr = self.statsFrame # Segment start start = limits[self.currentSegment] startStr = helper_functions.roundToSF(start, NUMBER_OF_SF) fr.expSegStartLimit_E.insertNew(start) fr.expSegStartLimit_E.setUserEditable(self.currentSegment != 0) # Segment end end = limits[self.currentSegment+1] endStr = helper_functions.roundToSF(end, NUMBER_OF_SF) fr.expSegEndLimit_E.insertNew(end) fr.expSegEndLimit_E.setUserEditable(self.currentSegment != n-1) # Segment coefficient coefficient = coefficients [self.currentSegment] coefficientStr = helper_functions.roundToSF(coefficient, NUMBER_OF_SF) fr.expSegCoefficent_E.insertNew(coefficient) # Segment exponent exponent = exponents[self.currentSegment] exponentStr = helper_functions.roundToSF(exponent, NUMBER_OF_SF) fr.expSegExponent_E.insertNew(exponent) # Segment volume segmentVolumes = [calculateExponentialSegmentVolume(coefficients[i], exponents[i], limits[i], limits[i+1]) for i in range(n)] segmentVolumeStr = helper_functions.roundToSF(segmentVolumes[self.currentSegment], NUMBER_OF_SF) fr.expSegVolume_E.insertNew(segmentVolumeStr) # Total volume totalVolume = sum(segmentVolumes) estimatedTotalVolumeStr = helper_functions.roundToSF(totalVolume, NUMBER_OF_SF) fr.totalEstimatedVolume_E.insertNew(estimatedTotalVolumeStr) # Error def thicknessFunction(x): for i in range(n): if limits[i] <= x < limits[i+1]: return coefficients[i]*math.exp(-exponents[i]*x) error = regression_methods.meanRelativeSquaredError(self.sqrtAreaKM, self.thicknessM, thicknessFunction) errorStr = helper_functions.roundToSF(error, NUMBER_OF_SF) fr.relativeSquaredError_E.insertNew(errorStr) # Equation equationStr = "T = " + coefficientStr if exponent > 0: equationStr += "exp(-" + exponentStr + "x)" elif exponent < 0: equationStr += "exp(" + exponentStr[1:] + "x)" fr.equation_E.insertNew(equationStr) ############ ## Graphs ## ############ if not comboboxUpdate: # Model endXs = limits[1:-1] + [1.5*max(self.sqrtAreaKM)-0.5*min(self.sqrtAreaKM)] for i in range(n): xs = helper_functions.getStaggeredPoints(limits[i], endXs[i], MODEL_PLOTTING_PRECISION) ys = [coefficients[i]*math.exp(-exponents[i]*x) for x in xs] self.modelGraphFrame.plotFilledLine(xs, ys, color=colours[i]) # Regression logThicknessM = [np.log(t) for t in self.thicknessM] self.regressionGraphFrame.plotScatter(self.sqrtAreaKM, logThicknessM, False) self.regressionGraphFrame.axes.set_xlabel(r"$\sqrt{Area}$") for i in range(n): xs = [limits[i], endXs[i]] ys = [np.log(thicknessFunction(x)) for x in xs] self.regressionGraphFrame.plotLine(xs,ys, color=colours[i]) def _updatePow(self): ########### ## Stats ## ########### fr = self.statsFrame # Coefficient c = self.currentParameters["coefficient"] coefficientStr = helper_functions.roundToSF(c, NUMBER_OF_SF) fr.powCoefficient_E.insertNew(c) # Exponent m = self.currentParameters["exponent"] exponentStr = helper_functions.roundToSF(m, NUMBER_OF_SF) fr.powExponent_E.insertNew(m) # Proximal limit proximalLimitKM = self.currentParameters["proximalLimitKM"] proximalLimitStr = helper_functions.roundToSF(proximalLimitKM, NUMBER_OF_SF) fr.powProximalLimit_E.insertNew(proximalLimitKM) # Distal limit distalLimitKM = self.currentParameters["distalLimitKM"] distalLimitStr = helper_functions.roundToSF(distalLimitKM, NUMBER_OF_SF) fr.powDistalLimit_E.insertNew(distalLimitKM) # Volume volume = calculatePowerLawVolume(c, m, proximalLimitKM, distalLimitKM) volumeStr = helper_functions.roundToSF(volume, NUMBER_OF_SF) fr.totalEstimatedVolume_E.insertNew(volumeStr) # Error thicknessFunction = lambda x : c*(x**(-m)) error = regression_methods.meanRelativeSquaredError(self.sqrtAreaKM, self.thicknessM, thicknessFunction) errorStr = helper_functions.roundToSF(error, NUMBER_OF_SF) fr.relativeSquaredError_E.insertNew(errorStr) # Equation equationStr = "T = " + coefficientStr if m > 0: equationStr += "x^-" + exponentStr elif m < 0: equationStr += "x^" + exponentStr[1:] fr.equation_E.insertNew(equationStr) # Suggested proximal limit suggestedProximalLimit = self.currentParameters["suggestedProximalLimit"] suggestedProximalLimitStr = helper_functions.roundToSF(suggestedProximalLimit, NUMBER_OF_SF) fr.powSuggestedProximalLimit_E.insertNew(suggestedProximalLimitStr) ############ ## Graphs ## ############ startX = proximalLimitKM*SQRT_PI endX = distalLimitKM*SQRT_PI # Model xs = helper_functions.getStaggeredPoints(startX, endX, MODEL_PLOTTING_PRECISION) ys = [thicknessFunction(x) for x in xs] self.modelGraphFrame.plotFilledLine(xs, ys, color=colours[0]) # Regression logXs = [np.log(a) for a in self.sqrtAreaKM] logYs = [np.log(t) for t in self.thicknessM] self.regressionGraphFrame.plotScatter(logXs, logYs, False) self.regressionGraphFrame.axes.set_xlabel(r"$\log{\sqrt{Area}}$") lineXs = [np.sqrt(startX), np.sqrt(endX)] lineYs = [np.log(c) - m*x for x in lineXs] self.regressionGraphFrame.plotLine(lineXs, lineYs, colours[0]) def _updateWei(self): ########### ## Stats ## ########### fr = self.statsFrame # lambda lamb = self.currentParameters["lambda"] lambdaStr = helper_functions.roundToSF(lamb, NUMBER_OF_SF) fr.weiLambdaE.insertNew(lamb) # k k = self.currentParameters["k"] kStr = helper_functions.roundToSF(k, NUMBER_OF_SF) fr.weiKE.insertNew(k) # theta theta = self.currentParameters["theta"] thetaStr = helper_functions.roundToSF(theta, NUMBER_OF_SF) fr.weiThetaE.insertNew(theta) # Volume volume = calculateWeibullVolume(lamb, k, theta) volumeStr = helper_functions.roundToSF(volume, NUMBER_OF_SF) fr.totalEstimatedVolume_E.insertNew(volumeStr) # Error thicknessFunction = lambda x : theta*((x/lamb)**(k-2))*math.exp(-((x/lamb)**k)) error = regression_methods.meanRelativeSquaredError(self.sqrtAreaKM, self.thicknessM, thicknessFunction) errorStr = helper_functions.roundToSF(error, NUMBER_OF_SF) fr.relativeSquaredError_E.insertNew(errorStr) # Equation invLambdaStr = helper_functions.roundToSF(1/lamb, NUMBER_OF_SF) kminus2Str = helper_functions.roundToSF(k-2, NUMBER_OF_SF) equationStr = "T = " + thetaStr + "((" + invLambdaStr + "x)^" +kminus2Str + ")exp(-(" + invLambdaStr + "x)^" + kStr + ")" fr.equation_E.insertNew(equationStr) ############ ## Graphs ## ############ # Model startX = 0 endX = (self.isopachs[-1].distanceFromVentKM()+50)*SQRT_PI xs = helper_functions.getStaggeredPoints(startX,endX,MODEL_PLOTTING_PRECISION)[1:] ys = [theta*((x/lamb)**(k-2))*math.exp(-((x/lamb)**k)) for x in xs] self.modelGraphFrame.plotFilledLine(xs, ys, colours[0]) def _displayErrorSurface(self,event): try: xLL, xUL, yLL, yUL, resolution = self.errorSurfaceFrame.getSurfaceParameters() except ValueError as ve: messagebox.showerror("Calculation error", ve.args[0]) return self.graphNotebook.addFrame(self.errorSurfaceGraphFrame, text="Error surface") if self.errorSurfaceFrame.xSymbol == "\u03BB": self.errorSurfaceGraphFrame.axes.set_xlabel("$\lambda$") else: self.errorSurfaceGraphFrame.axes.set_xlabel(self.errorSurfaceFrame.xSymbol) xs = [isopach.sqrtAreaKM for isopach in self.isopachs] ys = [isopach.thicknessM for isopach in self.isopachs] if self.modelType == Model.POW: def errorFunction(c,m): thicknessFunction = lambda x : c*(x**(-m)) return math.log(regression_methods.meanRelativeSquaredError(xs, ys, thicknessFunction)) elif self.modelType == Model.WEI: def errorFunction(lamb,k): theta = calculateTheta(xs,ys,lamb,k) def thicknessFunction(x): try: return np.exp(np.log(theta)+(k-2)*np.log(x/lamb)-(x/lamb)**k) except FloatingPointError: return 0 mrse = regression_methods.meanRelativeSquaredError(xs, ys, thicknessFunction) return math.log(mrse) self.errorSurfaceGraphFrame.axes.set_ylabel(self.errorSurfaceFrame.ySymbol) self.errorSurfaceGraphFrame.clear() self.errorSurfaceGraphFrame.plotSurface(errorFunction, xLL, xUL, yLL, yUL, resolution) self.graphNotebook.select(self.errorSurfaceGraphFrame) def _parametersReset(self,event): self.currentParameters = deepcopy(self.defaultParameters) self._updateDisplay(False) def _parametersChanged(self,event): try: newValues = self.statsFrame.getParameters(self.modelType) except ValueError as ve: messagebox.showerror("Calculation error", ve.args[0]) return if self.modelType == Model.EXP: self.currentParameters["segmentCoefficients"][self.currentSegment] = newValues["c"] self.currentParameters["segmentExponents"][self.currentSegment] = newValues["m"] self.currentParameters["segmentLimits"][self.currentSegment] = newValues["segStart"] self.currentParameters["segmentLimits"][self.currentSegment+1] = newValues["segEnd"] elif self.modelType == Model.POW: self.currentParameters["coefficient"] = newValues["c"] self.currentParameters["exponent"] = newValues["m"] elif self.modelType == Model.WEI: self.currentParameters["lambda"] = newValues["lambda"] self.currentParameters["k"] = newValues["k"] self.currentParameters["theta"] = newValues["theta"] self._updateDisplay(False) def clear(self): if self.modelType is not None: for component in self.statsFrame.components[self.modelType]: component.grid_remove() self.statsFrame.grid_remove() self.graphNotebook.grid_remove() self.errorSurfaceFrame.grid_remove() self.errorSurfaceSeperator.grid_remove() self.config(text="Results") self.modelGraphFrame.clear() self.regressionGraphFrame.clear() self.errorSurfaceGraphFrame.clear() self.graphNotebook.removeFrame(self.regressionGraphFrame) self.graphNotebook.removeFrame(self.errorSurfaceGraphFrame) self.modelType = None
def __init__(self, master): self.filename = '' # By default drop down menu will have Text mode self.list_choice = 'Text' self.label = Label(master, text="DATA:", fg="#ED3276") self.label.grid(row=2, sticky=W, padx=5) self.entry = Entry(master, width="128") self.entry.grid(row=2, column=1, padx=5) # add mouse click event to the data entry field self.entry.bind('<Button-1>', self.clean_up) self.button = Button(master, text="Hashify!", command=self.calc_hash) self.button.grid(row=16, column=1, padx=5, pady=3) self.op_button = Button(master, text="Choose File", command=self.open_box) self.var = StringVar() self.lst = ["Text", "File"] # , "HexString"] self.var.set(self.lst[0]) self.drop_menu = OptionMenu(master, self.var, *self.lst, command=self.toggle_open_btn) self.drop_menu.grid(row=0, column=0, padx=5, sticky=W) self.sep1 = Separator(master, orient=HORIZONTAL) self.sep1.grid(row=1, sticky='we', columnspan=2, pady=5, padx=5) self.sep2 = Separator(master, orient=HORIZONTAL) self.sep2.grid(row=3, sticky='we', columnspan=2, pady=5, padx=5) self.l_md5 = Label(master, text="MD5:", fg="#ED3276") self.l_sha1 = Label(master, text="SHA1:", fg="#ED3276") self.l_sha224 = Label(master, text="SHA-224:", fg="#ED3276") self.l_sha256 = Label(master, text="SHA-256:", fg="#ED3276") self.l_sha384 = Label(master, text="SHA-384:", fg="#ED3276") self.l_sha512 = Label(master, text="SHA-512:", fg="#ED3276") self.l_ripemd = Label(master, text="RIPE-MD-160:", fg="#ED3276") self.l_md4 = Label(master, text="MD4:", fg="#ED3276") self.l_whirl = Label(master, text="WHIRLPOOL:", fg="#ED3276") self.l_dsa = Label(master, text="DSA:", fg="#ED3276") self.l_crc32 = Label(master, text="CRC-32:", fg="#ED3276") self.l_adler32 = Label(master, text="ADLER-32:", fg="#ED3276") self.entryMd5 = Entry(master, width="128") self.entryMd4 = Entry(master, width="128") self.entrySha1 = Entry(master, width="128") self.entrySha224 = Entry(master, width="128") self.entrySha256 = Entry(master, width="128") self.entrySha384 = Entry(master, width="128") self.entrySha512 = Entry(master, width="128") self.entryRipeMd = Entry(master, width="128") self.entryWhirl = Entry(master, width="128") self.entryDsa = Entry(master, width="128") self.entryCrc = Entry(master, width="128") self.entryAdler = Entry(master, width="128") self.l_md5.grid(row=4, sticky=W, padx=5) self.entryMd5.grid(row=4, column=1) self.l_sha1.grid(row=5, sticky=W, padx=5) self.entrySha1.grid(row=5, column=1) self.l_sha224.grid(row=6, sticky=W, padx=5) self.entrySha224.grid(row=6, column=1) self.l_sha256.grid(row=7, sticky=W, padx=5) self.entrySha256.grid(row=7, column=1) self.l_sha384.grid(row=8, sticky=W, padx=5) self.entrySha384.grid(row=8, column=1) self.l_sha512.grid(row=9, sticky=W, padx=5) self.entrySha512.grid(row=9, column=1) self.l_md4.grid(row=10, sticky=W, padx=5) self.entryMd4.grid(row=10, column=1) self.l_ripemd.grid(row=11, sticky=W, padx=5) self.entryRipeMd.grid(row=11, column=1) self.l_whirl.grid(row=12, sticky=W, padx=5) self.entryWhirl.grid(row=12, column=1) self.l_dsa.grid(row=13, sticky=W, padx=5) self.entryDsa.grid(row=13, column=1) self.l_crc32.grid(row=14, sticky=W, padx=5) self.entryCrc.grid(row=14, column=1) self.l_adler32.grid(row=15, sticky=W, padx=5) self.entryAdler.grid(row=15, column=1) # Disable all the Entry fields self.disable_entry()
class HashClass: def __init__(self, master): self.filename = '' # By default drop down menu will have Text mode self.list_choice = 'Text' self.label = Label(master, text="DATA:", fg="#ED3276") self.label.grid(row=2, sticky=W, padx=5) self.entry = Entry(master, width="128") self.entry.grid(row=2, column=1, padx=5) # add mouse click event to the data entry field self.entry.bind('<Button-1>', self.clean_up) self.button = Button(master, text="Hashify!", command=self.calc_hash) self.button.grid(row=16, column=1, padx=5, pady=3) self.op_button = Button(master, text="Choose File", command=self.open_box) self.var = StringVar() self.lst = ["Text", "File"] # , "HexString"] self.var.set(self.lst[0]) self.drop_menu = OptionMenu(master, self.var, *self.lst, command=self.toggle_open_btn) self.drop_menu.grid(row=0, column=0, padx=5, sticky=W) self.sep1 = Separator(master, orient=HORIZONTAL) self.sep1.grid(row=1, sticky='we', columnspan=2, pady=5, padx=5) self.sep2 = Separator(master, orient=HORIZONTAL) self.sep2.grid(row=3, sticky='we', columnspan=2, pady=5, padx=5) self.l_md5 = Label(master, text="MD5:", fg="#ED3276") self.l_sha1 = Label(master, text="SHA1:", fg="#ED3276") self.l_sha224 = Label(master, text="SHA-224:", fg="#ED3276") self.l_sha256 = Label(master, text="SHA-256:", fg="#ED3276") self.l_sha384 = Label(master, text="SHA-384:", fg="#ED3276") self.l_sha512 = Label(master, text="SHA-512:", fg="#ED3276") self.l_ripemd = Label(master, text="RIPE-MD-160:", fg="#ED3276") self.l_md4 = Label(master, text="MD4:", fg="#ED3276") self.l_whirl = Label(master, text="WHIRLPOOL:", fg="#ED3276") self.l_dsa = Label(master, text="DSA:", fg="#ED3276") self.l_crc32 = Label(master, text="CRC-32:", fg="#ED3276") self.l_adler32 = Label(master, text="ADLER-32:", fg="#ED3276") self.entryMd5 = Entry(master, width="128") self.entryMd4 = Entry(master, width="128") self.entrySha1 = Entry(master, width="128") self.entrySha224 = Entry(master, width="128") self.entrySha256 = Entry(master, width="128") self.entrySha384 = Entry(master, width="128") self.entrySha512 = Entry(master, width="128") self.entryRipeMd = Entry(master, width="128") self.entryWhirl = Entry(master, width="128") self.entryDsa = Entry(master, width="128") self.entryCrc = Entry(master, width="128") self.entryAdler = Entry(master, width="128") self.l_md5.grid(row=4, sticky=W, padx=5) self.entryMd5.grid(row=4, column=1) self.l_sha1.grid(row=5, sticky=W, padx=5) self.entrySha1.grid(row=5, column=1) self.l_sha224.grid(row=6, sticky=W, padx=5) self.entrySha224.grid(row=6, column=1) self.l_sha256.grid(row=7, sticky=W, padx=5) self.entrySha256.grid(row=7, column=1) self.l_sha384.grid(row=8, sticky=W, padx=5) self.entrySha384.grid(row=8, column=1) self.l_sha512.grid(row=9, sticky=W, padx=5) self.entrySha512.grid(row=9, column=1) self.l_md4.grid(row=10, sticky=W, padx=5) self.entryMd4.grid(row=10, column=1) self.l_ripemd.grid(row=11, sticky=W, padx=5) self.entryRipeMd.grid(row=11, column=1) self.l_whirl.grid(row=12, sticky=W, padx=5) self.entryWhirl.grid(row=12, column=1) self.l_dsa.grid(row=13, sticky=W, padx=5) self.entryDsa.grid(row=13, column=1) self.l_crc32.grid(row=14, sticky=W, padx=5) self.entryCrc.grid(row=14, column=1) self.l_adler32.grid(row=15, sticky=W, padx=5) self.entryAdler.grid(row=15, column=1) # Disable all the Entry fields self.disable_entry() def clean_up(self, event): self.entry.delete(0, END) self.enable_entry() self.clear_fields() self.disable_entry() if self.filename != '': self.filename = '' def toggle_open_btn(self, val): # The method for cleanup self.clean_up(0) self.list_choice = val if val == "Text": self.op_button.grid_forget() if val == "File": self.op_button.grid(row=0, column=1, padx=5, pady=5, sticky=W) def open_box(self): self.clean_up(0) self.filename = filedialog.askopenfilename() self.entry.insert(0, self.filename) def calc_hash(self): if self.list_choice == "File": if os.path.isfile(self.filename): # read() from file as bytes txt = open(self.filename, 'rb').read() else: # No such file, warning self.filename = '' messagebox.showinfo('Error', 'File not found !\n' + self.entry.get()) return elif self.list_choice == "Text": txt = self.entry.get().encode() self.enable_entry() self.clear_fields() print(self.list_choice) # algorithms_guaranteed self.entryMd5.insert(0, hlb.md5(txt).hexdigest()) self.entrySha1.insert(0, hlb.sha1(txt).hexdigest()) self.entrySha224.insert(0, hlb.sha224(txt).hexdigest()) self.entrySha256.insert(0, hlb.sha256(txt).hexdigest()) self.entrySha384.insert(0, hlb.sha384(txt).hexdigest()) self.entrySha512.insert(0, hlb.sha512(txt).hexdigest()) # algorithms_not_guaranteed # Collisions might occur # Using the same object initialized in __init__ method results in unsecured hashes. # So initialize objects each time self.init_insecure_hashes() # ripemd160 self.ripe.update(txt) self.entryRipeMd.insert(0, self.ripe.hexdigest()) # md4 self.md4.update(txt) self.entryMd4.insert(0, self.md4.hexdigest()) # whirlpool self.whirl.update(txt) self.entryWhirl.insert(0, self.whirl.hexdigest()) # dsa self.dsa.update(txt) self.entryDsa.insert(0, self.dsa.hexdigest()) # Starting from index 2 to get rid of the '0x' # crc32 self.entryCrc.insert(0, (8 - len(hex(crc32(txt))[2:])) * '0' + hex(crc32(txt))[2:]) # adler32 self.entryAdler.insert(0, (8 - len(hex(adler32(txt))[2:])) * '0' + hex(adler32(txt))[2:]) self.disable_entry() def clear_fields(self): self.entryMd5.delete(0, END) self.entrySha1.delete(0, END) self.entrySha224.delete(0, END) self.entrySha256.delete(0, END) self.entrySha384.delete(0, END) self.entrySha512.delete(0, END) self.entryRipeMd.delete(0, END) self.entryMd4.delete(0, END) self.entryWhirl.delete(0, END) self.entryDsa.delete(0, END) self.entryCrc.delete(0, END) self.entryAdler.delete(0, END) def init_insecure_hashes(self): self.ripe = hlb.new("ripemd160") self.md4 = hlb.new("md4") self.whirl = hlb.new("whirlpool") self.dsa = hlb.new("dsaEncryption") def disable_entry(self): self.entryMd5.config(state="readonly") self.entryMd4.config(state="readonly") self.entrySha1.config(state="readonly") self.entrySha224.config(state="readonly") self.entrySha256.config(state="readonly") self.entrySha384.config(state="readonly") self.entrySha512.config(state="readonly") self.entryRipeMd.config(state="readonly") self.entryWhirl.config(state="readonly") self.entryDsa.config(state="readonly") self.entryCrc.config(state="readonly") self.entryAdler.config(state="readonly") def enable_entry(self): self.entryMd5.config(state=NORMAL) self.entryMd4.config(state=NORMAL) self.entrySha1.config(state=NORMAL) self.entrySha224.config(state=NORMAL) self.entrySha256.config(state=NORMAL) self.entrySha384.config(state=NORMAL) self.entrySha512.config(state=NORMAL) self.entryRipeMd.config(state=NORMAL) self.entryWhirl.config(state=NORMAL) self.entryDsa.config(state=NORMAL) self.entryCrc.config(state=NORMAL) self.entryAdler.config(state=NORMAL)
def __init__(self,parent): LabelFrame.__init__(self,parent,text="Model",borderwidth=5) self.selection = tkinter.IntVar() self.exponential = Radiobutton(self,text="Exponential model",variable=self.selection,value=Model.EXP.value,command=self.changeSelection) self.powerlaw = Radiobutton(self,text="Power law model",variable=self.selection,value=Model.POW.value,command=self.changeSelection) self.weibull = Radiobutton(self,text="Weibull model",variable=self.selection,value=Model.WEI.value,command=self.changeSelection) self.exponential.grid(row=0,column=0,sticky="W",padx=10,pady=(self.topPadding,5)) self.powerlaw.grid(row=1,column=0,sticky="W",padx=10,pady=5) self.weibull.grid(row=2,column=0,sticky="W",padx=10,pady=(5,0)) seperator = Separator(self, orient=tkinter.VERTICAL) seperator.grid(row=0, column=1, rowspan=3, sticky="NS", padx=(20,10), pady=(self.topPadding,0)) ## Exponential setup self.expNumberOfSegments_L = Label(self,text="Number of segments: ") self.expNumberOfSegments_E = Entry(self,width=5, justify="right") self.expNumberOfSegments_E.insert(0, settings.EXP_DEFAULT_NUMBER_OF_SEGMENTS) self.expWidgets = [self.expNumberOfSegments_L,self.expNumberOfSegments_E] ## Power law setup self.powProximalLimit_L = Label(self,text="Proximal limit of integration: ") self.powProximalLimit_E = Entry(self,width=5, justify="right") self.powDistalLimit_L = Label(self,text="Distal limit of integration: ") self.powDistalLimit_E = Entry(self,width=5, justify="right") self.powProximalLimit_E.insert(0, settings.POW_DEFAULT_PROXIMAL_LIMIT) self.powDistalLimit_E.insert(0, settings.POW_DEFAULT_DISTAL_LIMIT) self.powWidgets = [self.powProximalLimit_L,self.powProximalLimit_E, self.powDistalLimit_L,self.powDistalLimit_E] ## Weibull setup self.weiNumberOfRuns_L = Label(self,text="Number of runs: ") self.weiNumberOfRuns_E = Entry(self,width=5, justify="right") self.weiIterationsPerRun_L = Label(self,text="Iterations per run: ") self.weiIterationsPerRun_E = Entry(self,width=5, justify="right") self.weiEstimatedTime_L = Label(self,text="Estimated time (s): ") self.weiEstimatedTime_E = CustomEntry(self,width=5, justify="right") self.weiEstimatedTime_E.setUserEditable(False) self.weiLambdaLowerBoundL = Label(self,text="\u03BB lower bound:") self.weiLambdaUpperBoundL = Label(self,text="\u03BB upper bound:") self.weiLambdaLowerBoundE = Entry(self,width=5, justify="right") self.weiLambdaUpperBoundE = Entry(self,width=5, justify="right") self.weiKLowerBoundL = Label(self,text="k lower bound:") self.weiKUpperBoundL = Label(self,text="k upper bound:") self.weiKLowerBoundE = Entry(self,width=5, justify="right") self.weiKUpperBoundE = Entry(self,width=5, justify="right") self.weiNumberOfRuns_E.insert(0, settings.WEI_DEFAULT_NUMBER_OF_RUNS) self.weiIterationsPerRun_E.insert(0, settings.WEI_DEFAULT_ITERATIONS_PER_RUN) self.weiLambdaLowerBoundE.insert(0, settings.WEI_DEFAULT_LAMBDA_LOWER_BOUND) self.weiLambdaUpperBoundE.insert(0, settings.WEI_DEFAULT_LAMBDA_UPPER_BOUND) self.weiKLowerBoundE.insert(0, settings.WEI_DEFAULT_K_LOWER_BOUND) self.weiKUpperBoundE.insert(0, settings.WEI_DEFAULT_K_UPPER_BOUND) self.weiWidgets = [self.weiNumberOfRuns_L,self.weiNumberOfRuns_E, self.weiIterationsPerRun_L,self.weiIterationsPerRun_E, self.weiEstimatedTime_L,self.weiEstimatedTime_E, self.weiLambdaLowerBoundL,self.weiLambdaUpperBoundL,self.weiLambdaLowerBoundE,self.weiLambdaUpperBoundE, self.weiKLowerBoundL,self.weiKUpperBoundL,self.weiKLowerBoundE,self.weiKUpperBoundE] ## General self.currentWidgets = [] self.selection.set(Model.EXP.value) self.changeSelection()