def __setup_buttons(self, data): Label(self, text='Document UUID').grid(column=0, row=1) doc_entry = Entry(self) doc_entry.grid(column=0, row=2) Label(self, text='User UUID (optional)').grid(column=1, row=1) user_entry = Entry(self) user_entry.grid(column=1, row=2) search_button = Button(self, text='Find', command=lambda: self.__find_page( doc_entry.get(), user_entry.get())) search_button.grid(column=2, row=2) docs = sorted(data.documents.values(), key=lambda document: len(document.views), reverse=True) for val, doc in enumerate(docs[:20], 3): text = doc.doc_id[:6] + "... " button = Button(self, text=text, width=20, command=lambda document=doc: self.controller. show_graph_page(document)) button.grid(column=0, row=val) label = Label(self, text=str(len(doc.views)) + " views") label.grid(column=1, row=val) self.active_buttons.append((button, label))
def load_login_page(): label_username = Label(frame_login, text="Username:"******"*", font=font) label_error = Label(frame_login, text="", font=font, foreground="red") label_password = Label(frame_login, text="Password:"******"Login", width=10, command=lambda: check_credentials(input_username.get(), input_password, label_error)) button_login.bind( '<Return>', lambda _: check_credentials(input_username.get(), input_password, label_error)) label_username.grid(column=1, row=1, pady=(0, 10)) input_username.grid(column=2, row=1, pady=(0, 10), sticky=W) label_password.grid(column=1, row=2) input_password.grid(column=2, row=2, sticky=W) input_password.bind( '<Return>', lambda _: check_credentials(input_username.get(), input_password, label_error)) label_error.grid(column=2, row=3, sticky=W) button_login.grid(column=2, row=4, pady=10, sticky=W) frame_login.grid()
def customDate(): def displayCustomDate(date): enterDateBox.destroy() print("Start listing songs from: " + date + ".") try: chart = billboard.ChartData("hot-100", date) label1 = str("1. " + str(chart[0])) label2 = str("2. " + str(chart[1])) label3 = str("3. " + str(chart[2])) label4 = str("4. " + str(chart[3])) label5 = str("5. " + str(chart[4])) topSong1.set(label1) topSong2.set(label2) topSong3.set(label3) topSong4.set(label4) topSong5.set(label5) chart_date.set("Chart data date: " + date) print("Done listing songs from: " + date + ".") except Exception as e: logDump(e) messagebox.showerror( "Out of range date", "Check your dates again. It could be due to:\n-Date too long in the past (before BillBoard charts existed)\-" ) def cancelDialog(): enterDateBox.destroy() date_object = datetime.now() formatted_date = "Chart data date: " + date_object.strftime( '%Y-%m-%d') chart_date.set(formatted_date) enterDateBox = Toplevel(billpy_window) enterDateBox.grab_set() enterDateBox.title("Custom date entry") enterDateBox.focus_set() enterDate_msg = Label(enterDateBox, text="Enter the date below (YYYY-MM-DD):", font=("Segoe UI", 10)) enterDate_entry = Entry(enterDateBox) enterDate_entry.focus_set() enterDate_confirm = Button( enterDateBox, text="OK", command=lambda: displayCustomDate(enterDate_entry.get())) enterDate_confirm.bind( "<Return>", lambda: displayCustomDate(enterDate_entry.get())) enterDate_cancel = Button(enterDateBox, text="Cancel", command=cancelDialog) enterDate_msg.pack() enterDate_entry.pack() enterDate_confirm.pack() enterDate_cancel.pack() centerForms(enterDateBox) chart_date.set("Loading charts...") enterDateBox.mainloop()
class SimpleDialog(Frame): def __init__(self): super().__init__() self.output1 = "" self.output2 = "" self.output3 = "" self.entry1 = "" self.entry2 = "" self.entry3 = "" self.initUI() def initUI(self): self.master.title("Birthday Calc") self.pack(fill=BOTH, expand=True) frame1 = Frame(self) frame1.pack(fill=X) lbl1 = Label(frame1, text="day", width=8) lbl1.pack(side=LEFT, padx=1, pady=2) self.entry1 = Entry(frame1, textvariable=self.output1) self.entry1.pack(fill=X, padx=1, expand=True) frame2 = Frame(self) frame2.pack(fill=X) lbl2 = Label(frame2, text="month", width=8) lbl2.pack(side=LEFT, padx=1, pady=2) self.entry2 = Entry(frame2) self.entry2.pack(fill=X, padx=1, expand=True) frame3 = Frame(self) frame3.pack(fill=X) lbl3 = Label(frame3, text="year", width=8) lbl3.pack(side=LEFT, padx=1, pady=2) self.entry3 = Entry(frame3) self.entry3.pack(fill=X, padx=1, expand=True) frame4 = Frame(self) frame4.pack(fill=X) btn = Button(frame4, text="Calc", command=self.onClick) btn.pack(padx=10, pady=10) def onClick(self): self.output1 = self.entry1.get() self.output2 = self.entry2.get() self.output3 = self.entry3.get() self.quit()
class LoginWindow(TkinterWindow): """ Login GUI Window """ def __init__(self, event_handlers): """Have a username, password, and submit button""" super().__init__(event_handlers) self.master.title("EmpDat Login") self.master.resizable(False, False) main = Frame(self.master) icon_image = ui.load_image("ui/icons/EmpDat.gif") icon = Label(main, image=icon_image) icon.image = icon_image icon.pack(padx=10, pady=10) self.title = Label(main, text="EmpDat") self.title.pack(pady=10) self.username = Label(main, text="Employee ID") self.entry = Entry(main, width=50) self.username.pack() self.entry.pack(padx=10) self.password = Label(main, text="Password") self.password_entry = Entry(main, width=50, show="•") self.password.pack() self.password_entry.pack(padx=10) self.submit_button = Button( main, text="Submit", command=lambda: event_handlers['submit'] (self.entry.get(), self.password_entry.get()), ) self.submit_button.pack(pady=10) main.pack() self.master.bind( '<Return>', lambda x: event_handlers['submit'] (self.entry.get(), self.password_entry.get())) def validate(self): """ Validates login fields :return: bool is_valid """ if len(self.entry.get()) <= 0: self.show_error('Username required', 'No username given.') return False return True
class WinLogin(Tk): def __init__(self, *args, **kwargs): ''' Se establecen las configuraciones de la ventana de logueo ''' global connection self.cursor = connection.cursor() self.accepted = False self.root = Tk() self.root.title("Inicio de sesión") self.root.resizable(0, 0) # Cuando se genera el evento de eliminar la pantalla (cerrarla) # se destuye la ventana principal de la aplicación que estaba minimizada self.root.protocol("WM_DELETE_WINDOW", self.root.destroy) lbl_user = Label(self.root, text="Usuario: ") lbl_user.grid(row=0, column=0, padx=(20, 10), pady=(10, 0)) self.e_user = Entry(self.root, width=25) self.e_user.grid(row=0, column=1, padx=(10, 20), pady=(20, 10)) self.e_user.focus_set() lbl_password = Label(self.root, text="Contraseña: ") lbl_password.grid(row=2, column=0, padx=(20, 10)) self.e_password = Entry(self.root, width=25, show="*") self.e_password.grid(row=2, column=1, padx=(10, 20), pady=10) btn_login = Button(self.root, text="Ingresar", command=self.login) btn_login.grid(row=3, column=0, columnspan=3, padx=10, pady=(5, 20)) self.root.mainloop() def login(self): ''' Realiza el proceso de logueo de un administrador ''' # Busca el administrador que posea el usuario y la contraseña proporcionados. sql = '''SELECT * FROM `Administrador` WHERE usuario = (?) and contrasena = (?)''' self.cursor.execute(sql, (self.e_user.get(), self.e_password.get())) # Si lo encontró, completa el logueo. Caso contrario, informa el error. if self.cursor.fetchone(): self.accepted = True self.root.destroy() else: mb.showerror("Datos inválidos", "El usuario y/o la contraseña son incorrectos.")
class ProjectWindow(): def __init__(self, master): self.master = master # self.master.geometry("500x300+300+300") self.master.title("ProjectWindow") self.project = dict() self.init_ui() super().__init__() def init_ui(self): self.frame = Frame(self.master) self.frame.pack(fill=X) self.frame_footer = Frame(self.master) self.frame_footer.pack(side=BOTTOM) row = 1 first_column_width = 15 second_column_width = 60 lbl_name = Label(self.frame, text="Name") lbl_name.grid(row=row, column=0) self.project_name = Entry(self.frame, width=second_column_width) self.project_name.grid(row=row, column=1) row += 1 lbl_description = Label(self.frame, text="Description") lbl_description.grid(row=row, column=0) self.project_description = Entry(self.frame, width=second_column_width) self.project_description.grid(row=row, column=1) bttn_create_project = Button(self.frame_footer, text="Create", command=self.create_project) bttn_create_project.pack(side=BOTTOM, padx=5, pady=5) def create_project(self): if self.project_name.get(): project = Project(name=self.project_name.get(), description=self.project_description.get()) project = db.create(project) db.commit_changes() global app app.update_projects() app.project_cmbx.set(project.name) app.project_selected() self.master.destroy() else: messagebox.showerror("Error", "Project Name cannot be null")
def __init__(self, root): ttk.Frame.__init__(self, root) Label(root, text='title').grid(row=0, column=0, sticky=W) Label(root, text='body').grid(row=1, column=0, sticky=W) Label(root, text='labels[]').grid(row=2, column=0, sticky=W) Label(root, text='milestone').grid(row=3, column=0, sticky=W) Label(root, text='assignees[]').grid(row=4, column=0, sticky=W) Label(root, text='status').grid(row=5, column=0, sticky=W) entryTitle = Entry(root, width=50) entryTitle.grid(row=0, column=1, padx=5, pady=5) entryBody = Text(root, width=57, height=8) entryBody.grid(row=1, column=1, padx=5, pady=5) entryLabels = Entry(root, width=50) entryLabels.grid(row=2, column=1, padx=5, pady=5) entryMilestone = Entry(root, width=50) entryMilestone.grid(row=3, column=1, padx=5, pady=5) entryAssignees = Entry(root, width=50) entryAssignees.grid(row=4, column=1, padx=5, pady=5) entryStatus = Entry(root, width=50) entryStatus.grid(row=5, column=1, padx=5, pady=5) lblResult = Label(root, text="") lblResult.grid(row=7, column=0, columnspan=2, padx=5, pady=5) buttonSave = Button(root, text="Save", width=70, command=lambda: root.saveNewIssue( { "title": entryTitle.get(), "body": entryBody.get("1.0", END), "labels": entryLabels.get(), "milestone": entryMilestone.get(), "assignees": entryAssignees.get(), "status": entryStatus.get(), }, lblResult)) buttonSave.grid(row=6, column=0, columnspan=2, padx=5, pady=5) buttonSave = Button(root, text="Close", width=70, command=root.closeButton) buttonSave.grid(row=8, column=0, columnspan=2, padx=5, pady=5)
class SegmentationConfigFrame(Frame): def __init__(self, parent, configuration): Frame.__init__(self, parent) self.configuration = configuration self.sigma_in = None self.tau_in = None self.position_in = None self.position_value = None self.init_view() def init_view(self): Label(self, text="Sigma").grid(row=0, column=0, sticky="w") self.sigma_in = Entry(self) self.sigma_in.insert(END, self.configuration.qs_sigma) self.sigma_in.grid(row=0, column=1, sticky="w", padx=5, pady=5) Label(self, text="Tau").grid(row=1, column=0, sticky="w") self.tau_in = Entry(self) self.tau_in.insert(END, self.configuration.qs_tau) self.tau_in.grid(row=1, column=1, sticky="w", padx=5, pady=5) self.position_value = IntVar() self.position_in = Checkbutton(self, text="Use position", variable=self.position_value) self.position_in.grid(row=2, column=0, columnspan=2, sticky="w", padx=5, pady=5) def get_values(self): errors = [] try: sigma_val = int(self.sigma_in.get()) except ValueError: errors.append("Invalid value for sigma") try: tau_val = int(self.tau_in.get()) except ValueError: errors.append("Invalid value for tau") if errors: raise ValidationError("Segmentation validation error", errors) return sigma_val, tau_val, self.position_value.get()
def login(self, username_entry: ttk.Entry, password_entry: ttk.Entry): data: dict = {"Usuario": str, "Contrasena": str} data["Usuario"] = username_entry.get() data["Contrasena"] = password_entry.get() response = self.makeRequest("POST", "login", data) if response.status_code == 200: self.interface_state = response.json()["account_type"] elif response.status_code == 401: messagebox.showerror("", "usuario o contrasena invalidos") password_entry.delete(0, tk.END) else: print("error en el server, help!!!")
class AuthPopup(Toplevel): def __init__(self, master, auth=dict()): self.master = master Toplevel.__init__(self, self.master) self.auth = auth self.title('Enter details') self._create_widgets() self.deiconify() self.focus_set() # wait for window to appear on screen before calling grab_set self.wait_visibility() self.grab_set() self.wait_window(self) self.bind('<Return>', self._proceed) def _create_widgets(self): frame = Frame(self) Label(frame, text="Username: "******"Password: "******"*") self.pword_box.grid(column=1, row=1) btn = Button(frame, text="Cancel", command=self._exit) btn.grid(column=0, row=2, sticky='w') btn = Button(frame, text="Confirm", command=self._proceed) btn.grid(column=1, row=2, sticky='w') frame.grid() def _exit(self): self.auth['uname'] = self.uname_box.get() self.auth['pword'] = self.pword_box.get() self.withdraw() self.update_idletasks() self.master.focus_set() self.destroy() def _proceed(self): self.auth['uname'] = self.uname_box.get() self.auth['pword'] = self.pword_box.get() self.withdraw() self.update_idletasks() self.master.focus_set() self.destroy()
class PasswordDialog(TkinterDialog): """ Dialog for changing others' passwords """ def __init__(self, event_handlers, employees): """ Shows the employee picker, a password, and a password confirm field :param event_handlers: Expects 'save' :param employees: list of valid employees """ super().__init__(event_handlers) # Employee Picker self.emp_label = Label(self, text="Employee:") self.emp_label.grid(column=0, row=0) self.employee_selected = StringVar(self) self.employee_picker = EmployeePicker(self, self.employee_selected, employees) self.employee_picker.grid(column=1, row=0) Label(self, text="New Password").grid(column=0, row=1) self.password_entry = Entry(self, width=50, show="•") self.password_entry.grid(column=1, row=1) Label(self, text="Confirm Password").grid(column=0, row=2) self.confirm_password_entry = Entry(self, width=50, show="•") self.confirm_password_entry.grid(column=1, row=2) Label(self, text="Passwords need to include one number, one " "capital letter, and one special character") \ .grid(column=0, row=3, columnspan=2) # Actions self.save_btn = Button( self, text="Save", command=lambda: self.event_handlers['save'] (self, self.employee_picker.get_value(), self.password_entry.get(), self.confirm_password_entry.get())) self.save_btn.grid(column=0, row=4) self.cancel_btn = Button(self, text="Cancel", command=self.destroy) self.cancel_btn.grid(column=1, row=4) self.master.bind( '<Return>', lambda: self.event_handlers['save'] (self, self.employee_picker.get_value(), self.password_entry.get(), self.confirm_password_entry.get()))
def get_number_from(entry: Entry) -> float: try: return float(fix_separator(entry.get())) except ValueError: entry.focus_set() entry.select_range(0, END) stop_execution("Неверный формат строки")
class AddAlertPopup(object): def __init__(self, master, coin): self.top = Toplevel(master) self.top.title("Add Alert") Label(self.top, text=("Alert when price goes")).grid(row=0, column=0, columnspan=2, sticky="NEWS") b_m = ["above", "below"] self.a = Combobox(self.top, values=b_m, width=10) self.a.set(b_m[0]) self.a.grid(row=1, column=0, sticky="NEWS") self.e = Entry(self.top) self.e.focus_set() self.e.grid(row=1, column=1, sticky="NEWS") mark = [coin.market, "USDT"] self.m = Combobox(self.top, values=mark, width=10) self.m.set(mark[0]) self.m.grid(row=1, column=2, sticky="NEWS") Button(self.top, text='Ok', command=self.cleanup).grid(row=2, column=0, columnspan=3) ##center after packing center(self.top, master) def cleanup(self): self.value = [self.a.get(), self.e.get(), self.m.get()] self.top.destroy()
def attr_list_entry_callback(self, _event, attrib, entry_box: ttk.Entry, selected_widget): if selected_widget is not None: values: str = entry_box.get() values.strip(' ') if values.startswith('[') and values.endswith(']'): values = values[1:-1].strip(' ') value_list = [] while len(values) > 0: if values[0] == "'": next_value = values[1:].split("'")[0] value_list.append(next_value) values = values[(2 + len(next_value)):].strip(' ') if values.startswith(','): values = values[1:].strip(' ') else: entry_box.delete(0, tkinter.END) entry_box.insert(0, str(getattr(selected_widget, attrib))) raise Exception( 'entry should be a list of str, comma separated') else: value_list = [values] return_value = self.pyted_core.update_widget_attribute( selected_widget, attrib, value_list) # self.update_attr_frame() if selected_widget.tk_name is not None: self.handles.place_selected_widget_handles( selected_widget.tk_name) if return_value is not None: messagebox.showwarning( 'Renaming problem', 'Name already exists for another widget and Name not changed' )
class DateWidget(Frame): """Gets a date from the user.""" def __init__(self, master): """Make boxes, register callbacks etc.""" Frame.__init__(self, master) self.label = Label(self, text="När är du född?") self.label.pack() self.entry_text = StringVar() self.entry_text.trace("w", lambda *args: self.onEntryChanged()) self.entry = Entry(self, width=date_entry_width, textvariable=self.entry_text) self.entry.insert(0, "ÅÅÅÅ-MM-DD") self.entry.pack(pady=small_pad) self.button = Button(self, text="Uppdatera", command=lambda: self.onDateChanged()) self.button.pack() self.entry.focus_set() self.entry.select_range(0, END) self.entry.bind("<Return>", lambda x: self.onDateChanged()) def setListener(self, pred_view): """Select whom to notify when a new date is entered.""" self.pred_view = pred_view def onDateChanged(self): """Notifies the PredictionWidget that the date has been changed.""" try: date = datetime.datetime.strptime(self.entry.get(), "%Y-%m-%d").date() self.pred_view.update(date) except ValueError: self.entry.configure(foreground="red") def onEntryChanged(self): """Reset the text color.""" self.entry.configure(foreground="")
class AskElement(Toplevel): def __init__(self, window, callback): super(AskElement, self).__init__(window) self.window = window self.callback = callback self.clabel = Label(self, text="Entrez le type de l'élément :", font=("Arial", "14")) self.combo = Combobox(self, values=ELEMENTS) self.elabel = Label(self, text="Entrez le nom de l'élément :", font=("Arial", "14")) self.entry = Entry(self) self.button = Button(self, text="Valider", command=self.valide) self.combo.current(0) self.clabel.pack(padx=10, pady=10) self.combo.pack(padx=10, pady=7) self.elabel.pack(padx=10, pady=17) self.entry.pack(padx=10, pady=0) self.button.pack(padx=10, pady=7) self.title("Ajouter Element") def valide(self): name = self.entry.get() type_ = ELEMENTS[self.combo.current()] if name != "": self.callback(name, type_) self.destroy()
class AddCoinPopup(object): def __init__(self, master, overview): #228 107 self.top = Toplevel(master, padx=50, pady=5) self.top.title("Add Coin") #Label(self.top, text="Add coin").grid(row=0,column=0,columnspan=2,sticky="NEWS") exch = ["Bittrex", "Binance"] mark = ["BTC", "ETH", "BNB", "USDT"] self.c = Combobox(self.top, values=exch, width=10) self.c.set(exch[0]) self.c.grid(row=0, column=0, columnspan=2, sticky="NEWS") self.m = Combobox(self.top, values=mark, width=10) self.m.set(mark[0]) self.m.grid(row=1, column=0, sticky="NEWS") self.e = Entry(self.top) self.e.focus_set() self.e.grid(row=1, column=1, columnspan=1, sticky="NEWS") Button(self.top, text='Ok', command=self.cleanup).grid(row=2, column=0, columnspan=2) ##center after packing center(self.top, master) def cleanup(self, ): self.value = [self.c.get(), self.m.get(), self.e.get()] self.top.destroy()
class Add(Toplevel): def __init__(self, master): Toplevel.__init__(self, master, class_=APP_NAME, padx=6, pady=6) self.title(_("Add Feed")) self.grab_set() self.resizable(True, False) self.columnconfigure(1, weight=1) Label(self, text=_('URL')).grid(row=0, column=0, sticky='e', pady=4, padx=4) self.url = "" self.url_entry = Entry(self, width=30) self.url_entry.grid(row=0, column=1, sticky='ew', pady=4, padx=4) self.url_entry.bind('<Return>', self.validate) frame = Frame(self) frame.grid(row=1, column=0, columnspan=2) Button(frame, text=_('Ok'), command=self.validate).grid(row=0, column=0, sticky='e', pady=4, padx=4) Button(frame, text=_('Cancel'), command=self.destroy).grid(row=0, column=1, sticky='w', pady=4, padx=4) self.url_entry.focus_set() def validate(self, event=None): self.url = self.url_entry.get().strip() self.destroy()
class SizeConfigFrame(Frame): def __init__(self, parent, configuration): Frame.__init__(self, parent) self.configuration = configuration self.use_resize_in = None self.resize_val = IntVar() self.width_in = None self.height_in = None self.init_view() def init_view(self): self.use_resize_in = Checkbutton(self, text="Resize image", variable=self.resize_val).grid( row=0, column=0, columnspan=2) Label(self, text="Width").grid(row=1, column=0, sticky="w") self.width_in = Entry(self) self.width_in.insert(END, self.configuration.size[1]) self.width_in.grid(row=1, column=1, sticky="w", padx=5, pady=5) Label(self, text="Height").grid(row=2, column=0, sticky="w") self.height_in = Entry(self) self.height_in.insert(END, self.configuration.size[0]) self.height_in.grid(row=2, column=1, sticky="w", padx=5, pady=5) def get_values(self): errors = [] try: height_value = int(self.height_in.get()) except ValueError: errors.append("Invalid height value") try: width_value = int(self.width_in.get()) except ValueError: errors.append("Invalid width value") if errors: raise ValidationError("Size validation error", errors) return self.resize_val.get(), height_value, width_value
def apagar_caracter_invalido(evento_char, ref_entry: ttk.Entry, caracteres_inválidos: str): """ Método estático para apagar os caracteres inseridos em um Entry no momento da digitação(evento Release). Pode ser usado sem instanciação. :param evento_char: event.char do evento. :param ref_entry: Referência do componente Entry. :param caracteres_inválidos: string de caracteres que deseja-se que sejam apagados. :return: none. """ if evento_char in caracteres_inválidos: ref_entry.delete(len(ref_entry.get()) - 1, 'end')
class Main(Frame): """Main class for our browser. Note that we inherit from Frame, making this a Frame object. """ def __init__(self, master): Frame.__init__(self, master) self.master = master self.master.title("Browser") self.header = {"User-Agent": "Tkinter Browser 0.1"} # Here we make our widgets. self.top_frame = Frame(self) self.url_frame = Frame(self.top_frame) self.url_label = Label(self.url_frame, text="Url: ", anchor="n") self.url_entry = Entry(self.url_frame, width=80) self.url_button = Button(self.url_frame, text="Go", command=self.go_button) self.bottom_frame = Frame(self) self.text_field = Text(self.bottom_frame) #Here we pack our widgets. self.top_frame.pack(side="top", padx=15, pady=15) self.url_frame.pack(anchor="center") self.bottom_frame.pack(side="bottom", fill="both", expand=True) self.text_field.pack(side="bottom", fill="both", expand=True) self.url_label.pack(side="left") self.url_entry.pack(side="left", fill="x", expand=True) self.url_button.pack(side="left", padx=5) self.text_field.config(state="disabled", padx=5, pady=5) def go_button(self): url = self.url_entry.get() if url: if "http://" not in url: url = "http://" + url page_text = self.get_page(url) self.text_field.config(state="normal") self.text_field.delete(1.0, "end") self.text_field.insert("end", page_text) self.text_field.config(state="disable") def get_page(self, url): s = requests.Session() resp = s.get(url, headers=self.header) data = resp.text soup = bs(data, "html.parser") page_text = soup.find_all(text=True) page_text = filter(self.visible, page_text) return "".join([str(i) + '\n' for i in page_text]) def visible(self, e): if e.parent.name in ('style', 'script', '[document]', 'head', 'title'): return False elif re.match('<!--.*-->', str(e.encode('utf-8'))): return False return True
class ArgEntry(Frame): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__namelabel = Label(self) self.__namelabel.pack(expand='yes', fill='x') self.__entry = Entry(self) self.__entry.pack(side='left', expand='yes', fill='x') self.__btn = Button(self) self.__btn.pack(side='right') self.__btn['state'] = 'disabled' @property def entry(self): return self.__entry @property def entry_text(self): return self.__entry.get() @entry_text.setter def entry_text(self, value): self.__entry.delete(0, 'end') self.__entry.insert(0, value) @property def button(self): return self.__btn @property def arg_name(self): return self.__namelabel['text'] @arg_name.setter def arg_name(self, val): self.__namelabel['text'] = val @property def arg_value(self): return self.__entry.get() @arg_value.setter def arg_value(self, val): self.__entry.delete(0, 'end') self.__entry.insert(0, val)
class Main(Frame): """Main class for our browser. Note that we inherit from Frame, making this a Frame object. """ def __init__(self, master): Frame.__init__(self, master) self.master = master self.master.title("Browser") self.header = {"User-Agent":"Tkinter Browser 0.1"} # Here we make our widgets. self.top_frame = Frame(self) self.url_frame = Frame(self.top_frame) self.url_label = Label(self.url_frame, text="Url: ", anchor="n") self.url_entry = Entry(self.url_frame, width=80) self.url_button = Button(self.url_frame, text="Go", command=self.go_button) self.bottom_frame = Frame(self) self.text_field = Text(self.bottom_frame) #Here we pack our widgets. self.top_frame.pack(side="top", padx=15, pady=15) self.url_frame.pack(anchor="center") self.bottom_frame.pack(side="bottom", fill="both", expand=True) self.text_field.pack(side="bottom", fill="both", expand=True) self.url_label.pack(side="left") self.url_entry.pack(side="left", fill="x", expand=True) self.url_button.pack(side="left", padx=5) self.text_field.config(state="disabled", padx=5, pady=5) def go_button(self): url = self.url_entry.get() if url: if "http://" not in url: url = "http://"+url page_text = self.get_page(url) self.text_field.config(state="normal") self.text_field.delete(1.0, "end") self.text_field.insert("end", page_text) self.text_field.config(state="disable") def get_page(self, url): s = requests.Session() resp = s.get(url, headers=self.header) data = resp.text soup = bs(data, "html.parser") page_text = soup.find_all(text=True) page_text = filter(self.visible, page_text) return "".join([str(i)+'\n' for i in page_text]) def visible(self, e): if e.parent.name in ('style', 'script', '[document]', 'head', 'title'): return False elif re.match('<!--.*-->', str(e.encode('utf-8'))): return False return True
class MyTestDialog( ModalDialog ): def body( self, master ): """ Override the empty ModalDialog.body function to set up the dialog how we want it. """ from tkinter.ttk import Label, Entry Label( master, text="First:" ).grid( row=0 ) Label( master, text="Second:" ).grid( row=1 ) self.e1 = Entry( master ) self.e2 = Entry( master ) self.e1.grid( row=0, column=1 ) self.e2.grid( row=1, column=1 ) return self.e1 # initial focus # end of MyTestDialog.apply def validate( self ): """ Override the empty ModalDialog.validate function to check that the results are how we need them. """ try: int( self.e1.get() ) and int( self.e2.get() ) except ValueError: print( "ERROR: We need two valid integers!" ) return False return True # end of MyTestDialog.validate def apply( self ): """ Override the empty ModalDialog.apply function to process the results how we need them. """ first = int( self.e1.get() ) second = int( self.e2.get() ) print( first, second ) # or something self.result = (first, second,)
class SimpleDialog(Frame): def __init__(self): super().__init__() self.output1 = "" self.output2 = "" self.initUI() def initUI(self): self.master.title("Length Calc") self.pack(fill=BOTH, expand=True) frame1 = Frame(self) frame1.pack(fill=X) lbl1 = Label(frame1, text="x Value", width=8) lbl1.pack(side=LEFT, padx=5, pady=10) self.entry1 = Entry(frame1, textvariable=self.output1) self.entry1.pack(fill=X, padx=5, expand=True) frame2 = Frame(self) frame2.pack(fill=X) lbl2 = Label(frame2, text="y Value", width=8) lbl2.pack(side=LEFT, padx=5, pady=10) self.entry2 = Entry(frame2) self.entry2.pack(fill=X, padx=5, expand=True) frame3 = Frame(self) frame3.pack(fill=X) btn = Button(frame3, text="Calc", command=self.onClick) btn.pack(padx=10, pady=10) def onClick(self): self.output1 = self.entry1.get() self.output2 = self.entry2.get() self.quit()
class TextureConfigFrame(Frame): def __init__(self, parent, configuration): Frame.__init__(self, parent) self.configuration = configuration self.texture_model_path_in = None self.texture_model_path_res = configuration.texture_model_path self.texture_detection_type_in = None self.texture_types = {'Window scan': 0, 'Around each pixel': 1} self.texture_detection_area_in = None self.init_view() def init_view(self): self.texture_model_path_in = Label(self, text=FileUtils.get_filename_from_path(self.configuration.texture_model_path)) self.texture_model_path_in.grid(row=0, column=1, sticky="we", padx=5, pady=5) Button(self, text="Browse model", command=self.browse_texture_model)\ .grid(row=0, column=0, sticky="w") Label(self, text="Detection type").grid(row=1, column=0, sticky="w") self.texture_detection_type_in = Combobox(self, values=list(self.texture_types.keys())) self.texture_detection_type_in.grid(row=1, column=1, sticky="w", padx=5, pady=5) Label(self, text="Detection area").grid(row=2, column=0, sticky="w") self.texture_detection_area_in = Entry(self) self.texture_detection_area_in.insert(END, self.configuration.texture_detection_area) self.texture_detection_area_in.grid(row=2, column=1, sticky="w", padx=5, pady=5) def get_values(self): errors = [] try: texture_area_value = int(self.texture_detection_area_in.get()) except ValueError: errors.append("Invalid texture area") if self.texture_detection_type_in.get() not in self.texture_types: errors.append("You must select a texture detection type") if errors: raise ValidationError("Texture validation error", errors) return self.texture_model_path_res, self.texture_types[self.texture_detection_type_in.get()], texture_area_value def browse_texture_model(self): self.texture_model_path_res = filedialog.askopenfilename() self.texture_model_path_in.config(text=self.texture_model_path_res.split('/')[-1])
class PasswordGenerator(Frame): def __init__(self): super().__init__() self.initUI() self.my_pw = '' def initUI(self): self.master.title('Simple PasswordGenerator v1.0') self.pack(fill=BOTH, expand=False) frame1 = Frame(self) frame1.pack(fill=X) lbl1 = Label(frame1, text='Input password lenght: (6-15)', width=27) lbl1.pack(side=LEFT, padx=5, pady=10) self.entry1 = Entry(frame1, width=10) self.entry1.pack(side=LEFT, padx=2) frame2 = Frame(self) frame2.pack(fill=X) lbl2 = Label(frame2, text='Generated password:'******'end') try: pw_length = int(self.entry1.get()) if pw_length >= 6 and pw_length <=15: for i in range(pw_length): index = random.randrange(len(possible_chars)) self.my_pw += possible_chars[index] self.entry2.insert(1, self.my_pw) self.my_pw = '' else: messagebox.showwarning('Error!', 'Password must be 6-15 characters!') self.entry1.delete(0, 'end') except: messagebox.showwarning('Error!', 'Field must contain a number!') self.entry1.delete(0, 'end')
def escrever_mascara_entry(evento_char, ref_entry: ttk.Entry, mascara: str, especial: str = ''): """ Método estático para formatar a entrada de um Entry de acordo com mascara. Pode ser usado sem instanciação. :param evento_char: event.char do evento. :param ref_entry: Referência do componente Entry. :param mascara: Mascara base para a formatação. Deve apresentar espacos onde quer ser inseridos os números. :return: none. """ # Apaga o Entry caso o conteúdo seja o default. if ref_entry.get() == mascara: ref_entry.delete(0, 'end') # O event.char captura de tecla literalmente, mas não captura teclas de controle(Backspace, ...). # O event.keysym usa uma nomenclatura diferente, e captura todas as teclas. # Tkinter 8.5 reference gui for Python. 161-162. if evento_char in string.digits or evento_char in especial: pos = len(ref_entry.get()) try: if mascara[pos] != ' ': ref_entry.insert('end', mascara[pos]) except IndexError: ref_entry.delete(0, 'end')
class EntryOptionsWindow: def __init__(self, ls: str, tk: Tk, select_path=False) -> None: self.select_path = select_path self.List = ls self.Tk = tk self.Root = Toplevel(self.Tk) self.Root.withdraw() self.Frame = Frame(self.Root) self.Box = Listbox(self.Frame, selectmode='extended', width=54, height=24) for i in globals()[self.List]: self.Box.insert(END, i) self.Scroll = Scrollbar(self.Frame, command=self.Box.yview) self.Entry = Entry(self.Frame) self.ButtonAdd = Button(self.Frame, text='Добавить', command=self.__add_item) self.ButtonDel = Button(self.Frame, text='Удалить', command=self.__del_item) self.ButtonDone = Button(self.Frame, text='Готово', command=self.__save_list) self.ButtonExit = Button(self.Frame, text='Отмена', command=self.Root.destroy) def __add_item(self) -> None: if self.select_path: text = filedialog.askdirectory() else: text = self.Entry.get() if text: self.Box.insert(END, text) self.Entry.delete(0, END) def __del_item(self) -> None: select = list(self.Box.curselection()) select.reverse() for i in select: self.Box.delete(i) def __save_list(self) -> None: globals()[self.List] = list(self.Box.get(0, END)) self.Root.destroy() def main(self) -> None: center_win(self.Root, '500x400') self.Root.deiconify() self.Root.title(f'Editing {self.List}') self.Box.pack(side='left', expand=True) self.Scroll.pack(side='left', fill='y') self.Box.config(yscrollcommand=self.Scroll.set) self.Frame.pack(side='left', padx=10) if not self.select_path: self.Entry.pack(anchor='n') self.ButtonAdd.pack(fill='x') self.ButtonDel.pack(fill='x') self.ButtonDone.pack(fill='x') self.ButtonExit.pack(fill='x') self.Root.mainloop()
class StartPage(Frame): def __init__(self, master, data): Frame.__init__(self, master) self.pack(fill=BOTH, expand=True) frame1 = Frame(self) frame1.pack(fill=X) label_moves = Label(frame1, text="Moves", width=6) label_moves.pack(side=LEFT, padx=5, pady=5) self.entry_moves = Entry(frame1) self.entry_moves.pack(fill=X, padx=5, expand=True) frame2 = Frame(self) frame2.pack(fill=BOTH, expand=True, pady=20, padx=5) label_table = Label(frame2, text="Table", width=6) label_table.pack() self.text_table = Text(frame2) self.text_table.pack(expand=True, fill=BOTH) frame3 = Frame(self) frame3.pack(fill=BOTH, padx=5, side=BOTTOM, before=frame2) frame3.grid_columnconfigure(0, weight=1) frame3.grid_columnconfigure(3, weight=1) quit_button = Button(frame3, text="Quit", command=self.quit) quit_button.grid(row=0, column=1) next_button = Button(frame3, text="Next", command=self.next) next_button.grid(row=0, column=2) def next(self): #TODO bawimy się w sprawdzanie danych?? data = dict() moves = self.entry_moves.get() moves = moves.split(',') for i in range(len(moves)): moves[i] = utils.order_from_char(moves[i]) data["moves"] = moves raw_table_input = self.text_table.get('0.1', END) raw_table_input = raw_table_input.splitlines() table_input = [None] * len(raw_table_input) for i in range(len(raw_table_input)): chars = raw_table_input[i].split(' ') table_input[i] = list() for j in range(len(chars)): table_input[i].append(int(chars[j])) data["table"] = Table(table_input) self.master.switch_frame(ViewPage, data)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("LabelFrame") self.pack(fill=BOTH, expand=True) labFrame = LabelFrame(self, text="Address") nameLbl = Label(labFrame, text="Street:") nameLbl.grid(row=0, column=0, padx=10, pady=10, sticky=E) self.streetEntry = Entry(labFrame) self.streetEntry.grid(row=0, column=1) addrLbl = Label(labFrame, text="Postal code:") addrLbl.grid(row=1, column=0, padx=10, sticky=E) self.postEntry = Entry(labFrame) self.postEntry.grid(row=1, column=1) labFrame.pack(anchor=N + W, ipadx=20, ipady=20, padx=15, pady=15) btn = Button(self, text="OK", command=self.buttonClick) btn.pack(pady=20) def buttonClick(self): print(self.streetEntry.get()) print(self.postEntry.get()) print(type(self.streetEntry.get())) print(type(self.postEntry.get()))
class HelpSource(Query): "Get menu name and help source for Help menu." # Used in ConfigDialog.HelpListItemAdd/Edit, (941/9) def __init__(self, parent, title, *, menuitem='', filepath='', used_names={}, _htest=False, _utest=False): """Get menu entry and url/local file for Additional Help. User enters a name for the Help resource and a web url or file name. The user can browse for the file. """ self.filepath = filepath message = 'Name for item on Help menu:' super().__init__( parent, title, message, text0=menuitem, used_names=used_names, _htest=_htest, _utest=_utest) def create_widgets(self): super().create_widgets() frame = self.frame pathlabel = Label(frame, anchor='w', justify='left', text='Help File Path: Enter URL or browse for file') self.pathvar = StringVar(self, self.filepath) self.path = Entry(frame, textvariable=self.pathvar, width=40) browse = Button(frame, text='Browse', width=8, command=self.browse_file) self.path_error = Label(frame, text=' ', foreground='red', font=self.error_font) pathlabel.grid(column=0, row=10, columnspan=3, padx=5, pady=[10,0], sticky=W) self.path.grid(column=0, row=11, columnspan=2, padx=5, sticky=W+E, pady=[10,0]) browse.grid(column=2, row=11, padx=5, sticky=W+S) self.path_error.grid(column=0, row=12, columnspan=3, padx=5, sticky=W+E) def askfilename(self, filetypes, initdir, initfile): # htest # # Extracted from browse_file so can mock for unittests. # Cannot unittest as cannot simulate button clicks. # Test by running htest, such as by running this file. return filedialog.Open(parent=self, filetypes=filetypes)\ .show(initialdir=initdir, initialfile=initfile) def browse_file(self): filetypes = [ ("HTML Files", "*.htm *.html", "TEXT"), ("PDF Files", "*.pdf", "TEXT"), ("Windows Help Files", "*.chm"), ("Text Files", "*.txt", "TEXT"), ("All Files", "*")] path = self.pathvar.get() if path: dir, base = os.path.split(path) else: base = None if platform[:3] == 'win': dir = os.path.join(os.path.dirname(executable), 'Doc') if not os.path.isdir(dir): dir = os.getcwd() else: dir = os.getcwd() file = self.askfilename(filetypes, dir, base) if file: self.pathvar.set(file) item_ok = SectionName.entry_ok # localize for test override def path_ok(self): "Simple validity check for menu file path" path = self.path.get().strip() if not path: #no path specified self.showerror('no help file path specified.', self.path_error) return None elif not path.startswith(('www.', 'http')): if path[:5] == 'file:': path = path[5:] if not os.path.exists(path): self.showerror('help file path does not exist.', self.path_error) return None if platform == 'darwin': # for Mac Safari path = "file://" + path return path def entry_ok(self): "Return apparently valid (name, path) or None" self.entry_error['text'] = '' self.path_error['text'] = '' name = self.item_ok() path = self.path_ok() return None if name is None or path is None else (name, path)
class ModelFrame(LabelFrame): topPadding = 12 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() def changeSelection(self): for widget in self.currentWidgets: widget.grid_remove() modelType = Model(self.selection.get()) sX = 10 bX = 20 if modelType == Model.EXP: self.expNumberOfSegments_L.grid(row=0,column=2,padx=(bX,sX),pady=(self.topPadding,5),sticky="W") self.expNumberOfSegments_E.grid(row=0,column=3,padx=(sX,bX),pady=(self.topPadding,5),sticky="W") self.currentWidgets = self.expWidgets elif modelType == Model.POW: self.powProximalLimit_L.grid(row=0,column=2,padx=(bX,sX),pady=(self.topPadding,5),sticky="W") self.powProximalLimit_E.grid(row=0,column=3,padx=(sX,bX),pady=(self.topPadding,5),sticky="W") self.powDistalLimit_L.grid(row=1,column=2,padx=(bX,sX),pady=5,sticky="W") self.powDistalLimit_E.grid(row=1,column=3,padx=(sX,bX),pady=5,sticky="W") self.currentWidgets = self.powWidgets elif modelType == Model.WEI: self.weiNumberOfRuns_L.grid(row=0,column=2,padx=(bX,sX),pady=(self.topPadding,5),sticky="W") self.weiNumberOfRuns_E.grid(row=0,column=3,padx=(sX,bX),pady=(self.topPadding,5),sticky="W") self.weiIterationsPerRun_L.grid(row=1,column=2,padx=(bX,sX),pady=5,sticky="W") self.weiIterationsPerRun_E.grid(row=1,column=3,padx=(sX,bX),pady=5,sticky="W") self.weiEstimatedTime_L.grid(row=2,column=2,padx=(bX,sX),pady=5,sticky="W") self.weiEstimatedTime_E.grid(row=2,column=3,padx=(sX,bX),pady=5,sticky="W") self.weiLambdaLowerBoundL.grid(row=0,column=4,padx=(bX,sX),pady=(self.topPadding,5),sticky="W") self.weiLambdaLowerBoundE.grid(row=0,column=5,padx=(sX,bX),pady=(self.topPadding,5)) self.weiLambdaUpperBoundL.grid(row=1,column=4,padx=(bX,sX),pady=5,sticky="W") self.weiLambdaUpperBoundE.grid(row=1,column=5,padx=(sX,bX),pady=5) self.weiKLowerBoundL.grid(row=0,column=6,padx=(bX,sX),pady=(self.topPadding,5),sticky="W") self.weiKLowerBoundE.grid(row=0,column=7,padx=(sX,sX),pady=(self.topPadding,5)) self.weiKUpperBoundL.grid(row=1,column=6,padx=(bX,sX),pady=5,sticky="W") self.weiKUpperBoundE.grid(row=1,column=7,padx=(sX,sX),pady=5) self.currentWidgets = self.weiWidgets def getModelDetails(self): modelType = Model(self.selection.get()) values = [modelType] if modelType == Model.EXP: numberOfSegments = helper_functions.validateValue( self.expNumberOfSegments_E.get(), "The number of exponential segments must be 1 \u2264 n \u2264 " + str(settings.EXP_MAX_NUMBER_OF_SEGMENTS), "int", lowerBound=1, upperBound=settings.EXP_MAX_NUMBER_OF_SEGMENTS) values.append(numberOfSegments) elif modelType == Model.POW: proximalLimitKM = helper_functions.validateValue( self.powProximalLimit_E.get(), "The proximal limit of integration must be 0 \u2264 x \u2264 \u221E", "float", strictLowerBound=0, strictUpperBound=float('inf')) proximalLimitKM /= SQRT_PI distalLimitKM = helper_functions.validateValue( self.powDistalLimit_E.get(), "The distal limit of integration must be prox \u2264 x \u2264 \u221E", "float", strictLowerBound=proximalLimitKM, strictUpperBound=float('inf')) distalLimitKM /= SQRT_PI values.extend([proximalLimitKM,distalLimitKM]) elif modelType == Model.WEI: numberOfRuns = helper_functions.validateValue( self.weiNumberOfRuns_E.get(), "The number of runs must be greater than 0", "int", strictLowerBound=0) iterationsPerRun = helper_functions.validateValue( self.weiIterationsPerRun_E.get(), "The number of iterations must be greater than 0", "int", strictLowerBound=0) lambdaLowerBound = helper_functions.validateValue( self.weiLambdaLowerBoundE.get(), "The lower bound for \u03BB must be a decimal", "float") lambdaUpperBound = helper_functions.validateValue( self.weiLambdaUpperBoundE.get(), "The upper bound for \u03BB must be greater than the lower bound", "float", strictLowerBound=lambdaLowerBound) kLowerBound = helper_functions.validateValue( self.weiKLowerBoundE.get(), "The lower bound for k must be numeric and less than 2", "float", strictUpperBound=2) kUpperBound = helper_functions.validateValue( self.weiKUpperBoundE.get(), "The upper bound for k must be greater than the lower bound and less than or equal to 2", "float", strictLowerBound=kLowerBound, upperBound=2) values.extend([numberOfRuns,iterationsPerRun,[[lambdaLowerBound,lambdaUpperBound],[kLowerBound,kUpperBound]]]) return values
class MarkovDemo(Frame): "MarkovDemo(master=None, **kw) -> MarkovDemo instance" TEXT = dict(height=2, width=46, wrap=WORD) # Text Options GRID = dict(padx=5, pady=5) # Grid Options # Initialize a MarkovDemo instance with a GUI for interaction. def __init__(self, master=None, **kw): "Initialize the MarkovDemo instance's widgets and settings." super().__init__(master, **kw) self.build_widgets() self.place_widgets() self.setup_widgets() self.grid_rowconfigure(2, weight=1) self.grid_rowconfigure(3, weight=1) self.grid_columnconfigure(0, weight=1) self.key = self.primer = None def build_widgets(self): "Build the various widgets that will be used in the program." # Create processing frame widgets. self.processing_frame = LabelFrame(self, text='Processing Mode:') self.mode_var = StringVar(self, 'encode') self.decode_button = Radiobutton(self.processing_frame, text='Decode Cipher-Text', command=self.handle_radiobuttons, value='decode', variable=self.mode_var) self.encode_button = Radiobutton(self.processing_frame, text='Encode Plain-Text', command=self.handle_radiobuttons, value='encode', variable=self.mode_var) self.freeze_var = BooleanVar(self, False) self.freeze_button = Checkbutton(self.processing_frame, text='Freeze Key & Primer', command=self.handle_checkbutton, offvalue=False, onvalue=True, variable=self.freeze_var) # Create encoding frame widgets. self.encoding_frame = LabelFrame(self, text='Encoding Options:') self.chain_size_label = Label(self.encoding_frame, text='Chain Size:') self.chain_size_entry = Entry(self.encoding_frame) self.plain_text_label = Label(self.encoding_frame, text='Plain-Text:') self.plain_text_entry = Entry(self.encoding_frame) # Create input frame widgets. self.input_frame = LabelFrame(self, text='Input Area:') self.input_text = ScrolledText(self.input_frame, **self.TEXT) # Create output frame widgets. self.output_frame = LabelFrame(self, text='Output Area:') self.output_text = ScrolledText(self.output_frame, **self.TEXT) def place_widgets(self): "Place the widgets where they belong in the MarkovDemo frame." # Locate processing frame widgets. self.processing_frame.grid(sticky=EW, **self.GRID) self.decode_button.grid(row=0, column=0, **self.GRID) self.encode_button.grid(row=0, column=1, **self.GRID) self.freeze_button.grid(row=0, column=2, **self.GRID) # Locate encoding frame widgets. self.encoding_frame.grid(sticky=EW, **self.GRID) self.chain_size_label.grid(row=0, column=0, sticky=W, **self.GRID) self.chain_size_entry.grid(row=0, column=1, sticky=EW, **self.GRID) self.plain_text_label.grid(row=1, column=0, sticky=W, **self.GRID) self.plain_text_entry.grid(row=1, column=1, sticky=EW, **self.GRID) self.encoding_frame.grid_columnconfigure(1, weight=1) # Locate input frame widgets. self.input_frame.grid(sticky=NSEW, **self.GRID) self.input_text.grid(sticky=NSEW, **self.GRID) self.input_frame.grid_rowconfigure(0, weight=1) self.input_frame.grid_columnconfigure(0, weight=1) # Locate output frame widgets. self.output_frame.grid(sticky=NSEW, **self.GRID) self.output_text.grid(sticky=NSEW, **self.GRID) self.output_frame.grid_rowconfigure(0, weight=1) self.output_frame.grid_columnconfigure(0, weight=1) def setup_widgets(self): "Setup each widget's configuration for the events they handle." self.input_text.bind('<Key>', self.handle_key_events) self.input_text.bind('<Control-Key-a>', self.handle_control_a) self.input_text.bind('<Control-Key-/>', lambda event: 'break') self.output_text['state'] = DISABLED self.output_text.bind('<Control-Key-a>', self.handle_control_a) self.output_text.bind('<Control-Key-/>', lambda event: 'break') ######################################################################## # Take care of any special event needing dedicated processing. def handle_radiobuttons(self): "Change the interface based on the encoding / decoding setting." if self.encrypting: self.freeze_button.grid() if not self.freeze_var.get(): self.encoding_frame.grid() else: self.freeze_button.grid_remove() if not self.freeze_var.get(): self.encoding_frame.grid_remove() self.handle_key_events(None) def handle_checkbutton(self): "Change the interface based on the key / primer freeze setting." if self.freeze_var.get(): self.encoding_frame.grid_remove() else: self.encoding_frame.grid() def handle_key_events(self, event): "Schedule refreshing the output area after an input area event." if event is None or event.char and event.state | 0o11 == 0o11: self.after_idle(self.refresh) @staticmethod def handle_control_a(event): "Select all text in the widget associated with the given event." event.widget.tag_add(SEL, 1.0, END + '-1c') return 'break' ######################################################################## # Handle interface's updates when either encoding or decoding. def refresh(self): "Refresh the output based on the value of the input." text = self.input_text.get(1.0, END + '-1c') if not text: self.output = text elif self.encrypting: self.encode(text) else: self.decode(text) def output(self, value): "Set the text in the output area to the string value." self.output_text['state'] = NORMAL self.output_text.delete(1.0, END) self.output_text.insert(END, value) if self.encrypting and self.freeze_var.get(): self.output_text.see(END) self.output_text['state'] = DISABLED output = property(fset=output, doc='Output area property.') @property def chain_size(self): "Chain size for the Markov chains used when encrypting." try: value = ast.literal_eval(self.chain_size_entry.get()) assert isinstance(value, int) and 2 <= value <= 256 return value except: self.chain_size_entry.delete(0, END) self.chain_size_entry.insert(0, '2') return 2 @property def plain_text(self): "Plain text or ignored characters in encryption process." try: value = self.repr_to_obj(self.plain_text_entry.get(), '') assert isinstance(value, str) return value except: self.plain_text_entry.delete(0, END) return '' ######################################################################## # Encrypt a string for display in the interface's output area. def encode(self, string): "Encode the string and show the cipher-text in the output." try: cipher = self.build_cipher(string) except ValueError: self.output = '' except: self.output = traceback.format_exc() else: self.output = self.build_header() + '\n\n' + cipher def build_cipher(self, string): "Build cipher-text based on plain-text and return answer." if self.key and self.freeze_var.get(): cipher, primer = me.encrypt_str(string, self.key, self.primer) else: args = string, self.chain_size, self.plain_text cipher, self.key, self.primer = me.auto_encrypt_str(*args) return cipher def build_header(self): "Build header from key and primer values in current use." header = '\n'.join(map(self.bytes_to_repr, self.key.data)) header += '\n' + self.bytes_to_repr(self.primer.data) return header ######################################################################## # Decrypt a string for display in the interface's output area. def decode(self, string): "Decode encrypted message and display plain-text in output." try: cipher = self.extract_keys(string) text = self.extract_text(cipher) except ValueError: self.output = '' except: self.output = traceback.format_exc() else: self.output = text def extract_keys(self, string): "Extract keys to decryption and return the cipher-text area." header, cipher = string.split('\n\n', 1) *key, primer = map(self.repr_to_obj, header.split('\n')) self.key, self.primer = me.Key(tuple(key)), me.Primer(primer) return cipher def extract_text(self, string): "Extract text message from string using built key and primer." text, primer = me.decrypt_str(string, self.key, self.primer) return text ######################################################################## # Provide some special methods to simplify the program's code. @property def encrypting(self): "Encrypting boolean stating current operations mode." return {'encode': True, 'decode': False}[self.mode_var.get()] @staticmethod def bytes_to_repr(obj): "Convert bytes object into suitable representation." if not isinstance(obj, bytes): raise TypeError('Object must be a bytes instance!') return repr(obj)[2:-1] @staticmethod def repr_to_obj(string, prefix='b'): "Convert representation into an equivalent object." for template in '{}"{}"', "{}'{}'": try: return ast.literal_eval(template.format(prefix, string)) except: pass raise ValueError('Cannot convert {!r} to object!'.format(string)) @classmethod def main(cls): "Create context for demo and run a test instance." NoDefaultRoot() root = Tk() root.minsize(420, 330) root.title('Markov Demo 2') test = cls(root) test.grid(sticky=NSEW) root.grid_rowconfigure(0, weight=1) root.grid_columnconfigure(0, weight=1) root.mainloop()
class Example(Frame): def __init__(self, parent, q): Frame.__init__(self, parent) self.queue = q self.parent = parent self.initUI() def initUI(self): self.parent.title("Pi computation") self.pack(fill=BOTH, expand=True) self.grid_columnconfigure(4, weight=1) self.grid_rowconfigure(3, weight=1) lbl1 = Label(self, text="Digits:") lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10) self.ent1 = Entry(self, width=10) self.ent1.insert(END, "4000") self.ent1.grid(row=0, column=1, sticky=W) lbl2 = Label(self, text="Accuracy:") lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10) self.ent2 = Entry(self, width=10) self.ent2.insert(END, "100") self.ent2.grid(row=0, column=3, sticky=W) self.startBtn = Button(self, text="Start", command=self.onStart) self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W) self.pbar = Progressbar(self, mode='indeterminate') self.pbar.grid(row=1, column=1, columnspan=3, sticky=W+E) self.txt = scrolledtext.ScrolledText(self) self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5, columnspan=5, sticky=E+W+S+N) def onStart(self): self.startBtn.config(state=DISABLED) self.txt.delete("1.0", END) self.digits = int(self.ent1.get()) self.accuracy = int(self.ent2.get()) self.p1 = Process(target=self.generatePi, args=(self.queue,)) self.p1.start() self.pbar.start(DELAY2) self.after(DELAY1, self.onGetValue) def onGetValue(self): if (self.p1.is_alive()): self.after(DELAY1, self.onGetValue) return else: try: self.txt.insert('end', self.queue.get(0)) self.txt.insert('end', "\n") self.pbar.stop() self.startBtn.config(state=NORMAL) except queue.Empty: print("queue is empty") def generatePi(self, queue): getcontext().prec = self.digits time.sleep(10) pi = Decimal(0) k = 0 n = self.accuracy while k < n: pi += (Decimal(1)/(16**k))*((Decimal(4)/(8*k+1)) - (Decimal(2)/(8*k+4)) - (Decimal(1)/(8*k+5)) - (Decimal(1)/(8*k+6))) k += 1 print(self.p1.is_alive()) queue.put(pi) print("end")
class HelpSource(Query): "Get menu name and help source for Help menu." # Used in ConfigDialog.HelpListItemAdd/Edit, (941/9) def __init__(self, parent, title, *, menuitem="", filepath="", used_names={}, _htest=False, _utest=False): """Get menu entry and url/local file for Additional Help. User enters a name for the Help resource and a web url or file name. The user can browse for the file. """ self.filepath = filepath message = "Name for item on Help menu:" super().__init__(parent, title, message, text0=menuitem, used_names=used_names, _htest=_htest, _utest=_utest) def create_widgets(self): super().create_widgets() frame = self.frame pathlabel = Label(frame, anchor="w", justify="left", text="Help File Path: Enter URL or browse for file") self.pathvar = StringVar(self, self.filepath) self.path = Entry(frame, textvariable=self.pathvar, width=40) browse = Button(frame, text="Browse", width=8, command=self.browse_file) pathlabel.pack(anchor="w", padx=5, pady=3) self.path.pack(anchor="w", padx=5, pady=3) browse.pack(pady=3) def askfilename(self, filetypes, initdir, initfile): # htest # # Extracted from browse_file so can mock for unittests. # Cannot unittest as cannot simulate button clicks. # Test by running htest, such as by running this file. return filedialog.Open(parent=self, filetypes=filetypes).show(initialdir=initdir, initialfile=initfile) def browse_file(self): filetypes = [ ("HTML Files", "*.htm *.html", "TEXT"), ("PDF Files", "*.pdf", "TEXT"), ("Windows Help Files", "*.chm"), ("Text Files", "*.txt", "TEXT"), ("All Files", "*"), ] path = self.pathvar.get() if path: dir, base = os.path.split(path) else: base = None if platform[:3] == "win": dir = os.path.join(os.path.dirname(executable), "Doc") if not os.path.isdir(dir): dir = os.getcwd() else: dir = os.getcwd() file = self.askfilename(filetypes, dir, base) if file: self.pathvar.set(file) item_ok = SectionName.entry_ok # localize for test override def path_ok(self): "Simple validity check for menu file path" path = self.path.get().strip() if not path: # no path specified showerror(title="File Path Error", message="No help file path specified.", parent=self) return None elif not path.startswith(("www.", "http")): if path[:5] == "file:": path = path[5:] if not os.path.exists(path): showerror(title="File Path Error", message="Help file path does not exist.", parent=self) return None if platform == "darwin": # for Mac Safari path = "file://" + path return path def entry_ok(self): "Return apparently valid (name, path) or None" name = self.item_ok() path = self.path_ok() return None if name is None or path is None else (name, path)
class Query(Toplevel): """Base class for getting verified answer from a user. For this base class, accept any non-blank string. """ def __init__(self, parent, title, message, *, text0='', used_names={}, _htest=False, _utest=False): """Create popup, do not return until tk widget destroyed. Additional subclass init must be done before calling this unless _utest=True is passed to suppress wait_window(). title - string, title of popup dialog message - string, informational message to display text0 - initial value for entry used_names - names already in use _htest - bool, change box location when running htest _utest - bool, leave window hidden and not modal """ Toplevel.__init__(self, parent) self.withdraw() # Hide while configuring, especially geometry. self.configure(borderwidth=5) self.resizable(height=False, width=False) self.title(title) self.transient(parent) self.grab_set() self.bind('<Key-Return>', self.ok) self.bind('<Key-Escape>', self.cancel) self.protocol("WM_DELETE_WINDOW", self.cancel) self.parent = parent self.message = message self.text0 = text0 self.used_names = used_names self.create_widgets() self.update_idletasks() # Needed here for winfo_reqwidth below. self.geometry( # Center dialog over parent (or below htest box). "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width()/2 - self.winfo_reqwidth()/2), parent.winfo_rooty() + ((parent.winfo_height()/2 - self.winfo_reqheight()/2) if not _htest else 150) ) ) if not _utest: self.deiconify() # Unhide now that geometry set. self.wait_window() def create_widgets(self): # Call from override, if any. # Bind to self widgets needed for entry_ok or unittest. self.frame = frame = Frame(self, borderwidth=2, relief='sunken', ) entrylabel = Label(frame, anchor='w', justify='left', text=self.message) self.entryvar = StringVar(self, self.text0) self.entry = Entry(frame, width=30, textvariable=self.entryvar) self.entry.focus_set() buttons = Frame(self) self.button_ok = Button(buttons, text='Ok', width=8, command=self.ok) self.button_cancel = Button(buttons, text='Cancel', width=8, command=self.cancel) frame.pack(side='top', expand=True, fill='both') entrylabel.pack(padx=5, pady=5) self.entry.pack(padx=5, pady=5) buttons.pack(side='bottom') self.button_ok.pack(side='left', padx=5) self.button_cancel.pack(side='right', padx=5) def entry_ok(self): # Example: usually replace. "Return non-blank entry or None." entry = self.entry.get().strip() if not entry: showerror(title='Entry Error', message='Blank line.', parent=self) return None return entry def ok(self, event=None): # Do not replace. '''If entry is valid, bind it to 'result' and destroy tk widget. Otherwise leave dialog open for user to correct entry or cancel. ''' entry = self.entry_ok() if entry is not None: self.result = entry self.destroy() else: # [Ok] moves focus. (<Return> does not.) Move it back. self.entry.focus_set() def cancel(self, event=None): # Do not replace. "Set dialog result to None and destroy tk widget." self.result = None self.destroy()
class Query(Toplevel): """Base class for getting verified answer from a user. For this base class, accept any non-blank string. """ def __init__(self, parent, title, message, *, text0='', used_names={}, _htest=False, _utest=False): """Create popup, do not return until tk widget destroyed. Additional subclass init must be done before calling this unless _utest=True is passed to suppress wait_window(). title - string, title of popup dialog message - string, informational message to display text0 - initial value for entry used_names - names already in use _htest - bool, change box location when running htest _utest - bool, leave window hidden and not modal """ Toplevel.__init__(self, parent) self.withdraw() # Hide while configuring, especially geometry. self.parent = parent self.title(title) self.message = message self.text0 = text0 self.used_names = used_names self.transient(parent) self.grab_set() windowingsystem = self.tk.call('tk', 'windowingsystem') if windowingsystem == 'aqua': try: self.tk.call('::tk::unsupported::MacWindowStyle', 'style', self._w, 'moveableModal', '') except: pass self.bind("<Command-.>", self.cancel) self.bind('<Key-Escape>', self.cancel) self.protocol("WM_DELETE_WINDOW", self.cancel) self.bind('<Key-Return>', self.ok) self.bind("<KP_Enter>", self.ok) self.resizable(height=False, width=False) self.create_widgets() self.update_idletasks() # Needed here for winfo_reqwidth below. self.geometry( # Center dialog over parent (or below htest box). "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width()/2 - self.winfo_reqwidth()/2), parent.winfo_rooty() + ((parent.winfo_height()/2 - self.winfo_reqheight()/2) if not _htest else 150) ) ) if not _utest: self.deiconify() # Unhide now that geometry set. self.wait_window() def create_widgets(self): # Call from override, if any. # Bind to self widgets needed for entry_ok or unittest. self.frame = frame = Frame(self, padding=10) frame.grid(column=0, row=0, sticky='news') frame.grid_columnconfigure(0, weight=1) entrylabel = Label(frame, anchor='w', justify='left', text=self.message) self.entryvar = StringVar(self, self.text0) self.entry = Entry(frame, width=30, textvariable=self.entryvar) self.entry.focus_set() self.error_font = Font(name='TkCaptionFont', exists=True, root=self.parent) self.entry_error = Label(frame, text=' ', foreground='red', font=self.error_font) self.button_ok = Button( frame, text='OK', default='active', command=self.ok) self.button_cancel = Button( frame, text='Cancel', command=self.cancel) entrylabel.grid(column=0, row=0, columnspan=3, padx=5, sticky=W) self.entry.grid(column=0, row=1, columnspan=3, padx=5, sticky=W+E, pady=[10,0]) self.entry_error.grid(column=0, row=2, columnspan=3, padx=5, sticky=W+E) self.button_ok.grid(column=1, row=99, padx=5) self.button_cancel.grid(column=2, row=99, padx=5) def showerror(self, message, widget=None): #self.bell(displayof=self) (widget or self.entry_error)['text'] = 'ERROR: ' + message def entry_ok(self): # Example: usually replace. "Return non-blank entry or None." self.entry_error['text'] = '' entry = self.entry.get().strip() if not entry: self.showerror('blank line.') return None return entry def ok(self, event=None): # Do not replace. '''If entry is valid, bind it to 'result' and destroy tk widget. Otherwise leave dialog open for user to correct entry or cancel. ''' entry = self.entry_ok() if entry is not None: self.result = entry self.destroy() else: # [Ok] moves focus. (<Return> does not.) Move it back. self.entry.focus_set() def cancel(self, event=None): # Do not replace. "Set dialog result to None and destroy tk widget." self.result = None self.destroy()
class Query(Toplevel): """Base class for getting verified answer from a user. For this base class, accept any non-blank string. """ def __init__(self, parent, title, message, *, _htest=False, _utest=False): # Call from override. """Create popup, do not return until tk widget destroyed. Additional subclass init must be done before calling this. title - string, title of popup dialog message - string, informational message to display _htest - bool, change box location when running htest _utest - bool, leave window hidden and not modal """ Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.resizable(height=FALSE, width=FALSE) self.title(title) self.transient(parent) self.grab_set() self.bind("<Key-Return>", self.ok) self.protocol("WM_DELETE_WINDOW", self.cancel) self.parent = parent self.message = message self.create_widgets() self.update_idletasks() # needs to be done here so that the winfo_reqwidth is valid self.withdraw() # Hide while configuring, especially geometry. self.geometry( "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width() / 2 - self.winfo_reqwidth() / 2), parent.winfo_rooty() + ((parent.winfo_height() / 2 - self.winfo_reqheight() / 2) if not _htest else 150), ) ) # centre dialog over parent (or below htest box) if not _utest: self.deiconify() # geometry set, unhide self.wait_window() def create_widgets(self): # Call from override, if any. frame = Frame(self, borderwidth=2, relief="sunken") label = Label(frame, anchor="w", justify="left", text=self.message) self.entry = Entry(frame, width=30) # Bind name for entry_ok. self.entry.focus_set() buttons = Frame(self) # Bind buttons for invoke in unittest. self.button_ok = Button(buttons, text="Ok", width=8, command=self.ok) self.button_cancel = Button(buttons, text="Cancel", width=8, command=self.cancel) frame.pack(side="top", expand=TRUE, fill="both") label.pack(padx=5, pady=5) self.entry.pack(padx=5, pady=5) buttons.pack(side="bottom") self.button_ok.pack(side="left", padx=5) self.button_cancel.pack(side="right", padx=5) def entry_ok(self): # Usually replace. "Check that entry not blank." entry = self.entry.get().strip() if not entry: showerror(title="Entry Error", message="Blank line.", parent=self) return entry def ok(self, event=None): # Do not replace. """If entry is valid, bind it to 'result' and destroy tk widget. Otherwise leave dialog open for user to correct entry or cancel. """ entry = self.entry_ok() if entry: self.result = entry self.destroy() else: # [Ok] (but not <Return>) moves focus. Move it back. self.entry.focus_set() def cancel(self, event=None): # Do not replace. "Set dialog result to None and destroy tk widget." self.result = None self.destroy()
class BookManagerUi(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.db = dao('blist') #데이터베이스 관리 클래스 생성 def initUI(self): self.parent.title("Book Manager") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.columnconfigure(0, pad=3) self.columnconfigure(1, pad=3) self.columnconfigure(2, pad=3) self.rowconfigure(0, pad=3) self.rowconfigure(1, pad=3) self.rowconfigure(2, pad=3) self.rowconfigure(3, pad=3) self.rowconfigure(4, pad=3) self.rowconfigure(5, pad=3) self.rowconfigure(6, pad=3) self.input_bname='' self.input_aname='' self.input_price=0 self.delete='' lb_bookname = Label(self, text="bookname:") lb_bookname.grid(row=0, column =0 ,sticky=W, pady=4, padx=5) self.entry_bookname = Entry(self) self.entry_bookname.grid(row=0, column = 1 ) lb_author = Label(self, text="author:") lb_author.grid(row=0, column =2,sticky=W, pady=4, padx=5) self.entry_author = Entry(self) self.entry_author.grid(row=0, column = 3 ) lb_price = Label(self, text="price:") lb_price.grid(row=0, column =4 ,sticky=W, pady=4, padx=5) self.entry_price = Entry(self) self.entry_price.grid(row=0, column = 5 ,padx=15) abtn = Button(self, text="Add", command=lambda:self.clicked_add()) abtn.grid(row=0, column=6) sbtn = Button(self, text="Serach", command = lambda:self.clicked_search()) sbtn.grid(row=1, column=6, pady=4) dbtn = Button(self, text="Delete", command = lambda:self.clicked_delete()) dbtn.grid(row=2, column=6, pady=4) self.lb = Listbox(self) self.lb.grid(row=3,column = 0, columnspan = 6,rowspan= 4, sticky = E+W+S+N) self.lb.bind("<<ListboxSelect>>", self.onSelect) #삭제를 위한 select부분 def onSelect(self,val): sender = val.widget idx = sender.curselection() value = sender.get(idx) self.delete = value # 데이터 추가 버튼 def clicked_add(self): bname =self.entry_bookname.get() aname = self.entry_author.get() price = self.entry_price.get() self.lb.delete(0,END) # 입력받을 데이터가 모자란지 검사 if(len(bname) >0 and len(aname)>0 and len(price)>0 ): #가격에 문자를 입력했을 경우 처리 try: priceI = eval(price) except: self.lb.insert(END,"you input wrong price. it must be integer") #사용자가 입력한 내용중 중복된 책이름이 있을 경우(저자는 책이 여러가지일 수 있으니 제외) rec = self.db.excute_select(bname,'') if ( len(rec) >0): self.lb.insert(END,bname +" is already in the database") else: self.db.insert_data(bname,aname,priceI) # 모든 조건 만족시 데이터 입력 수행 r =self.db.excute_select(bname,aname) for rs in r: self.lb.insert(END,str(rs)) else: s = StringVar() self.entry_price.config(textvariable = s) self.lb.insert(END,"you have to input more values") #검색버튼 def clicked_search(self): bname =self.entry_bookname.get() aname = self.entry_author.get() self.lb.delete(0,END) #책이름 또는 저자이름 둘중 하나만입력 되어도 검색 가능하도록 if(len(bname)>0 or len(aname)>0 ): rec = self.db.excute_select(bname,aname) for r in rec: self.lb.insert(END,str(r)) else: self.lb.insert(END,"you have to input more values(bookname or author") #삭제 버튼 def clicked_delete(self): self.lb.delete(0,END) q = self.db.excute_delete(self.delete) self.lb.insert(END,q+' is delete from database')
class CreateCustomer(Frame): """Create customer screen""" def __init__(self, master): Frame.__init__(self,master) self.master = master self.frame = Frame(self.master) self.initUI() def initUI(self): self.master.title("3D Printer - Add Customer") self.style = Style() default_padding = {'padx': 10, 'pady' : 10} #TODO change alignment #Left frame for labels self.left_frame = Frame(self.master) self.name_label = Label(self.left_frame, text = "Name", style="BW.TLabel") self.name_label.pack(default_padding) self.surname_label = Label(self.left_frame, text = "Surname", style="BW.TLabel") self.surname_label.pack(default_padding) self.email_label = Label(self.left_frame, text = "Email", style="BW.TLabel") self.email_label.pack(default_padding) self.cellphone_label = Label(self.left_frame, text = "Cellphone", style="BW.TLabel") self.cellphone_label.pack(default_padding) #Right frame for entries self.right_frame = Frame(self.master) self.name_entry = Entry(self.right_frame) self.name_entry.pack(default_padding) self.surname_entry = Entry(self.right_frame) self.surname_entry.pack(default_padding) self.email_entry = Entry(self.right_frame) self.email_entry.pack(default_padding) self.cellphone_entry = Entry(self.right_frame) self.cellphone_entry.pack(default_padding) #Bottom frame for button self.button_frame = Frame(self.master) self.create_customer_button = Button(self.button_frame, text = "Create Customer", command = self.save_customer) self.create_customer_button.pack(default_padding) self.button_frame.pack(side = BOTTOM, fill = "x", expand = True) self.left_frame.pack(side = LEFT, expand = True, fill = "y") self.right_frame.pack(side = RIGHT, expand = True, fill = "y") self.frame.pack() def save_customer(self): print("saving customer") self.customer = Customer(self.name_entry.get(), self.surname_entry.get(), self.email_entry.get(), self.cellphone_entry.get()) if not self.customer.validate(): messagebox.showerror(message = "All fields are mandatory, please fill in all the fields") return db = TinyDB('db/db.json') self.customer_id = db.insert(self.customer.__dict__) #TODO redirect to next page self.go_to_execute_script() def go_to_execute_script(self): """redirect to next page""" self.execute_script = Toplevel(self, self.master) self.app = ExecuteScript(self.execute_script)