def __init__(self, theme="arc"): """ :param theme: Theme to show off """ ThemedTk.__init__(self) self.set_theme(theme) # Create widgets self.label = ttk.Label(self, text="This is an example label.") self.dropdown = ttk.OptionMenu(self, tk.StringVar(), "First value") self.entry = ttk.Entry( self, textvariable=tk.StringVar(value="Default entry value.")) self.button = ttk.Button(self, text="Button") self.radio_one = ttk.Radiobutton(self, text="Radio one") self.radio_two = ttk.Radiobutton(self, text="Radio two") self.scroll = ttk.Scrollbar(self, orient=tk.VERTICAL) self.checked = ttk.Checkbutton(self, text="Checked", variable=tk.BooleanVar(value=True)) self.unchecked = ttk.Checkbutton(self, text="Unchecked") self.tree = ttk.Treeview(self, height=4, show=("tree", )) self.setup_tree() self.scale_entry = ScaleEntry(self, from_=0, to=50, orient=tk.HORIZONTAL, compound=tk.RIGHT) self.combo = AutocompleteCombobox( self, completevalues=["something", "something else"]) # Grid widgets self.grid_widgets() # Bind screenshot button self.bind("<F10>", self.screenshot)
def __init__(self, master=None, callback=None, **kwargs): """ :param master: master widget :param callback: callable object with single argument: font family name :param kwargs: keyword arguments passed on to AutocompleteCombobox initializer """ font_families = sorted([item for item in font.families()]) self._fonts = font_families self._font = tk.StringVar(master) self.__callback = callback AutocompleteCombobox.__init__(self, master, textvariable=self._font, completevalues=font_families, **kwargs) self.bind("<<ComboboxSelected>>", self._on_select)
def __init__(self, master=None, callback=None, **kwargs): """ Create a FontFamilyDropdown. :param master: master widget :type master: widget :param callback: callable object with single argument: font family name :type callback: function :param kwargs: keyword arguments passed on to the :class:`~ttkwidgets.autocomplete.AutocompleteCombobox` initializer """ font_families = sorted(set(font.families())) self._fonts = font_families self._font = tk.StringVar(master) self.__callback = callback AutocompleteCombobox.__init__(self, master, textvariable=self._font, completevalues=font_families, **kwargs) self.bind("<<ComboboxSelected>>", self._on_select) self.bind("<Return>", self._on_select)
def __init__(self, master=None, callback=None, **kwargs): """ :param master: master widget :param callback: callback on click with signle argument: int size :param kwargs: keyword arguments passed on to AutocompleteCombobox initializer """ int_values = [ 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72 ] values = [str(value) for value in int_values] AutocompleteCombobox.__init__(self, master, completevalues=values, **kwargs) self.bind("<<ComboboxSelected>>", self._on_click) self.__callback = callback self.insert(0, "12")
def __init__(self, theme="arc"): """ :param theme: Theme to show off """ ThemedTk.__init__(self, fonts=True, themebg=True) self.set_theme(theme) # Create widgets self.notebook = ttk.Notebook(self) self.notebook.add(ttk.Button(self, text="Hello World"), text="Frame One") self.notebook.add(ttk.Button(self, text="Hello Universe"), text="Frame Two") self.menu = tk.Menu(self, tearoff=False) self.sub_menu = tk.Menu(self.menu, tearoff=False) self.sub_menu.add_command(label="Exit", command=self.destroy) self.menu.add_cascade(menu=self.sub_menu, label="General") self.config(menu=self.menu) self.label = ttk.Label(self, text="This is an example label.") self.dropdown = ttk.OptionMenu(self, tk.StringVar(), "First value", "Second Value") self.entry = ttk.Entry( self, textvariable=tk.StringVar(value="Default entry value.")) self.button = ttk.Button(self, text="Button") self.radio_one = ttk.Radiobutton(self, text="Radio one", value=True) self.radio_two = ttk.Radiobutton(self, text="Radio two", value=False) self.scroll = ttk.Scrollbar(self, orient=tk.VERTICAL) self.checked = ttk.Checkbutton(self, text="Checked", variable=tk.BooleanVar(value=True)) self.unchecked = ttk.Checkbutton(self, text="Unchecked") self.tree = ttk.Treeview(self, height=4, show=("tree", "headings")) self.setup_tree() self.scale_entry = ScaleEntry(self, from_=0, to=50, orient=tk.HORIZONTAL, compound=tk.RIGHT) self.combo = AutocompleteCombobox( self, completevalues=["something", "something else"]) self.progress = ttk.Progressbar(self, maximum=100, value=50) # Grid widgets self.grid_widgets() # Bind screenshot button self.bind("<F10>", self.screenshot) self.bind("<F9>", self.screenshot_themes)
def __init__(self, master, **kwargs): self._textv = StringVar() super().__init__(tk=AutocompleteCombobox(master=master, textvariable=self._textv), **kwargs) self._setter = self.connect_to_prop("value", self.on_changed_value) self._trace = self._textv.trace_add( "write", lambda *_: self._setter(self._textv.get())) self.connect_to_prop("suggestion", self.on_changed_suggestion)
def __init__(self, master, **kwargs): self._onlydir = False self._ext = ('Any File', '.*') self._rootdir = None self._excludefiles = [] self._suggestions = [] self._file_suggestions = None self._textv = StringVar() self._box = ttk.Frame(master=master) self._box.grid_columnconfigure(0, weight=1) self._box.grid_columnconfigure(1, weight=0) self._box.grid_rowconfigure(0, weight=1) self._input = AutocompleteCombobox( master=self._box, completevalues=[], textvariable=self._textv ) # Redirect configure to input setattr(self._box, "config", self._input.config) setattr(self._box, "configure", self._input.configure) setattr(self._box, "keys", self._input.keys) setattr(self._box, "cget", self._input.cget) setattr(self._box, "winfo_class", self._input.winfo_class) setattr(self._box, "bind", self._input.bind) setattr(self._box, "set_completion_list", self._input.set_completion_list) super().__init__(tk=self._box, **kwargs) self.connect_to_prop("onlydir", self._on_onlydir_changed) self.connect_to_prop("ext", self._on_ext_changed) self.connect_to_prop("rootdir", self._on_rootdir_changed) self.connect_to_prop("excludefiles", self._on_excludefiles_changed) #self.connect_to_prop("suggestion", self.on_changed_suggestion) self._input.drop_target_register(DND_FILES) self._input.dnd_bind('<<Drop>>', self._drop) self._input.grid(row=0, column=0, sticky="news") self._btn = ttk.Button(master=self._box, command=self._load_file, text="Browse...") self._btn.grid(row=0, column=1)
def __init__(self, root): self.root = root self.root.title("Programa base de datos Anla") self.canvas = tk.Canvas(self.root, height = 400, width =700) self.canvas.pack() self.imagen_fondo = PhotoImage(file='fondo.png') self.frame = tk.Frame(self.root, bg = None ) #"#20CDC8" self.frame.place(relheight = 1, relwidth= 1) self.imagen_Label = tk.Label(self.frame, image= self.imagen_fondo) self.imagen_Label.place(relheight = 1, relwidth= 1) #self.desplegable = ttk.Combobox(self.frame, height = 10, textvariable = StringVar, values = self.combo()) #self.desplegable.place(relheight = 0.05, relwidth = 0.65, relx = 0.2, rely = 0.08) self.autocompletar = AutocompleteCombobox(self.frame, completevalues = self.combo()) self.autocompletar.place(relheight = 0.05, relwidth = 0.65, relx = 0.2, rely = 0.08) self.boton = tk.Button(self.frame, text = "Agregar Componente", bg = "#4CE37C", bd = 0.5, command = self.adicionar_componentes) self.boton.place(relheight = 0.07, relwidth = 0.18, relx = 0.018, rely = 0.08) #self.new_frame = tk.Frame(self.frame, bd = 2, bg = "white") #self.new_frame.place(relheight = 0.65, relwidth = 0.7, relx = 0.15, rely = 0.3) self.style = ttk.Style() self.style.configure("Treeview.Heading", font=("Helvetica", 12, "bold")) self.arbol = ttk.Treeview(self.frame, height = 5) self.arbol.place(relheight = 0.65, relwidth = 0.7, relx = 0.15, rely = 0.25) self.arbol.heading('#0', text = 'COMPONENTES SELECCIONADOS', anchor = CENTER) self.fuente = font.Font(family='Helvetica', size=10, weight='bold') self.boton_delete = tk.Button(self.frame, text = "Eliminar componente", command = self.eliminar_seleccion) self.boton_delete.place(relheight = 0.07, relwidth = 0.18) self.boton_delete_all = tk.Button(self.frame, text = "Eliminar todo", command = self.eliminar_todo) self.boton_delete_all.place(relheight = 0.07, relwidth = 0.18, relx = 0.5, rely = 0.5) self.mensaje = tk.Label(self.frame, text = "", anchor = "center", font = self.fuente, bg = "#20CDC8" ) self.mensaje.place(relx = 0.2, rely = 0.15)
def __init__(self, master=None, async_loop=None): tk.Frame.__init__(self, master) self.async_loop = async_loop # basics # master.resizable(width=True, height=True) master.title( "Isogeo Python SDK v{} - Sample desktop search form".format(pysdk_version) ) master.focus_force() self.grid(sticky="NSWE") self.grid_propagate(1) # styling self.style = ttk.Style(self) self.s1 = tk.PhotoImage( master=self, name="search1", data=data, format="gif -index 0" ) self.s2 = tk.PhotoImage( master=self, name="search2", data=data, format="gif -index 1" ) self.style.element_create( "Search.field", "image", "search1", ("focus", "search2"), border=[22, 7, 14], sticky="ew", ) self.style.layout( "Search.entry", [ ( "Search.field", { "sticky": "nswe", "border": 1, "children": [ ( "Entry.padding", { "sticky": "nswe", "children": [ ("Entry.textarea", {"sticky": "nswe"}) ], }, ) ], }, ) ], ) self.style.configure("Search.entry") # frames fr_global = ttk.Frame(self, name="global") fr_search = ttk.Frame(self, name="search_form") # UI vars self.app_name = StringVar(fr_global, "Sample desktop form") self.app_total = StringVar(fr_global, "0") self.app_url = StringVar(fr_global, "http://isogeo-api-pysdk.readthedocs.io") self.app_results = StringVar(fr_search, "0") # -- WIDGETS CREATION ------------------------------------------------- # add widgets lbl_app_name = tk.Label(fr_global, textvariable=self.app_name) lbl_app_total = ttk.Label(fr_global, textvariable=self.app_total) btn_app_url = ttk.Button( fr_global, text="APP Website", command=lambda: self.worker_allocator( async_loop=self.async_loop, to_do="open_web", **{"url": self.app_url} ), ) lbl_actions = ttk.Label(fr_search, text="Linked action") lbl_contacts = ttk.Label(fr_search, text="Contact") lbl_formats = ttk.Label(fr_search, text="Source format") lbl_inspires = ttk.Label(fr_search, text="INSPIRE theme") lbl_keywords = ttk.Label(fr_search, text="Keyword") lbl_licenses = ttk.Label(fr_search, text="License") lbl_owners = ttk.Label(fr_search, text="Owner") lbl_shares = ttk.Label(fr_search, text="Share") lbl_srs = ttk.Label(fr_search, text="Source spatial reference system") lbl_types = ttk.Label(fr_search, text="Type") # add form widgets self.ent_search = AutocompleteEntry( fr_search, style="Search.entry", width=20, completevalues=list() ) self.cb_actions = AutocompleteCombobox(fr_search) self.cb_contacts = AutocompleteCombobox(fr_search) self.cb_formats = AutocompleteCombobox(fr_search) self.cb_inspires = AutocompleteCombobox(fr_search) self.cb_keywords = AutocompleteCombobox(fr_search) self.cb_licenses = AutocompleteCombobox(fr_search) self.cb_owners = AutocompleteCombobox(fr_search) self.cb_shares = AutocompleteCombobox(fr_search) self.cb_srs = AutocompleteCombobox(fr_search) self.cb_types = AutocompleteCombobox(fr_search) lbl_results = ttk.Label(fr_search, textvariable=self.app_results) btn_reset = ttk.Button( master, text="Reset", command=lambda: self.worker_allocator( async_loop=self.async_loop, to_do="form_clear", **{"clear": 1} ), ) btn_close = ttk.Button(master, text="Close", command=master.destroy) # after UI build self.worker_allocator( async_loop=self.async_loop, to_do="form_clear", **{"clear": 1} ) # -- WIDGETS PLACEMENT ------------------------------------------------ d_pad = {"padx": 5, "pady": 5, "sticky": "NSEW"} lbl_app_name.grid(row=0, column=0, **d_pad) btn_app_url.grid(row=1, column=0, **d_pad) lbl_app_total.grid(row=2, column=0, **d_pad) self.ent_search.grid(row=1, columnspan=3, **d_pad) self.cb_actions.grid(row=3, column=0, **d_pad) self.cb_contacts.grid(row=3, column=1, **d_pad) self.cb_formats.grid(row=3, column=2, **d_pad) self.cb_inspires.grid(row=5, column=0, **d_pad) self.cb_keywords.grid(row=5, column=1, **d_pad) self.cb_licenses.grid(row=5, column=2, **d_pad) self.cb_owners.grid(row=7, column=0, **d_pad) self.cb_shares.grid(row=7, column=1, **d_pad) self.cb_srs.grid(row=7, column=2, **d_pad) self.cb_types.grid(row=9, column=1, **d_pad) lbl_actions.grid(row=2, column=0, **d_pad) lbl_contacts.grid(row=2, column=1, **d_pad) lbl_formats.grid(row=2, column=2, **d_pad) lbl_inspires.grid(row=4, column=0, **d_pad) lbl_keywords.grid(row=4, column=1, **d_pad) lbl_licenses.grid(row=4, column=2, **d_pad) lbl_owners.grid(row=6, column=0, **d_pad) lbl_shares.grid(row=6, column=1, **d_pad) lbl_srs.grid(row=6, column=2, **d_pad) lbl_types.grid(row=8, column=1, **d_pad) lbl_results.grid(row=22, column=0, columnspan=2, **d_pad) fr_global.grid(row=0, columnspan=1, **d_pad) fr_search.grid(row=1, columnspan=1, **d_pad) btn_reset.grid(row=2, column=0, sticky="NSW", padx=5, pady=5) btn_close.grid(row=2, column=0, sticky="NSE", padx=5, pady=5) # connecting comboboxes event self.cb_actions.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_contacts.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_formats.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_inspires.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_keywords.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_licenses.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_owners.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_shares.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_srs.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_types.bind("<<ComboboxSelected>>", self.cbs_manager)
def test_autocompletecombobox(self): box = AutocompleteCombobox(self.window, completevalues=["Apple", "Pear", "Banana"]) box.pack() self.window.update() self.assertIn('completevalues', box.keys()) self.assertEqual(box['completevalues'], sorted(["Apple", "Pear", "Banana"])) box.insert(0, "A") self.window.update() for item in ["A", "Up", "Down", "Left", "Right", "Return"]: box.handle_keyrelease(TestEvent(item)) box.autocomplete(0) box.set_completion_list(["Apply"]) self.assertEqual(box['completevalues'], ["Apply"]) box['completevalues'] = ["Test"] self.assertEqual(box['completevalues'], ["Test"])
def __init__(self, restart_var, session): tk.Tk.__init__(self) self.restart_var = restart_var self.session = session self.window_config = { "title": "IGuard Desktop Admin", "cam-nav-text": "Cameras", "user-nav-text": "Users", "filter-btn-text": "Search", "filter-reset-btn-text": "Show All", "filter-label": 'Select User:'******'#cfebff', 'white', '#3A79D1', text=self.window_config['cam-nav-text'], font="Arial 15", height=3) self.camBtn.bind("<Button-1>", lambda e: self.showCameras()) self.camBtn.pack(side=tk.LEFT, fill='both', expand=True) self.usersBtn = ClickableLabel( self.navbar, '#cfebff', 'white', '#3A79D1', text=self.window_config['user-nav-text'], font="Arial 15", height=3) self.usersBtn.bind("<Button-1>", lambda e: self.showUsers()) self.usersBtn.pack(side=tk.RIGHT, fill='both', expand=True) self.camBtn.click() self.protocol("WM_DELETE_WINDOW", self.logOut) self.cam_frame = CamerasFrame(self) self.cam_frame.pack(side=tk.TOP, fill='both', expand=True) self.users_frame = UsersList( self, bg='#3A79D1', list_of_users=self.cam_frame.list_of_users, list_of_ids=self.cam_frame.list_of_ids, session=self.session) self.filter_frame = tk.Frame(self, bg='white') self.filter_frame.pack(side=tk.BOTTOM, fill=tk.X) tk.Label(self.filter_frame, text=self.window_config['filter-label'], bg='white', font='Arial 11').pack(side=tk.LEFT, fill=tk.Y, pady=10) self.filter_user_combobox = AutocompleteCombobox( self.filter_frame, completevalues=self.cam_frame.list_of_users) self.filter_user_combobox.pack(side=tk.LEFT, fill=tk.Y, pady=10, padx=10) self.filter_button = FocusButton( self.filter_frame, in_color='#325080', out_color='#3A79D1', text=self.window_config['filter-btn-text'], command=self.filterByUser, fg='white', relief=tk.FLAT) self.filter_button.pack(side=tk.LEFT, fill=tk.Y, pady=10, padx=10) self.filter_reset_button = FocusButton( self.filter_frame, in_color='#325080', out_color='#3A79D1', text=self.window_config['filter-reset-btn-text'], command=self.resetFilter, fg='white', relief=tk.FLAT) self.filter_reset_button.pack(side=tk.LEFT, fill=tk.Y, pady=10, padx=10)
class Interfaz(object): def __init__(self, root): self.root = root self.root.title("Programa base de datos Anla") self.canvas = tk.Canvas(self.root, height = 400, width =700) self.canvas.pack() self.imagen_fondo = PhotoImage(file='fondo.png') self.frame = tk.Frame(self.root, bg = None ) #"#20CDC8" self.frame.place(relheight = 1, relwidth= 1) self.imagen_Label = tk.Label(self.frame, image= self.imagen_fondo) self.imagen_Label.place(relheight = 1, relwidth= 1) #self.desplegable = ttk.Combobox(self.frame, height = 10, textvariable = StringVar, values = self.combo()) #self.desplegable.place(relheight = 0.05, relwidth = 0.65, relx = 0.2, rely = 0.08) self.autocompletar = AutocompleteCombobox(self.frame, completevalues = self.combo()) self.autocompletar.place(relheight = 0.05, relwidth = 0.65, relx = 0.2, rely = 0.08) self.boton = tk.Button(self.frame, text = "Agregar Componente", bg = "#4CE37C", bd = 0.5, command = self.adicionar_componentes) self.boton.place(relheight = 0.07, relwidth = 0.18, relx = 0.018, rely = 0.08) #self.new_frame = tk.Frame(self.frame, bd = 2, bg = "white") #self.new_frame.place(relheight = 0.65, relwidth = 0.7, relx = 0.15, rely = 0.3) self.style = ttk.Style() self.style.configure("Treeview.Heading", font=("Helvetica", 12, "bold")) self.arbol = ttk.Treeview(self.frame, height = 5) self.arbol.place(relheight = 0.65, relwidth = 0.7, relx = 0.15, rely = 0.25) self.arbol.heading('#0', text = 'COMPONENTES SELECCIONADOS', anchor = CENTER) self.fuente = font.Font(family='Helvetica', size=10, weight='bold') self.boton_delete = tk.Button(self.frame, text = "Eliminar componente", command = self.eliminar_seleccion) self.boton_delete.place(relheight = 0.07, relwidth = 0.18) self.boton_delete_all = tk.Button(self.frame, text = "Eliminar todo", command = self.eliminar_todo) self.boton_delete_all.place(relheight = 0.07, relwidth = 0.18, relx = 0.5, rely = 0.5) self.mensaje = tk.Label(self.frame, text = "", anchor = "center", font = self.fuente, bg = "#20CDC8" ) self.mensaje.place(relx = 0.2, rely = 0.15) def combo(self): conn = sqlite3.connect("anla.db") c = conn.cursor() lista_nueva = c.execute("SELECT DISTINCT COMPONENTE FROM diccionario_nuevo WHERE CÓDIGO != 'T' ORDER BY COMPONENTE") vacio = [] for componente in lista_nueva: vacio.append(componente[0]) return vacio def adicionar_componentes(self): add = self.autocompletar.get() if add not in self.combo(): self.mensaje = tk.Label(self.frame, text = "", anchor = "center", font = self.fuente, bg = "#20CDC8" ) self.mensaje["text"] = "{} no es un componente".format(add) self.mensaje.place(relx = 0.2, rely = 0.15) return self.mensaje else: return self.arbol.insert('', 0, text = add, value = ""), self.mensaje.destroy() def eliminar_seleccion(self): selected_item = self.arbol.selection() try: self.arbol.delete(selected_item) self.mensaje_seleccion.destroy() except: self.mensaje_seleccion = tk.Label(self.frame, text = "Seleccione un componente", font = self.fuente) self.mensaje_seleccion.place(relx = 0.8, rely = 0.9, anchor = "se") def eliminar_todo(self): for componente in self.arbol.get_children(): eliminar = self.arbol.delete(componente) return eliminar def otra_cosa(self): self.otra_ventana = Toplevel() self.otra_ventana.title("Resultados") self.otro_canvas = Canvas(self.otra_ventana, height = 400, width =700) self.otro_canvas.pack() self.imagen_otro = PhotoImage(file='cielo.png') self.imagen_Label_otro = tk.Label(self.otra_ventana, image= self.imagen_otro) self.imagen_Label_otro.place(relheight = 1, relwidth= 1) conn = sqlite3.connect("anla.db") c = conn.cursor() for componente in self.arbol.get_children(): c_individual = self.arbol.item(componente)["text"] if c_individual == "ANALISIS_RIESGO": anali_riesgo = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'ANALISIS_RIESGO' ") print(anali_riesgo) elif c_individual == "AREAS_CONSER_PROTEC_AMBIENTAL": area_conservacion = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'AREAS_CONSER_PROTEC_AMBIENTAL'") print(area_conservacion) elif c_individual == "AREAS_REGLAMENTACION_ESPECIAL": areas_reglamentacion = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'AREAS_REGLAMENTACION_ESPECIAL'") print(areas_reglamentacion) elif c_individual == "ARQUEOLOGIA": arqueologia = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'ARQUEOLOGIA'") print(arqueologia) elif c_individual == "ATMOSFERA": atmosfera = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'ATMOSFERA' OR Medio = 'ATMOSFERA'") print(atmosfera) elif c_individual == "BIOTICO_CONTI_COSTE": biotico = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'BIOTICO_CONTI_COSTE' or Medio = 'BIOTICO_CONTI_COSTE'") print(biotico) elif c_individual == "CLIMA": clima = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'CLIMA' or Medio = 'CLIMA'") print(clima) elif c_individual == "COMPENSACION": compensacion = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'COMPENSACION' OR Medio = 'COMPENSACION'") print(compensacion) elif c_individual == "CONTINGENCIAS": contingencias = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'CONTINGENCIAS' OR Medio = 'CONTINGENCIAS'") print(contingencias) elif c_individual == "ECONOMICO": economico = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'ECONOMICO'") print(economico) elif c_individual == "GEOLOGIA": geologia = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'GEOLOGIA' OR Medio = 'GEOLOGIA'") print(geologia) elif c_individual == "GEOMORFOLOGIA": geomorfologia = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'GEOMORFOLOGIA'") print(geomorfologia) elif c_individual == "GEOTECNIA": geotecnia = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'GEOTECNIA'") print(geotecnia) elif c_individual == "GESTION_RIESGO": gestion_riesgo = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'GESTION_RIESGO'") print(gestion_riesgo) elif c_individual == "HIDROGEOLOGIA": hidrogeologia = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'HIDROGEOLOGIA' OR Medio = 'HIDROGEOLOGIA'") print(hidrogeologia) elif c_individual == "HIDROLOGIA": hidrologia = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'HIDROLOGIA' OR Medio = 'HIDROLOGIA'") print(hidrologia) elif c_individual == "INVERSION_1_POR_CIENTO": inversion1 = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'INVERSION_1_POR_CIENTO' OR Medio = 'INVERSION_1_POR_CIENTO'") print(inversion1) elif c_individual == "MARINO": marino = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'MARINO' OR Medio = 'MARINO'") print(marino) elif c_individual == "PAISAJE": paisaje = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'PAISAJE'") elif c_individual == "POLITICO_ADMINISTRATIVO": politico = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'POLITICO_ADMINISTRATIVO' Medio = 'POLITICO_ADMINISTRATIVO'") print(politico) elif c_individual == "PROYECTO": proyecto = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'PROYECTO' OR Medio = 'PROYECTO'") print(proyecto) elif c_individual == "SOCIOCULTURAL": sociocultural = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'SOCIOCULTURAL'") print(sociocultural) elif c_individual == "SUELOS": suelos = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'SUELOS' OR Medio = 'SUELOS'") print(suelos) elif c_individual == "ZONIFICACION": zonificacion = c.execute("SELECT DISTINCT CAPAS, CÓDIGO FROM diccionario_nuevo WHERE COMPONENTE = 'ZONIFICACION'") print(zonificacion) else: pass
class Example(ThemedTk): """ Example that is used to create screenshots for new themes. """ def __init__(self): ThemedTk.__init__(self, themebg=True) # Create widgets self.menu = tk.Menu(self, tearoff=False) self.sub_menu = tk.Menu(self.menu, tearoff=False) self.sub_menu.add_command(label="Exit", command=self.destroy) self.menu.add_cascade(menu=self.sub_menu, label="General") self.config(menu=self.menu) self.label = ttk.Label(self, text="This is an example label.") self.dropdown = ttk.OptionMenu(self, tk.StringVar(), "First value", "Second Value") self.entry = ttk.Entry( self, textvariable=tk.StringVar(value="Default entry value.")) self.button = ttk.Button(self, text="Button") self.radio_one = ttk.Radiobutton(self, text="Radio one", value=True) self.radio_two = ttk.Radiobutton(self, text="Radio two", value=False) self.scroll = ttk.Scrollbar(self, orient=tk.VERTICAL) self.checked = ttk.Checkbutton(self, text="Checked", variable=tk.BooleanVar(value=True)) self.unchecked = ttk.Checkbutton(self, text="Unchecked") self.tree = ttk.Treeview(self, height=4, show=("tree", "headings")) self.setup_tree() self.scale_entry = ScaleEntry(self, from_=0, to=50, orient=tk.HORIZONTAL, compound=tk.RIGHT) self.combo = AutocompleteCombobox( self, completevalues=["something", "something else"]) self.progress = ttk.Progressbar(self, maximum=100, value=50) # Grid widgets self.grid_widgets() # Bind screenshot button self.bind("<F10>", self.screenshot) self.bind("<F9>", self.screenshot_themes) def setup_tree(self): """Setup an example Treeview""" self.tree.insert("", tk.END, text="Example 1", iid="1") self.tree.insert("", tk.END, text="Example 2", iid="2") self.tree.insert("2", tk.END, text="Example Child") self.tree.heading("#0", text="Example heading") def grid_widgets(self): """Put widgets in the grid""" sticky = {"sticky": "nswe"} self.label.grid(row=1, column=1, columnspan=2, **sticky) self.dropdown.grid(row=2, column=1, **sticky) self.entry.grid(row=2, column=2, **sticky) self.button.grid(row=3, column=1, columnspan=2, **sticky) self.radio_one.grid(row=4, column=1, **sticky) self.radio_two.grid(row=4, column=2, **sticky) self.checked.grid(row=5, column=1, **sticky) self.unchecked.grid(row=5, column=2, **sticky) self.scroll.grid(row=1, column=3, rowspan=8, padx=5, **sticky) self.tree.grid(row=6, column=1, columnspan=2, **sticky) self.scale_entry.grid(row=7, column=1, columnspan=2, **sticky) self.combo.grid(row=8, column=1, columnspan=2, **sticky) self.progress.grid(row=9, column=1, columnspan=2, padx=5, pady=5, **sticky) def screenshot(self, *args): """Take a screenshot, crop and save""" from mss import mss if not os.path.exists("screenshots"): os.makedirs("screenshots") box = { "top": self.winfo_y(), "left": self.winfo_x(), "width": self.winfo_width(), "height": self.winfo_height() } screenshot = mss().grab(box) screenshot = Image.frombytes("RGB", screenshot.size, screenshot.rgb) screenshot.save("screenshots/{}.png".format( ttk.Style(self).theme_use())) def screenshot_themes(self, *args): """Take a screenshot for all themes available""" from time import sleep for theme in THEMES: example.set_theme(theme) example.update() sleep(0.05) self.screenshot()
def __init__(self, *args, **kwargs): """Configure the GUI and other important features (load peak locations)""" tk.Tk.__init__(self, *args, **kwargs) self.title("PGAA Data Analysis App") sens_file = open("AllSensitivity.csv") self.all_peaks_sens = [ line.strip(" ").split(",") for line in sens_file.read().split("\n") ][:-1] sens_file.close() menuBar = tk.Menu(self, tearoff=0) fileMenu = tk.Menu(menuBar, tearoff=0) fileMenu.add_command(label="Add File(s)", command=lambda: self.add_files( tk.filedialog.askopenfilenames( initialdir=".", title="Select files", filetypes=[("Spectrum files", "*.spe")]))) fileMenu.add_command(label="Remove File(s)", command=self.remove_file_GUI) menuBar.add_cascade(label="File", menu=fileMenu) editMenu = tk.Menu(menuBar, tearoff=0) editMenu.add_command(label="ROIs", command=self.edit_ROIs_GUI) menuBar.add_cascade(label="Edit", menu=editMenu) viewMenu = tk.Menu(menuBar, tearoff=0) viewMenu.add_command(label="Side-by-Side", command=self.side_to_side_GUI) viewMenu.add_command(label="Zoom to ROI", command=self.ROIZoomGUI) menuBar.add_cascade(label="View", menu=viewMenu) analyzeMenu = tk.Menu(menuBar, tearoff=0) analyzeMenu.add_command(label="Elemental Analysis", command=self.Elemental_Analysis_GUI) analyzeMenu.add_command(label="Decomposition Analysis", command=lambda: 0) menuBar.add_cascade(label="Analyze", menu=analyzeMenu) self.config(menu=menuBar) graphInfo = tk.Frame(self) tk.Label(graphInfo, text="Current File:").grid(row=0, column=0) self.selectedFile = tk.StringVar() self.fileSelector = ttk.OptionMenu(graphInfo, self.selectedFile, "No Files to Display", command=self.change_file) self.fileSelector.grid(row=0, column=1, padx=(0, 75)) tk.Label(graphInfo, text="Livetime:").grid(row=0, column=2) self.currentLivetime = tk.Label(graphInfo, text=" N/A ", borderwidth=2, relief="sunken") self.currentLivetime.grid(row=0, column=3, padx=(0, 20)) tk.Label(graphInfo, text="Realtime:").grid(row=0, column=4) self.currentRealtime = tk.Label(graphInfo, text=" N/A ", borderwidth=2, relief="sunken") self.currentRealtime.grid(row=0, column=5) graphInfo.grid(row=0, column=1, pady=(10, 0)) f = Figure(figsize=(7, 3), dpi=100) self.plotAxes = f.add_subplot(111) f.subplots_adjust(bottom=0.15) self.plotAxes.set_xlabel("Energy (kEv)") self.plotAxes.set_ylabel("Counts Per Second") self.canvas = FigureCanvasTkAgg(f, self) self.canvas.draw() self.canvas.get_tk_widget().grid(row=1, column=0, columnspan=6, rowspan=6) toolbarFrame = tk.Frame(self) toolbarFrame.grid(row=8, column=0, columnspan=6, sticky="w") toolbar = NavigationToolbar2Tk(self.canvas, toolbarFrame) toolbar.children['!button6'].pack_forget() toolbar._Spacer() self.scaleChangeButton = tk.Button(toolbar, text="LOG", command=self.toggle_y_scale) self.scaleChangeButton.pack(side="left") win = tk.Toplevel() win.wm_title("Edit ROIs") ttk.Label(win, text="Add/Remove Elements of Interest:").grid(row=0, column=0, columnspan=2) elementsList = [ 'Actinium', 'Aluminum', 'Americium', 'Antimony', 'Argon', 'Arsenic', 'Astatine', 'Barium', 'Berkelium', 'Beryllium', 'Bismuth', 'Bohrium', 'Boron', 'Bromine', 'Cadmium', 'Calcium', 'Californium', 'Carbon', 'Cerium', 'Cesium', 'Chlorine', 'Chromium', 'Cobalt', 'Copper', 'Curium', 'Darmstadtium', 'Dubnium', 'Dysprosium', 'Einsteinium', 'Erbium', 'Europium', 'Fermium', 'Fluorine', 'Francium', 'Gadolinium', 'Gallium', 'Germanium', 'Gold', 'Hafnium', 'Hassium', 'Helium', 'Holmium', 'Hydrogen', 'Indium', 'Iodine', 'Iridium', 'Iron', 'Krypton', 'Lanthanum', 'Lawrencium', 'Lead', 'Lithium', 'Lutetium', 'Magnesium', 'Manganese', 'Meitnerium', 'Mendelevium', 'Mercury', 'Molybdenum', 'Neodymium', 'Neon', 'Neptunium', 'Nickel', 'Niobium', 'Nitrogen', 'Nobelium', 'Oganesson', 'Osmium', 'Oxygen', 'Palladium', 'Phosphorus', 'Platinum', 'Plutonium', 'Polonium', 'Potassium', 'Praseodymium', 'Promethium', 'Protactinium', 'Radium', 'Radon', 'Rhenium', 'Rhodium', 'Roentgenium', 'Rubidium', 'Ruthenium', 'Rutherfordium', 'Samarium', 'Scandium', 'Seaborgium', 'Selenium', 'Silicon', 'Silver', 'Sodium', 'Strontium', 'Sulfur', 'Tantalum', 'Technetium', 'Tellurium', 'Terbium', 'Thallium', 'Thorium', 'Thulium', 'Tin', 'Titanium', 'Tungsten', 'Ununbium', 'Ununhexium', 'Ununpentium', 'Ununquadium', 'Ununseptium', 'Ununtrium', 'Uranium', 'Vanadium', 'Xenon', 'Ytterbium', 'Yttrium', 'Zinc', 'Zirconium' ] self.comboValue = tk.StringVar() combo = AutocompleteCombobox(win, elementsList, textvariable=self.comboValue) combo.grid(row=1, column=0) ttk.Button(win, text="Add", command=lambda: self.add_element( win, self.elementIndex, self.comboValue.get())).grid( row=1, column=1) self.eleLabelList = [] self.removeBtnList = [] self.elementIndex = 2 ttk.Button(win, text="Submit", command=self.edit_ROIs).grid(row=1000, column=0, columnspan=2) self.ROIEditWindow = win self.ROIEditWindow.withdraw() self.ROIEditWindow.protocol("WM_DELETE_WINDOW", self.ROIEditWindow.withdraw) self.files = [] self.fileInfo = [] self.elements = [] self.polyFills = [] self.fitIndices = [] self.fitRanges = [] self.graphEnergies = [] self.graphCPS = [] self.selectionList = []
class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.config(pady=100) self.top_frame = tk.Frame(self, background="#f5f5f5", width=700, pady=10, padx=10) self.frame = tk.Frame(self.top_frame, background="#f5f5f5", height=200, width=700, pady=10) self.frame.grid_propagate(False) self.label1 = ttk.Label(self, text="Welcome!", font=LARGE_FONT) self.button1 = ttk.Button( self, text="Visit Page 1", command=lambda: controller.show_frame(PageOne)) self.button2 = ttk.Button( self, text="Visit Page 2", command=lambda: controller.show_frame(PageTwo)) self.button_test = ttk.Button(self.frame, text="Choose File", command=lambda: self.get_file_path()) self.label_welcome = ttk.Label(self.top_frame, text="Welcome!", font=("Helvetica", 16, 'bold')) self.label_point_notes = ttk.Label(self.frame, text="Notes", font=("Helvetica", 14, 'bold')) self.label_point1 = ttk.Label(self.frame, text="-> This is point 1", font=("Helvetica", 14)) self.dropdown = ttk.OptionMenu(self, tk.StringVar(), "First value", "Second Value") self.entry = ttk.Entry( self, textvariable=tk.StringVar(value="Default entry value.")) self.button = ttk.Button(self, text="Button") self.radio_one = ttk.Radiobutton(self, text="Radio one", value=True) self.radio_two = ttk.Radiobutton(self, text="Radio two", value=False) self.scroll = ttk.Scrollbar(self, orient=tk.VERTICAL) self.checked = ttk.Checkbutton(self, text="Checked", variable=tk.BooleanVar(value=True)) self.unchecked = ttk.Checkbutton(self, text="Unchecked") self.tree = ttk.Treeview(self, height=4, show=("tree", "headings")) self.setup_tree() self.scale_entry = ScaleEntry(self, from_=0, to=50, orient=tk.HORIZONTAL, compound=tk.RIGHT) self.combo = AutocompleteCombobox( self, completevalues=["something", "something else"]) self.progress = ttk.Progressbar(self, maximum=100, value=50) # Grid widgets self.set_grid_widgets() def get_file_path(self): self.filepath = tk.filedialog.askopenfilename() print(self.filepath) def setup_tree(self): """Setup an example Treeview""" self.tree.insert("", tk.END, text="Example 1", iid="1") self.tree.insert("", tk.END, text="Example 2", iid="2") self.tree.insert("2", tk.END, text="Example Child") self.tree.heading("#0", text="Example heading") def set_grid_widgets(self): """Put widgets in the grid""" sticky = {"sticky": "nswe"} self.label_welcome.grid(row=0, column=0) self.label_point_notes.grid(row=0, column=0) self.label_point1.grid(row=1, column=0) self.button_test.grid(row=2, column=0) self.frame.grid(row=1, column=0) self.top_frame.grid(row=0, column=0) self.top_frame.columnconfigure(0, weight=1) self.columnconfigure(0, weight=1) def grid_widgets(self): """Put widgets in the grid""" sticky = {"sticky": "nswe"} self.button1.grid(row=0, column=1, columnspan=2, **sticky) self.button2.grid(row=1, column=1, columnspan=2, **sticky) self.label1.grid(row=1, column=1, columnspan=2, **sticky) self.dropdown.grid(row=2, column=1, **sticky) self.entry.grid(row=2, column=2, **sticky) self.button.grid(row=3, column=1, columnspan=2, **sticky) self.radio_one.grid(row=4, column=1, **sticky) self.radio_two.grid(row=4, column=2, **sticky) self.checked.grid(row=5, column=1, **sticky) self.unchecked.grid(row=5, column=2, **sticky) self.scroll.grid(row=1, column=3, rowspan=8, padx=5, **sticky) self.tree.grid(row=6, column=1, columnspan=2, **sticky) self.scale_entry.grid(row=7, column=1, columnspan=2, **sticky) self.combo.grid(row=8, column=1, columnspan=2, **sticky) self.progress.grid(row=9, column=1, columnspan=2, padx=5, pady=5, **sticky)
class Interfaz(object): """ Programa para la filtración de bases de datos SQL, la personalización a través de una interfaz gráfica y la exportación de esos resultados en HTML""" def __init__( self, root): #Widgets que conformarán la interfaz gráfica del programa. self.root = root self.root.title("Programa base de datos Anla") self.root.iconbitmap(r'icono.ico') self.canvas = tk.Canvas(self.root, height=500, width=1000) self.canvas.pack() self.imagen_fondo = PhotoImage(file='montaña.png') self.frame = tk.Frame(self.root, bg=None) #"#20CDC8" self.frame.place(relheight=1, relwidth=1) self.imagen_Label = tk.Label(self.frame, image=self.imagen_fondo) self.imagen_Label.place(relheight=1, relwidth=1) self.autocompletar = AutocompleteCombobox(self.frame, completevalues=self.combo()) self.autocompletar.place(relheight=0.07, relwidth=0.65, relx=0.2, rely=0.08) self.boton = tk.Button(self.frame, text="Agregar Componente", relief="flat", fg="#FFDBA9", bg="#578FBE", font=("Helvetica", 10, "bold"), bd=1, command=self.adicionar_componentes) self.boton.place(relheight=0.07, relwidth=0.18, relx=0.018, rely=0.08) self.style = ttk.Style() self.style.configure("Treeview.Heading", font=("Helvetica", 12, "bold")) self.style.configure("mystyle.Treeview", highlightthickness=0, bd=0, font=('Helvetica', 11)) # Modify the font of the body self.arbol = ttk.Treeview(self.frame, height=5, style="mystyle.Treeview") self.arbol.place(relheight=0.65, relwidth=0.7, relx=0.15, rely=0.25) self.arbol.heading('#0', text='COMPONENTES SELECCIONADOS', anchor=CENTER) self.fuente = font.Font(family='Helvetica', size=10, weight='bold') self.boton_delete = tk.Button(self.frame, text="Eliminar componente", bg="#FFC16B", fg="#4F3F2A", relief="flat", font=("Helvetica", 10, "bold"), command=self.eliminar_seleccion) self.boton_delete.place(relheight=0.07, relwidth=0.15, relx=0.15, rely=0.92) self.boton_delete_all = tk.Button(self.frame, text="Eliminar todo", relief="flat", bg="#FF976B", fg="#4F3F2A", font=("Helvetica", 10, "bold"), command=self.eliminar_todo) self.boton_delete_all.place(relheight=0.07, relwidth=0.14, relx=0.72, rely=0.92) self.mensaje = tk.Label(self.frame, text="", anchor="center", font=self.fuente, bg="#20CDC8") self.mensaje.place(relx=0.2, rely=0.15) self.boton_prueba = tk.Button(self.frame, text="Conoce tus requisitos", relief="flat", bg="#52C496", fg="#4F3F2A", font=("Helvetica", 10, "bold"), command=self.otra_cosa) self.boton_prueba.place(relheight=0.07, relwidth=0.16, relx=0.43, rely=0.92) def combo( self ): #Formar una lista de los elementos seleccionados en la tabla de la base de datos #Función para desplegar los datos en un Autocomplete Combobox conn = sqlite3.connect("anla.db") c = conn.cursor() lista_nueva = c.execute( "SELECT DISTINCT COMPONENTE FROM diccionario_nuevo WHERE CÓDIGO != 'T' ORDER BY COMPONENTE" ) vacio = [] for componente in lista_nueva: vacio.append(componente[0]) return vacio def adicionar_componentes( self ): #Función que despliega los elementos seleccionados del Combobox #La información es desplegada en un Treeview widget add = self.autocompletar.get() if add not in self.combo(): self.mensaje = tk.Label(self.frame, text="", anchor="center", font=self.fuente, bg="#20CDC8") self.mensaje["text"] = "{} no es un componente".format(add) self.mensaje.place(relx=0.2, rely=0.15) return self.mensaje else: return self.arbol.insert('', tk.END, text=add, value=""), self.mensaje.destroy() def eliminar_seleccion( self): #Función para el botón de eliminar la selección una por una selected_item = self.arbol.selection() try: self.arbol.delete(selected_item) self.mensaje_seleccion.destroy() except: self.mensaje_seleccion = tk.Label(self.frame, text="Seleccione un componente", font=self.fuente, bg="#20CDC8") self.mensaje_seleccion.place(relx=0.8, rely=0.17) def eliminar_todo( self ): #Botón para eliminar todas las selecciones presentes en el Treeview for componente in self.arbol.get_children(): eliminar = self.arbol.delete(componente) return eliminar def otra_cosa( self ): #Crea una ventana en donde se desplegarán los resultados de la selección hecha self.otra_ventana = Toplevel() self.otra_ventana.title("Resultados") self.otra_ventana.iconbitmap(r'icono.ico') self.otro_canvas = Canvas(self.otra_ventana, height=600, width=1000) self.otro_canvas.pack() self.imagen_otro = PhotoImage(file='rosa.png') self.imagen_Label_otro = tk.Label(self.otra_ventana, image=self.imagen_otro) self.imagen_Label_otro.place(relheight=1, relwidth=1) self.arbol_otro = ttk.Treeview(self.otra_ventana, height=20, column=("column1", "column2", "column3"), show='headings') self.arbol_otro.column("#0", width=500, stretch=0, anchor="w") self.arbol_otro.place(relheight=0.65, relwidth=0.7, relx=0.15, rely=0.25) self.arbol_otro.heading("column1", text="Capas geográficas") self.arbol_otro.heading("column2", text="Tipo de información") self.arbol_otro.heading("column3", text="Geometría") self.boton_exportar = tk.Button(self.otra_ventana, text="Exportar", command=self.exportar) self.boton_exportar.place(relheight=0.07, relwidth=0.15, relx=0.15, rely=0.92) conn = sqlite3.connect("anla.db") c = conn.cursor() for componente in self.arbol.get_children( ): #Filtra la información de la tabla, de acuerdo a la selección hecha. c_individual = self.arbol.item(componente)["text"] insert = self.arbol_otro.insert("", tk.END, values=c_individual) if c_individual == "ANALISIS_RIESGO": anali_riesgo = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'ANALISIS_RIESGO' " ) for i in anali_riesgo.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "AREAS_CONSER_PROTEC_AMBIENTAL": area_conservacion = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'AREAS_CONSER_PROTEC_AMBIENTAL'" ) for i in area_conservacion.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "AREAS_REGLAMENTACION_ESPECIAL": areas_reglamentacion = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'AREAS_REGLAMENTACION_ESPECIAL'" ) for i in areas_reglamentacion.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "ARQUEOLOGIA": arqueologia = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'ARQUEOLOGIA'" ) for i in arqueologia.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "ATMOSFERA": atmosfera = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'ATMOSFERA' OR Medio = 'ATMOSFERA'" ) for i in atmosfera.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "BIOTICO_CONTI_COSTE": biotico = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'BIOTICO_CONTI_COSTE' or Medio = 'BIOTICO_CONTI_COSTE'" ) for i in biotico.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "CLIMA": clima = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'CLIMA' or Medio = 'CLIMA'" ) for i in clima.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "COMPENSACION": compensacion = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'COMPENSACION' OR Medio = 'COMPENSACION'" ) for i in compensacion.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "CONTINGENCIAS": contingencias = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'CONTINGENCIAS' OR Medio = 'CONTINGENCIAS'" ) for i in contingencias.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "ECONOMICO": economico = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'ECONOMICO'" ) for i in economico.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "GEOLOGIA": geologia = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'GEOLOGIA' OR Medio = 'GEOLOGIA'" ) for i in geologia.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "GEOMORFOLOGIA": geomorfologia = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'GEOMORFOLOGIA'" ) for i in geomorfologia.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "GEOTECNIA": geotecnia = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'GEOTECNIA'" ) for i in geotecnia.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "GESTION_RIESGO": gestion_riesgo = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'GESTION_RIESGO'" ) for i in gestion_riesgo.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "HIDROGEOLOGIA": hidrogeologia = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'HIDROGEOLOGIA' OR Medio = 'HIDROGEOLOGIA'" ) for i in hidrogeologia.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "HIDROLOGIA": hidrologia = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'HIDROLOGIA' OR Medio = 'HIDROLOGIA'" ) for i in hidrologia.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "INVERSION_1_POR_CIENTO": inversion1 = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'INVERSION_1_POR_CIENTO' OR Medio = 'INVERSION_1_POR_CIENTO'" ) for i in inversion1.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "MARINO": marino = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'MARINO' OR Medio = 'MARINO'" ) for i in marino.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "PAISAJE": paisaje = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'PAISAJE'" ) for i in paisaje.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "POLITICO_ADMINISTRATIVO ": politico = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'POLITICO_ADMINISTRATIVO ' OR Medio = 'POLITICO_ADMINISTRATIVO'" ) for i in politico.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "PROYECTO": proyecto = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'PROYECTO' OR Medio = 'PROYECTO'" ) for i in proyecto.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "SOCIOCULTURAL": sociocultural = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'SOCIOCULTURAL'" ) for i in sociocultural.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "SUELOS": suelos = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'SUELOS' OR Medio = 'SUELOS'" ) for i in suelos.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 elif c_individual == "ZONIFICACION": zonificacion = c.execute( "SELECT DISTINCT CAPAS, CÓDIGO, GEOMETRÍA FROM diccionario_nuevo WHERE COMPONENTE = 'ZONIFICACION'" ) for i in zonificacion.fetchall(): insert_2 = self.arbol_otro.insert(insert, tk.END, values=(i[0], i[1], i[2]), open=True) insert_2 else: pass def export_pdf(self): #Extrae la información del Treeview en un Dataframe vacio = [] valores = self.arbol_otro.get_children() for individuos in valores: c_individual = self.arbol_otro.item(individuos)["values"] vacio.append(c_individual) for child in self.arbol_otro.get_children(individuos): data = self.arbol_otro.item(child)["values"] vacio.append(data) df = pd.DataFrame( vacio, columns=["Capas geográficas", "Tipo de información", "Geometria"]) mask = df.applymap(lambda x: x is None) cols = df.columns[(mask).any()] for col in df[cols]: df.loc[mask[col], col] = '' return df def boton_pdf(self): #Devuelve la información como una tabla HTML df_2 = self.export_pdf() tabla = df_2.to_html("Resultados.html", justify="center", index=False) return tabla def exportar(self): #Exporta la selección return self.boton_pdf()
class Example(ThemedTk): """ Example that is used to create screenshots for new themes. """ def __init__(self, theme="arc"): """ :param theme: Theme to show off """ ThemedTk.__init__(self) self.set_theme(theme) # Create widgets self.label = ttk.Label(self, text="This is an example label.") self.dropdown = ttk.OptionMenu(self, tk.StringVar(), "First value") self.entry = ttk.Entry( self, textvariable=tk.StringVar(value="Default entry value.")) self.button = ttk.Button(self, text="Button") self.radio_one = ttk.Radiobutton(self, text="Radio one") self.radio_two = ttk.Radiobutton(self, text="Radio two") self.scroll = ttk.Scrollbar(self, orient=tk.VERTICAL) self.checked = ttk.Checkbutton(self, text="Checked", variable=tk.BooleanVar(value=True)) self.unchecked = ttk.Checkbutton(self, text="Unchecked") self.tree = ttk.Treeview(self, height=4, show=("tree", )) self.setup_tree() self.scale_entry = ScaleEntry(self, from_=0, to=50, orient=tk.HORIZONTAL, compound=tk.RIGHT) self.combo = AutocompleteCombobox( self, completevalues=["something", "something else"]) # Grid widgets self.grid_widgets() # Bind screenshot button self.bind("<F10>", self.screenshot) def setup_tree(self): """Setup an example Treeview""" self.tree.insert("", tk.END, text="Example 1", iid="1") self.tree.insert("", tk.END, text="Example 2", iid="2") self.tree.insert("2", tk.END, text="Example Child") def grid_widgets(self): """Put widgets in the grid""" sticky = {"sticky": "nswe"} self.label.grid(row=1, column=1, columnspan=2, **sticky) self.dropdown.grid(row=2, column=1, **sticky) self.entry.grid(row=2, column=2, **sticky) self.button.grid(row=3, column=1, columnspan=2, **sticky) self.radio_one.grid(row=4, column=1, **sticky) self.radio_two.grid(row=4, column=2, **sticky) self.checked.grid(row=5, column=1, **sticky) self.unchecked.grid(row=5, column=2, **sticky) self.scroll.grid(row=1, column=3, rowspan=8, **sticky, padx=5) self.tree.grid(row=6, column=1, columnspan=2, **sticky) self.scale_entry.grid(row=7, column=1, columnspan=2, **sticky) self.combo.grid(row=8, column=1, columnspan=2, **sticky) def screenshot(self, *args): """Take a screenshot, crop and save""" from mss import mss box = { "top": self.winfo_y(), "left": self.winfo_x(), "width": self.winfo_width(), "height": self.winfo_height() } screenshot = mss().grab(box) screenshot = Image.frombytes("RGB", screenshot.size, screenshot.rgb) screenshot.save("screenshot.png")
lbl_contacts = ttk.Label(window, text="Contact") lbl_formats = ttk.Label(window, text="Source format") lbl_inspires = ttk.Label(window, text="INSPIRE theme") lbl_keywords = ttk.Label(window, text="Keyword") lbl_licenses = ttk.Label(window, text="License") lbl_owners = ttk.Label(window, text="Owner") lbl_shares = ttk.Label(window, text="Share") lbl_srs = ttk.Label(window, text="Source spatial reference system") lbl_types = ttk.Label(window, text="Type") # add form widgets ent_search = AutocompleteEntry( window, style="Search.entry", width=20, completevalues=["bonjour", "bienvenue"] ) cb_fltr_actions = AutocompleteCombobox(window, completevalues=list(tags.get("actions"))) cb_fltr_contacts = AutocompleteCombobox( window, completevalues=list(tags.get("contacts")) ) cb_fltr_formats = AutocompleteCombobox(window, completevalues=list(tags.get("formats"))) cb_fltr_inspires = AutocompleteCombobox( window, completevalues=list(tags.get("inspires")) ) cb_fltr_keywords = AutocompleteCombobox( window, completevalues=list(tags.get("keywords")) ) cb_fltr_licenses = AutocompleteCombobox( window, completevalues=list(tags.get("licenses")) ) cb_fltr_owners = AutocompleteCombobox(window, completevalues=list(tags.get("owners"))) cb_fltr_shares = AutocompleteCombobox(window, completevalues=list(tags.get("shares")))
# -*- coding: utf-8 -*- # Copyright (c) Juliette Monsel 2018 # For license see LICENSE from ttkwidgets.autocomplete import AutocompleteCombobox import tkinter as tk window = tk.Tk() tk.Label( window, text="Combobox with autocompletion for the Tk instance's methods:").pack( side='left') entry = AutocompleteCombobox(window, width=20, completevalues=dir(window)) entry.pack(side='right') window.mainloop()
def __init__(self, *args, **kwargs): """Configure the GUI and other important features (load peak locations)""" tk.Tk.__init__(self, *args, **kwargs) self.title("PGAA Data Analysis App") sens_file = open("AllSensitivity.csv") self.all_peaks_sens = [line.strip(" ").split(",") for line in sens_file.read().split("\n")][:-1] sens_file.close() menuBar = tk.Menu(self, tearoff=0) fileMenu = tk.Menu(menuBar, tearoff=0) fileMenu.add_command(label="Add File(s)", command = lambda:self.add_files(tk.filedialog.askopenfilenames(initialdir = ".",title = "Select files",filetypes = [("Spectrum files","*.spe"), ("Canberra CNF Files","*.cnf")]))) fileMenu.add_command(label="Remove File(s)", command = self.remove_file_GUI) menuBar.add_cascade(label="File",menu=fileMenu) editMenu = tk.Menu(menuBar, tearoff=0) editMenu.add_command(label="ROIs", command = self.edit_ROIs_GUI) menuBar.add_cascade(label="Edit",menu=editMenu) viewMenu = tk.Menu(menuBar, tearoff=0) viewMenu.add_command(label="Side-by-Side", command = self.side_to_side_GUI) viewMenu.add_command(label="Zoom to ROI", command = self.ROIZoomGUI) menuBar.add_cascade(label="View",menu=viewMenu) analyzeMenu = tk.Menu(menuBar, tearoff=0) analyzeMenu.add_command(label="Elemental Analysis", command = self.Elemental_Analysis_GUI) analyzeMenu.add_command(label="Decomposition Analysis", command = lambda:0) menuBar.add_cascade(label="Analyze",menu=analyzeMenu) self.config(menu=menuBar) graphInfo = tk.Frame(self) tk.Label(graphInfo, text="Current File:").grid(row=0,column=0) self.selectedFile = tk.StringVar() self.fileSelector = ttk.OptionMenu(graphInfo, self.selectedFile, "No Files to Display", command=self.change_file) self.fileSelector.grid(row=0,column=1, padx=(0,75)) tk.Label(graphInfo, text="Livetime:").grid(row=0,column=2) self.currentLivetime = tk.Label(graphInfo, text=" N/A ", borderwidth=2, relief="sunken") self.currentLivetime.grid(row=0,column=3, padx=(0,20)) tk.Label(graphInfo, text="Realtime:").grid(row=0,column=4) self.currentRealtime = tk.Label(graphInfo, text=" N/A ", borderwidth=2, relief="sunken") self.currentRealtime.grid(row=0,column=5) graphInfo.grid(row=0,column=1, pady=(10,0)) f = Figure(figsize=(7,3), dpi=100) self.plotAxes = f.add_subplot(111) f.subplots_adjust(bottom=0.15) self.plotAxes.set_xlabel("Energy (kEv)") self.plotAxes.set_ylabel("Counts Per Second") self.canvas = FigureCanvasTkAgg(f, self) self.canvas.draw() self.canvas.get_tk_widget().grid(row=1,column=0,columnspan=6, rowspan=6) toolbarFrame = tk.Frame(self) toolbarFrame.grid(row=8,column=0,columnspan=6, sticky="w") toolbar = NavigationToolbar2Tk(self.canvas, toolbarFrame) toolbar._Spacer() self.scaleChangeButton = tk.Button(toolbar, text="LOG", command=self.toggle_y_scale) self.scaleChangeButton.pack(side="left") win = tk.Toplevel() win.wm_title("Edit ROIs") ttk.Label(win, text="Add/Remove Elements of Interest:").grid(row=0,column=0,columnspan=2) elementsList = list(set(map(lambda x: x[0], self.all_peaks_sens))) self.comboValue = tk.StringVar() combo = AutocompleteCombobox(win, elementsList, textvariable=self.comboValue) combo.grid(row=1,column=0) ttk.Button(win, text="Add", command=lambda: self.add_element(win, self.elementIndex, self.comboValue.get())).grid(row=1, column=1) self.eleLabelList = [] self.removeBtnList = [] self.elementIndex = 2 ttk.Button(win, text="Submit", command=self.edit_ROIs).grid(row=1000,column=0, columnspan=2) self.ROIEditWindow = win self.ROIEditWindow.withdraw() self.ROIEditWindow.protocol("WM_DELETE_WINDOW", self.ROIEditWindow.withdraw) self.files = [] self.fileInfo = [] self.elements = [] self.polyFills = [] self.fitIndices = [] self.fitRanges = [] self.graphEnergies = [] self.graphCPS = [] self.selectionList = [] self.isotopes = []
def __init__( self, root): #Widgets que conformarán la interfaz gráfica del programa. self.root = root self.root.title("Programa base de datos Anla") self.root.iconbitmap(r'icono.ico') self.canvas = tk.Canvas(self.root, height=500, width=1000) self.canvas.pack() self.imagen_fondo = PhotoImage(file='montaña.png') self.frame = tk.Frame(self.root, bg=None) #"#20CDC8" self.frame.place(relheight=1, relwidth=1) self.imagen_Label = tk.Label(self.frame, image=self.imagen_fondo) self.imagen_Label.place(relheight=1, relwidth=1) self.autocompletar = AutocompleteCombobox(self.frame, completevalues=self.combo()) self.autocompletar.place(relheight=0.07, relwidth=0.65, relx=0.2, rely=0.08) self.boton = tk.Button(self.frame, text="Agregar Componente", relief="flat", fg="#FFDBA9", bg="#578FBE", font=("Helvetica", 10, "bold"), bd=1, command=self.adicionar_componentes) self.boton.place(relheight=0.07, relwidth=0.18, relx=0.018, rely=0.08) self.style = ttk.Style() self.style.configure("Treeview.Heading", font=("Helvetica", 12, "bold")) self.style.configure("mystyle.Treeview", highlightthickness=0, bd=0, font=('Helvetica', 11)) # Modify the font of the body self.arbol = ttk.Treeview(self.frame, height=5, style="mystyle.Treeview") self.arbol.place(relheight=0.65, relwidth=0.7, relx=0.15, rely=0.25) self.arbol.heading('#0', text='COMPONENTES SELECCIONADOS', anchor=CENTER) self.fuente = font.Font(family='Helvetica', size=10, weight='bold') self.boton_delete = tk.Button(self.frame, text="Eliminar componente", bg="#FFC16B", fg="#4F3F2A", relief="flat", font=("Helvetica", 10, "bold"), command=self.eliminar_seleccion) self.boton_delete.place(relheight=0.07, relwidth=0.15, relx=0.15, rely=0.92) self.boton_delete_all = tk.Button(self.frame, text="Eliminar todo", relief="flat", bg="#FF976B", fg="#4F3F2A", font=("Helvetica", 10, "bold"), command=self.eliminar_todo) self.boton_delete_all.place(relheight=0.07, relwidth=0.14, relx=0.72, rely=0.92) self.mensaje = tk.Label(self.frame, text="", anchor="center", font=self.fuente, bg="#20CDC8") self.mensaje.place(relx=0.2, rely=0.15) self.boton_prueba = tk.Button(self.frame, text="Conoce tus requisitos", relief="flat", bg="#52C496", fg="#4F3F2A", font=("Helvetica", 10, "bold"), command=self.otra_cosa) self.boton_prueba.place(relheight=0.07, relwidth=0.16, relx=0.43, rely=0.92)
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.config(pady=100) self.top_frame = tk.Frame(self, background="#f5f5f5", width=700, pady=10, padx=10) self.frame = tk.Frame(self.top_frame, background="#f5f5f5", height=200, width=700, pady=10) self.frame.grid_propagate(False) self.label1 = ttk.Label(self, text="Welcome!", font=LARGE_FONT) self.button1 = ttk.Button( self, text="Visit Page 1", command=lambda: controller.show_frame(PageOne)) self.button2 = ttk.Button( self, text="Visit Page 2", command=lambda: controller.show_frame(PageTwo)) self.button_test = ttk.Button(self.frame, text="Choose File", command=lambda: self.get_file_path()) self.label_welcome = ttk.Label(self.top_frame, text="Welcome!", font=("Helvetica", 16, 'bold')) self.label_point_notes = ttk.Label(self.frame, text="Notes", font=("Helvetica", 14, 'bold')) self.label_point1 = ttk.Label(self.frame, text="-> This is point 1", font=("Helvetica", 14)) self.dropdown = ttk.OptionMenu(self, tk.StringVar(), "First value", "Second Value") self.entry = ttk.Entry( self, textvariable=tk.StringVar(value="Default entry value.")) self.button = ttk.Button(self, text="Button") self.radio_one = ttk.Radiobutton(self, text="Radio one", value=True) self.radio_two = ttk.Radiobutton(self, text="Radio two", value=False) self.scroll = ttk.Scrollbar(self, orient=tk.VERTICAL) self.checked = ttk.Checkbutton(self, text="Checked", variable=tk.BooleanVar(value=True)) self.unchecked = ttk.Checkbutton(self, text="Unchecked") self.tree = ttk.Treeview(self, height=4, show=("tree", "headings")) self.setup_tree() self.scale_entry = ScaleEntry(self, from_=0, to=50, orient=tk.HORIZONTAL, compound=tk.RIGHT) self.combo = AutocompleteCombobox( self, completevalues=["something", "something else"]) self.progress = ttk.Progressbar(self, maximum=100, value=50) # Grid widgets self.set_grid_widgets()
class MY_GUI(): def __init__(self, init_window_name): self.init_window_name = init_window_name #设置窗口 def set_init_window(self): ft1 = tkFont.Font(family='Arial', size=10, weight=tkFont.BOLD) ft_text = tkFont.Font(family='Arial', size=15) self.init_window_name.title("math quiz generator") #self.init_window_name.geometry('320x160+10+10') self.init_window_name.geometry('1000x700+10+10') # self.init_window_name["bg"] = "pink" # self.init_window_name.attributes("-alpha",0.9) self.choose_lable = Label(self.init_window_name, text="Please choose a Knowledge Component", font=ft1) self.choose_lable.grid(row=0, column=0, columnspan=2) # Drop down box from tkinter import ttk # self.drop_down_box = Combobox_Autocomplete(self.init_window_name, kc_list, listbox_width=150, highlightthickness=1) # self.drop_down_box.focus() self.drop_down_box = AutocompleteCombobox(self.init_window_name, completevalues=kc_list, width=150) self.drop_down_box.grid(row=1, column=0, columnspan=2) self.choose_language_label = Label(self.init_window_name, text="Please choose language", font=ft1) self.choose_language_label.grid(row=2, column=0) self.choose_language_box = ttk.Combobox(self.init_window_name, values=['English', 'Dutch'], width=50) self.choose_language_box.grid(row=3, column=0) self.is_retrieve = BooleanVar() self.choose_retrieve_button = ttk.Checkbutton( self.init_window_name, text='Retrieve Image or Not', variable=self.is_retrieve) self.choose_retrieve_button.grid(row=3, column=1) # Button self.str_generate_button = Button(self.init_window_name, text="Generate", bg="lightblue", width=10, command=self.generator) self.str_generate_button.grid(row=4, column=0, columnspan=2) self.result_data_label = Label(self.init_window_name, text="Generated question", font=ft1) self.result_data_label.grid(row=9, column=0) self.result_data_Text = Text(self.init_window_name, width=50) self.result_data_Text.grid(row=10, column=0) self.answer_label = Label(self.init_window_name, text="Answer", font=ft1) self.answer_label.grid(row=9, column=1) self.answer_data_Text = Text(self.init_window_name, width=50) self.answer_data_Text.grid(row=10, column=1) self.image_label = Label(self.init_window_name, text="Image", font=ft1) self.image_label.grid(row=11, column=0, columnspan=2) self.image_data_Text = Text(self.init_window_name, width=100) self.image_data_Text.grid(row=12, column=0, columnspan=2) self.img_label = Label(self.init_window_name, image=None) def generator(self): self.img_label.grid_forget() kc = self.drop_down_box.get() language = self.choose_language_box.get() kc_no = kc[0:kc.index('-') - 1] from overall_menu import Menu if language == 'Dutch': m = Menu(int(kc_no), 'nl', self.is_retrieve.get()) else: m = Menu(int(kc_no), 'en', self.is_retrieve.get()) question, answer, img_dir_list = m.menu() if len(question) == 0: question = "Sorry we can not generate text question for this KC" self.result_data_Text.delete(1.0, 'end') self.result_data_Text.insert(END, question) self.answer_data_Text.delete(1.0, 'end') self.answer_data_Text.insert(END, answer) from PIL import Image, ImageTk self.image_data_Text.delete(1.0, 'end') for img_dir in img_dir_list: self.image_data_Text.insert(END, str(img_dir)) self.image_data_Text.insert(END, '\n') # img = Image.open(img_dir) # w, h = img.size # ws = 500 # hs = h * ws / w # img = img.resize((ws,int(hs)), Image.ANTIALIAS) # photo = ImageTk.PhotoImage(img) # self.img_label.config(image=photo) # self.img_label.grid(row=12, column=0, columnspan=2) self.init_window_name.mainloop()
def test_autocompletecombobox(self): box = AutocompleteCombobox(self.window, completevalues=["Apple", "Pear", "Banana"]) box.pack() self.window.update() box.insert(0, "A") self.window.update() for item in ["A", "Up", "Down", "Left", "Right", "Return"]: box.handle_keyrelease(TestEvent(item)) box.autocomplete(0) box.set_completion_list(["Apply"])
class IsogeoSearchForm(ttk.Frame): def __init__(self, master=None, async_loop=None): tk.Frame.__init__(self, master) self.async_loop = async_loop # basics # master.resizable(width=True, height=True) master.title( "Isogeo Python SDK v{} - Sample desktop search form".format(pysdk_version) ) master.focus_force() self.grid(sticky="NSWE") self.grid_propagate(1) # styling self.style = ttk.Style(self) self.s1 = tk.PhotoImage( master=self, name="search1", data=data, format="gif -index 0" ) self.s2 = tk.PhotoImage( master=self, name="search2", data=data, format="gif -index 1" ) self.style.element_create( "Search.field", "image", "search1", ("focus", "search2"), border=[22, 7, 14], sticky="ew", ) self.style.layout( "Search.entry", [ ( "Search.field", { "sticky": "nswe", "border": 1, "children": [ ( "Entry.padding", { "sticky": "nswe", "children": [ ("Entry.textarea", {"sticky": "nswe"}) ], }, ) ], }, ) ], ) self.style.configure("Search.entry") # frames fr_global = ttk.Frame(self, name="global") fr_search = ttk.Frame(self, name="search_form") # UI vars self.app_name = StringVar(fr_global, "Sample desktop form") self.app_total = StringVar(fr_global, "0") self.app_url = StringVar(fr_global, "http://isogeo-api-pysdk.readthedocs.io") self.app_results = StringVar(fr_search, "0") # -- WIDGETS CREATION ------------------------------------------------- # add widgets lbl_app_name = tk.Label(fr_global, textvariable=self.app_name) lbl_app_total = ttk.Label(fr_global, textvariable=self.app_total) btn_app_url = ttk.Button( fr_global, text="APP Website", command=lambda: self.worker_allocator( async_loop=self.async_loop, to_do="open_web", **{"url": self.app_url} ), ) lbl_actions = ttk.Label(fr_search, text="Linked action") lbl_contacts = ttk.Label(fr_search, text="Contact") lbl_formats = ttk.Label(fr_search, text="Source format") lbl_inspires = ttk.Label(fr_search, text="INSPIRE theme") lbl_keywords = ttk.Label(fr_search, text="Keyword") lbl_licenses = ttk.Label(fr_search, text="License") lbl_owners = ttk.Label(fr_search, text="Owner") lbl_shares = ttk.Label(fr_search, text="Share") lbl_srs = ttk.Label(fr_search, text="Source spatial reference system") lbl_types = ttk.Label(fr_search, text="Type") # add form widgets self.ent_search = AutocompleteEntry( fr_search, style="Search.entry", width=20, completevalues=list() ) self.cb_actions = AutocompleteCombobox(fr_search) self.cb_contacts = AutocompleteCombobox(fr_search) self.cb_formats = AutocompleteCombobox(fr_search) self.cb_inspires = AutocompleteCombobox(fr_search) self.cb_keywords = AutocompleteCombobox(fr_search) self.cb_licenses = AutocompleteCombobox(fr_search) self.cb_owners = AutocompleteCombobox(fr_search) self.cb_shares = AutocompleteCombobox(fr_search) self.cb_srs = AutocompleteCombobox(fr_search) self.cb_types = AutocompleteCombobox(fr_search) lbl_results = ttk.Label(fr_search, textvariable=self.app_results) btn_reset = ttk.Button( master, text="Reset", command=lambda: self.worker_allocator( async_loop=self.async_loop, to_do="form_clear", **{"clear": 1} ), ) btn_close = ttk.Button(master, text="Close", command=master.destroy) # after UI build self.worker_allocator( async_loop=self.async_loop, to_do="form_clear", **{"clear": 1} ) # -- WIDGETS PLACEMENT ------------------------------------------------ d_pad = {"padx": 5, "pady": 5, "sticky": "NSEW"} lbl_app_name.grid(row=0, column=0, **d_pad) btn_app_url.grid(row=1, column=0, **d_pad) lbl_app_total.grid(row=2, column=0, **d_pad) self.ent_search.grid(row=1, columnspan=3, **d_pad) self.cb_actions.grid(row=3, column=0, **d_pad) self.cb_contacts.grid(row=3, column=1, **d_pad) self.cb_formats.grid(row=3, column=2, **d_pad) self.cb_inspires.grid(row=5, column=0, **d_pad) self.cb_keywords.grid(row=5, column=1, **d_pad) self.cb_licenses.grid(row=5, column=2, **d_pad) self.cb_owners.grid(row=7, column=0, **d_pad) self.cb_shares.grid(row=7, column=1, **d_pad) self.cb_srs.grid(row=7, column=2, **d_pad) self.cb_types.grid(row=9, column=1, **d_pad) lbl_actions.grid(row=2, column=0, **d_pad) lbl_contacts.grid(row=2, column=1, **d_pad) lbl_formats.grid(row=2, column=2, **d_pad) lbl_inspires.grid(row=4, column=0, **d_pad) lbl_keywords.grid(row=4, column=1, **d_pad) lbl_licenses.grid(row=4, column=2, **d_pad) lbl_owners.grid(row=6, column=0, **d_pad) lbl_shares.grid(row=6, column=1, **d_pad) lbl_srs.grid(row=6, column=2, **d_pad) lbl_types.grid(row=8, column=1, **d_pad) lbl_results.grid(row=22, column=0, columnspan=2, **d_pad) fr_global.grid(row=0, columnspan=1, **d_pad) fr_search.grid(row=1, columnspan=1, **d_pad) btn_reset.grid(row=2, column=0, sticky="NSW", padx=5, pady=5) btn_close.grid(row=2, column=0, sticky="NSE", padx=5, pady=5) # connecting comboboxes event self.cb_actions.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_contacts.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_formats.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_inspires.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_keywords.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_licenses.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_owners.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_shares.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_srs.bind("<<ComboboxSelected>>", self.cbs_manager) self.cb_types.bind("<<ComboboxSelected>>", self.cbs_manager) # -- TASKS HUB ------------------------------------------------------------ def cbs_manager(self, event): self.worker_allocator( async_loop=self.async_loop, to_do="form_update", **{"clear": 0} ) def worker_allocator(self, async_loop, to_do, **kwargs): """ Handler starting the asyncio part. """ d = kwargs threading.Thread( target=self._asyncio_thread, args=(async_loop, to_do, d) ).start() def _asyncio_thread(self, async_loop, to_do, kwargus): if to_do == "form_clear": async_loop.run_until_complete(self.fill_form(clear=1)) elif to_do == "form_update": async_loop.run_until_complete(self.fill_form(clear=0)) elif to_do == "open_web": async_loop.run_until_complete(self.open_url(kwargus.get("url").get())) else: pass # -- ASYNC METHODS -------------------------------------------------------- async def open_url(self, url): open_new_tab(url) async def fill_form(self, clear=0): if not hasattr(self, "isogeo"): self._init_isogeo() else: logging.info("App is already connected to Isogeo API") pass # search if clear: # clear self.ent_search.delete(0, "end") self.cb_actions.set("") self.cb_contacts.set("") self.cb_formats.set("") self.cb_inspires.set("") self.cb_keywords.set("") self.cb_licenses.set("") self.cb_owners.set("") self.cb_shares.set("") self.cb_srs.set("") self.cb_types.set("") # new search search = self.isogeo.search( self.token, page_size=0, whole_share=0, augment=1, tags_as_dicts=1 ) app_total = results_total = search.get("total") self.app_total.set("Total: {} metadata".format(app_total)) else: query = self.ent_search.get() + " " query += self.tags.get("actions").get(self.cb_actions.get(), "") + " " query += self.tags.get("contacts").get(self.cb_contacts.get(), "") + " " query += self.tags.get("formats").get(self.cb_formats.get(), "") + " " query += self.tags.get("inspires").get(self.cb_inspires.get(), "") + " " query += self.tags.get("keywords").get(self.cb_keywords.get(), "") + " " query += self.tags.get("licenses").get(self.cb_licenses.get(), "") + " " query += self.tags.get("owners").get(self.cb_owners.get(), "") + " " query += self.tags.get("shares").get(self.cb_shares.get(), "") + " " query += self.tags.get("srs").get(self.cb_srs.get(), "") + " " query += self.tags.get("types").get(self.cb_types.get(), "") + " " search = self.isogeo.search( self.token, page_size=0, whole_share=0, augment=1, tags_as_dicts=1, query=query, ) results_total = search.get("total") logging.debug(search.get("query")) self.tags = search.get("tags") # set values self.app_results.set("Results count: {} metadata".format(results_total)) self.ent_search.set_completion_list(list(self.tags.get("keywords").values())) self.cb_actions.set_completion_list(list(self.tags.get("actions"))) self.cb_contacts.set_completion_list(list(self.tags.get("contacts"))) self.cb_formats.set_completion_list(list(self.tags.get("formats"))) self.cb_inspires.set_completion_list(list(self.tags.get("inspires"))) self.cb_keywords.set_completion_list(list(self.tags.get("keywords"))) self.cb_licenses.set_completion_list(list(self.tags.get("licenses"))) self.cb_owners.set_completion_list(list(self.tags.get("owners"))) self.cb_shares.set_completion_list(list(self.tags.get("shares"))) self.cb_srs.set_completion_list(list(self.tags.get("srs"))) self.cb_types.set_completion_list(list(self.tags.get("types"))) def _init_isogeo(self): api_credentials = utils.credentials_loader("client_secrets.json") self.isogeo = Isogeo( client_id=api_credentials.get("client_id"), client_secret=api_credentials.get("client_secret"), ) self.token = self.isogeo.connect() # app properties self.isogeo.get_app_properties(self.token) self.app_props = self.isogeo.app_properties self.app_name.set( "Authenticated application: {}".format(self.app_props.get("name")) ) self.app_url.set(self.app_props.get("url", "https://www.isogeo.com"))
def __init__(self): super().__init__() self.master.title("Income calculator app") self.pack(fill=BOTH, expand=True) # label frame0 = Frame(self) frame0.pack(fill=X) title = Label(frame0, text='Welcome to the app', font=("Times New Roman", 20)) title.pack() # frame 1 frame1a = Frame(self) frame1a.pack(fill=X, padx=10, pady=10) name_label = Label(frame1a, text="Employee name :", width=15) name_label.pack(side=LEFT, padx=5, pady=5) name = Entry(frame1a) name.pack(fill=X, padx=5, expand=True) frame1b = Frame(self) frame1b.pack(fill=X, padx=10, pady=10) destination_label = Label(frame1b, text="Destination :", width=15) destination_label.pack(side=LEFT, padx=5, pady=5) # destination = Entry(frame1b) # destination.pack(fill=X, padx=5, expand=True) data = pd.read_csv("country_currency.csv") data.dropna(subset=['Country'], inplace=True) destination_select = StringVar(frame1b) destination = AutocompleteCombobox( frame1b, textvariable=destination_select, width=20, completevalues=data['Country'].to_list()) destination.pack() # frame 2 frame2 = Frame(self) frame2.pack(fill=X) netIncome_label = Label(frame2, text='Net income (per year)', width=20) netIncome_label.pack(side=LEFT, padx=5, pady=5) netIncome = Entry(frame2) netIncome.pack(fill=X, padx=5, expand=True) #frame 3 frame3 = Frame(self) frame3.pack(pady=10) maritalStatus_label = Label(frame3, text='Marital status ', width=15) maritalStatus_label.pack(side=LEFT, padx=5, pady=5) maritalStatus_select = StringVar(frame3) maritalStatus_select.set(maritalStatusList[0]) maritalStatus = OptionMenu(frame3, maritalStatus_select, *maritalStatusList) maritalStatus.pack(side=LEFT, padx=10) nKids_label = Label(frame3, text='Number of kids :', width=20) nKids_select = IntVar(frame3) nKids_select.set(nKids_list[0]) nKids_entry = OptionMenu(frame3, nKids_select, *nKids_list) nKids_label.pack(side=LEFT) nKids_entry.pack(side=LEFT) def get_info(): try: df_row = data[data['Country'] == destination_select.get()] currency_code = str(df_row['Currency code'].values[0]) currency_name = str(df_row['Currency'].values[0]) except: messagebox.showwarning('Warning', 'Please select a destination') currency_code = 'EUR' currecy_name = 'Euros' country2_select.set(currency_code) currency.set(currency_name) #frame 3 frame3a = Frame(self) frame3a.pack(pady=5) info_button = Button(frame3a, text='Get info', command=get_info) info_button.pack(side=TOP) forex_label = Label(frame3a, text='Currency conversion From ', width=15) forex_label.pack(side=LEFT, padx=5, pady=5) country1_select = StringVar(frame3a) country1_select.set(currecy_list[0]) country1 = OptionMenu(frame3a, country1_select, *currecy_list) country1.pack(side=LEFT, padx=10) forex_label2 = Label(frame3a, text=' To ', width=5) country2_select = StringVar(frame3a) currency = StringVar(frame3a) country2_select.set('EUR') currency.set('Euros') country2 = Text(frame3a, height=1, width=10) country2.insert(END, country2_select.get()) forex_label2.pack(side=LEFT) country2.pack(side=LEFT) forex_display = Text(frame3a, height=1, width=10) c = CurrencyRates() forex_display.insert( END, c.get_rate(country1_select.get(), country2_select.get())) forex_display.pack(side=RIGHT, padx=10) forex_conversion = StringVar() forex_conversion.set('1.0') def callback(*args): forex_display.delete(1.0, "end") country2.delete(1.0, "end") try: forex_conversion.set( c.get_rate(country1_select.get(), country2_select.get())) forex_display.insert(END, forex_conversion.get()) country2.insert(END, country2_select.get()) except Exception as exception_error: messagebox.showwarning('Warning', exception_error) forex_conversion.set('1.0') forex_display.insert(END, '0') country2_select.trace("w", callback) country1_select.trace("w", callback) #frame 4 frame4 = Frame(self) frame4.pack(pady=10) radioInput = IntVar(self) radioInput.set(1) R1 = Radiobutton(frame4, text="Yearly", variable=radioInput, value=1) R2 = Radiobutton(frame4, text="Montly", variable=radioInput, value=2) R3 = Radiobutton(frame4, text="Daily", variable=radioInput, value=3) period_label = Label(frame4, text='Calculating for period :') period_label.pack(side=LEFT) R1.pack(side=LEFT, pady=10) R2.pack(side=LEFT, pady=10) R3.pack(side=RIGHT, pady=10) now = datetime.now() # current date and time def get_string(): income = float('0' + netIncome.get()) status = str(maritalStatus_select.get()) output_string = "Income calculation \t {} \n\n".format( now.strftime("%d/%m/%Y, %H:%M:%S")) output_string += "Employee name :{} \n\n".format(name.get()) output_string += "Destination :{} \n".format( destination_select.get()) output_string += "Currency :{} - {} \n".format( country2_select.get(), currency.get()) output_string += "\nNet yearly income = {} {} ".format( income, country1_select.get()) output_string += "\n\nCalcualting for " + str( period[radioInput.get() - 1]) if radioInput.get() == 2: income = round(income / 12, 2) elif radioInput.get() == 3: income = round(income / 365, 2) output_string += "\nNet income = {} {} \nMarital status = {} ".format( income, country1_select.get(), status) output_string += "\nNumber of kids = " + str(nKids_select.get()) try: tax_rate = get_tax(country=destination_select.get()) social_sec_em, social_sec_com = get_social_security( country=destination_select.get()) except: messagebox.showwarning( 'Warning', 'Tax / social security information NOT found') tax_rate = 0 social_sec_em, social_sec_com = 0, 0 output_string += "\n\nTax rate : {} %".format(tax_rate) output_string += "\nSocial security rates:" output_string += "\n employee : {} %".format(social_sec_em) output_string += "\n company : {} %".format(social_sec_com) output_string += "\n\n Tax amount : {}".format( round(income * tax_rate / 100, 2)) output_string += "\n Employee social security amount : {}".format( round(income * social_sec_em / 100, 2)) output_string += "\n Company social security amount : {}".format( round(income * social_sec_com / 100, 2)) total = float( get_total(income=income, rate1=tax_rate, rate2=social_sec_em, rate3=social_sec_com)) output_string += "\n\nTotal : {} {}".format( total, country1_select.get()) output_string += '\n conversion = {}'.format( forex_conversion.get()) total *= float(forex_conversion.get()) output_string += "\n after conversion {} {} ".format( round(total, 2), country2_select.get()) return output_string def write_pdf(): pdf = FPDF() pdf.add_page() pdf.set_margins(30, 50, 25) pdf.set_font("Arial", size=15) output_string = get_string().split('\n') for s in output_string: pdf.cell(200, 10, txt=s, ln=1) pdf.output(name.get() + ' ' + str(now.strftime("%d_%m_%Y")) + '_info.pdf') def write_txt(): with open( name.get() + ' ' + str(now.strftime("%d_%m_%Y")) + '_info.txt', 'w') as sfile: sfile.write(get_string()) def string_display(): output_display.delete(1.0, END) output_display.insert(END, get_string()) frame5 = Frame(self, borderwidth=1) frame5.pack(fill=BOTH, expand=True, padx=5, pady=5) output_display = Text(frame5, height=15) scroll_y = Scrollbar(frame5, orient="vertical", command=output_display.yview) scroll_y.pack(side="right", expand=True, fill="y", padx=2, pady=2) output_display.pack(side='left', fill=X, padx=2, pady=2) output_display.configure(yscrollcommand=scroll_y.set) frame_final = Frame(self, relief=RAISED, borderwidth=1) frame_final.pack(fill=X, padx=10, pady=5) submit_button = Button(frame_final, text='Submit', command=string_display) submit_button.pack(side=LEFT) file_type_label = Label(frame_final, text='Choose file type:') file_type_label.pack() file_save_type = StringVar() file_save_type.set(save_list[0]) file_save = OptionMenu(frame_final, file_save_type, *save_list) def save_to_file(): if file_save_type.get() == 'txt': write_txt() messagebox.showinfo('Saved!', 'Saved as text file') elif file_save_type.get() == 'pdf': write_pdf() messagebox.showinfo('Saved!', 'Saved as pdf file') else: messagebox.showwarning('Warning', 'Please select text file or pdf') save_button = Button(frame_final, text='Save to file', command=save_to_file) save_button.pack(side=RIGHT) file_save.pack(side=RIGHT)
button_decimals=HoverButton(window,text='.',font=font,fg="Black",borderwidth=0,bg='white',command=lambda: input_to_input_var('.'),activebackground=active_button_background,takefocus=0) button_decimals.grid(row=6,column=0,sticky='news',padx=5,pady=5) deg_rad_button=tk.Button(window,text='deg',font=font,fg="Black",borderwidth=0,bg='hot pink',command=lambda: deg_rad_function(),activebackground=active_button_background) deg_rad_button.grid(row=6,column=1,sticky='news',padx=5,pady=5) deg_rad_button.bind('<Return>',lambda event: deg_rad_function()) deg_rad_button.bind('<FocusIn>',lambda event: deg_rad_button.config(bg='MediumPurple1')) deg_rad_button.bind('<FocusOut>',lambda event: deg_rad_button.config(bg='hot pink') if deg_rad_var.get()==0 else deg_rad_button.config(bg='turquoise1')) button_backspace=HoverButton(window,text='\u232b',font=font,fg="Black",borderwidth=0,bg='white',command=backspace,activebackground=active_button_background,takefocus=0) button_backspace.grid(row=6,column=2,sticky='news',padx=5,pady=5) button_clear_all=HoverButton(window,text='\u239a',font=font,fg="Black",borderwidth=0,bg='white',command=clear_input,activebackground=active_button_background,takefocus=0) button_clear_all.grid(row=6,column=3,sticky='news',padx=5,pady=5) function_dropdown=AutocompleteCombobox(window,width=5,textvariable=function_input_var,font=font) function_dropdown['completevalues']=function_list function_dropdown.bind('<Key>',function_select) function_dropdown.bind('<Double-Button-1>',function_select) function_dropdown.autocomplete(delta=-6) function_dropdown.current() function_dropdown.grid(row=7,column=0,sticky='news',padx=5,pady=5,columnspan=3) save_and_clear_all=HoverButton(window,text='\u21ba',font=font,fg="Black",borderwidth=0,bg='white',command=save_and_clear_input,activebackground=active_button_background,takefocus=0) save_and_clear_all.grid(row=7,column=3,sticky='news',padx=5,pady=5) button_Ans=HoverButton(window,text='Ans',font=font,fg="Black",borderwidth=0,bg='white',command=lambda: input_to_input_var('Ans'),activebackground=active_button_background,takefocus=0) button_Ans.grid(row=7,column=4,sticky='news',padx=5,pady=5) size_spinbox=tk.Spinbox(window,from_=0,to=100,font=font,fg="Black",bg="white",textvariable=size_var,width=4,command=lambda: resize(1),takefocus=1) size_spinbox.bind('<Key>',resize)
def set_init_window(self): ft1 = tkFont.Font(family='Arial', size=10, weight=tkFont.BOLD) ft_text = tkFont.Font(family='Arial', size=15) self.init_window_name.title("math quiz generator") #self.init_window_name.geometry('320x160+10+10') self.init_window_name.geometry('1000x700+10+10') # self.init_window_name["bg"] = "pink" # self.init_window_name.attributes("-alpha",0.9) self.choose_lable = Label(self.init_window_name, text="Please choose a Knowledge Component", font=ft1) self.choose_lable.grid(row=0, column=0, columnspan=2) # Drop down box from tkinter import ttk # self.drop_down_box = Combobox_Autocomplete(self.init_window_name, kc_list, listbox_width=150, highlightthickness=1) # self.drop_down_box.focus() self.drop_down_box = AutocompleteCombobox(self.init_window_name, completevalues=kc_list, width=150) self.drop_down_box.grid(row=1, column=0, columnspan=2) self.choose_language_label = Label(self.init_window_name, text="Please choose language", font=ft1) self.choose_language_label.grid(row=2, column=0) self.choose_language_box = ttk.Combobox(self.init_window_name, values=['English', 'Dutch'], width=50) self.choose_language_box.grid(row=3, column=0) self.is_retrieve = BooleanVar() self.choose_retrieve_button = ttk.Checkbutton( self.init_window_name, text='Retrieve Image or Not', variable=self.is_retrieve) self.choose_retrieve_button.grid(row=3, column=1) # Button self.str_generate_button = Button(self.init_window_name, text="Generate", bg="lightblue", width=10, command=self.generator) self.str_generate_button.grid(row=4, column=0, columnspan=2) self.result_data_label = Label(self.init_window_name, text="Generated question", font=ft1) self.result_data_label.grid(row=9, column=0) self.result_data_Text = Text(self.init_window_name, width=50) self.result_data_Text.grid(row=10, column=0) self.answer_label = Label(self.init_window_name, text="Answer", font=ft1) self.answer_label.grid(row=9, column=1) self.answer_data_Text = Text(self.init_window_name, width=50) self.answer_data_Text.grid(row=10, column=1) self.image_label = Label(self.init_window_name, text="Image", font=ft1) self.image_label.grid(row=11, column=0, columnspan=2) self.image_data_Text = Text(self.init_window_name, width=100) self.image_data_Text.grid(row=12, column=0, columnspan=2) self.img_label = Label(self.init_window_name, image=None)
class FileInput(BaseInput): def __init__(self, master, **kwargs): self._onlydir = False self._ext = ('Any File', '.*') self._rootdir = None self._excludefiles = [] self._suggestions = [] self._file_suggestions = None self._textv = StringVar() self._box = ttk.Frame(master=master) self._box.grid_columnconfigure(0, weight=1) self._box.grid_columnconfigure(1, weight=0) self._box.grid_rowconfigure(0, weight=1) self._input = AutocompleteCombobox( master=self._box, completevalues=[], textvariable=self._textv ) # Redirect configure to input setattr(self._box, "config", self._input.config) setattr(self._box, "configure", self._input.configure) setattr(self._box, "keys", self._input.keys) setattr(self._box, "cget", self._input.cget) setattr(self._box, "winfo_class", self._input.winfo_class) setattr(self._box, "bind", self._input.bind) setattr(self._box, "set_completion_list", self._input.set_completion_list) super().__init__(tk=self._box, **kwargs) self.connect_to_prop("onlydir", self._on_onlydir_changed) self.connect_to_prop("ext", self._on_ext_changed) self.connect_to_prop("rootdir", self._on_rootdir_changed) self.connect_to_prop("excludefiles", self._on_excludefiles_changed) #self.connect_to_prop("suggestion", self.on_changed_suggestion) self._input.drop_target_register(DND_FILES) self._input.dnd_bind('<<Drop>>', self._drop) self._input.grid(row=0, column=0, sticky="news") self._btn = ttk.Button(master=self._box, command=self._load_file, text="Browse...") self._btn.grid(row=0, column=1) def _on_excludefiles_changed(self, value): self._excludefiles = value if value else [] self._set_suggestions() def _on_onlydir_changed(self, value): self._onlydir = value def on_changed_suggestion(self, value): if value: self._suggestions = value self._set_suggestions() def _set_suggestions(self): if self._rootdir and Path(self._rootdir).exists() and self._file_suggestions == None: get_suggestion_from_ext = lambda ext: list(filter(lambda fn: Path(fn).stem not in self._excludefiles, [str(fn) for fn in Path(self._rootdir).rglob(f"*{ext[1]}")])) if isinstance(self._ext, list): from functools import reduce self._file_suggestions = reduce(lambda a, curr: a + get_suggestion_from_ext(curr), []) else: self._file_suggestions = get_suggestion_from_ext(self._ext) if isinstance(self._file_suggestions, list): self._input.set_completion_list(self._suggestions + self._file_suggestions) else: self._input.set_completion_list(self._suggestions) def _on_ext_changed(self, value): self._ext = value if value else ('Any File', '.*') self._set_suggestions() def _on_rootdir_changed(self, value): self._rootdir = value self._set_suggestions() @property def container(self): return self._box def on_disposed(self): self._box.destroy() self._btn.destroy() super().on_disposed() def _load_file(self): if self._onlydir: f = tk.filedialog.askdirectory() else: f = tk.filedialog.askopenfilename(filetypes=self._ext if isinstance(self._ext, list) else [self._ext]) if f is None or f == '': return self._textv.set(str(Path(f))) def _drop(self, event): if event.data: files = self._tk.tk.splitlist(event.data) for f in files: self._textv.set(f) break return event.action