def test_theme_setting(self): for theme in self.tk.get_themes(): window = ThemedTk() button = ttk.Button(window) label = ttk.Label(window) button.pack() label.pack() window.set_theme(theme) window.update() window.destroy()
class TestThemedWidgets(TestCase): """ Tkinter may crash if widgets are not configured properly in a theme. Therefore, in addition to checking if all files for a theme exist by loading it, this Test also tests every core ttk widget to see if the widget can be successfully created with the theme data. When Tkinter crashes, it keeps the Global Interpreter Lock in place, so the program actually has to be terminated with SIGTERM. Therefore, this test only executes on UNIX. """ WIDGETS = [ "Label", "Treeview", "Button", "Frame", "Notebook", "Progressbar", "Scrollbar", "Scale", "Entry", "Combobox" ] def setUp(self): self.window = ThemedTk() def test_widget_creation(self): try: import signal except ImportError: pass if "signal" not in locals() or not hasattr(signal, "alarm"): return for theme in self.window.themes: self.window.set_theme(theme) for widget in self.WIDGETS: window = ThemedTk(theme=theme) signal.alarm(5) printf("Testing {}: {}".format(theme, widget), end=" - ") getattr(ttk, widget)(window).pack() window.update() window.destroy() signal.alarm(0) printf("SUCCESS") def tearDown(self): self.window.destroy()
def test_widget_creation(self): try: import signal except ImportError: pass if "signal" not in locals() or not hasattr(signal, "alarm"): return for theme in self.window.themes: self.window.set_theme(theme) for widget in self.WIDGETS: window = ThemedTk(theme=theme) signal.alarm(5) printf("Testing {}: {}".format(theme, widget), end=" - ") getattr(ttk, widget)(window).pack() window.update() window.destroy() signal.alarm(0) printf("SUCCESS")
class ExportDialog: """ExportDialog provides a window to save a dataframe to csv file with custom settings""" def __init__(self, df: DataFrame): self.__root = ThemedTk(theme=theme) self.__root.title("Export") self.__df = df frame = Frame(self.__root) Label(frame, text="Seperator").grid(column=1, row=1) self.__separator = StringVar(self.__root, value=",") Entry(frame, textvariable=self.__separator).grid(column=2, row=1) Label(frame, text="Encoding").grid(column=1, row=2) self.__encoding = StringVar(self.__root, value="UTF-8") Combobox(frame, textvariable=self.__encoding, values=encodings, state="readonly").grid(column=2, row=2) frame.pack(fill="both", expand=True) frame = Frame(self.__root) Button(frame, text="Save", command=self.export_csv).pack() frame.pack(fill="both", expand=True) def run(self): self.__root.mainloop() def exit(self): self.__root.destroy() def export_csv(self): e = self.__encoding.get() s = self.__separator.get() destination = asksaveasfilename(defaultextension=".csv", filetypes=(("Csv File", "*.csv"), ), initialfile="export.csv") if destination: try: self.__df.to_csv(destination, sep=s, encoding=e) except ValueError: showerror(text="Oops. Something went wrong. Please try again.") finally: self.exit()
class MainteGuiMain: def __init__(self): print("MainteGui Constructor") def thread(self, input_queue, output_queue): self.input_queue = input_queue self.output_queue = output_queue self.root = ThemedTk(theme='radiance') app = MainteGui(master=self.root, num_arm=NUM_ARM, num_joint_per_arm=NUM_JOINT, input_queue=self.input_queue, output_queue=self.output_queue) self.root.protocol("WM_DELETE_WINDOW", self.quit) self.root.mainloop() def quit(self): print("Call destroy") msg = MsgCmd(MsgType.MSG_ALL_TERMINATE) self.output_queue.put(msg) self.root.destroy()
class NewMissionPopup(object): """This class creates a custom pop-up window for use when creating a new Mission object""" def __init__(self, text): self.top = ThemedTk(theme="plastik") self.top.title("New Mission") self.top.grab_set() # freezes the app until the user enters or cancels self.mfi = config.mission_file_items self.label = ttk.Label(self.top, text=text, background='white') self.label.pack() self.e = ttk.Entry(self.top) self.e.pack() self.b = ttk.Button(self.top, text='Ok', command=self._cleanup) self.b.pack() self.top.mainloop() #end init def _cleanup(self): """Clean up the window we created""" name = self.e.get() self._add_to_items_list(name) self.top.grab_release() # HAVE TO RELEASE self.top.destroy() #end _cleanup @staticmethod def _add_to_items_list(new_mission_name): logging.debug("Adding mission: \"%s\"..." % new_mission_name) mission = Mission(new_mission_name) config.mission_file_items.add_item(mission) config.active_item = mission config.gui.update_option_pane()
def destroy(self): """ Destroy the MainWindow after checking for running processes Destroying the MainWindow is not allowed while connected to a Strategy Server or running one, the user will have to exit the server first. """ if self.strategies_frame.settings is not None: if self.strategies_frame.settings.server: messagebox.showerror("Error", "You cannot exit the GSF Parser while running a Strategy Server.") return False if self.strategies_frame.settings.client: messagebox.showerror("Error", "You cannot exit the GSF Parser while connected to a Strategy Server.") return False self.strategies_frame.settings.destroy() if self.realtime_frame.parser is not None: if self.realtime_frame.parser.is_alive(): self.realtime_frame.stop_parsing() ThemedTk.destroy(self) if self.rpc is not None: self.rpc.update() self.rpc.close() return True
def main(): global LARGE_FONT, realpositive, port LARGE_FONT = ("Verdana", 12) x, y = 648, 520 #root = tk.Tk() root = ThemedTk(theme="adapta") realpositive = tk.IntVar() port = tk.StringVar() global startpage, synthesis, darlington, pageThree, transferFunction startpage = tk.Frame(root) synthesis = tk.Frame(root) darlington = tk.Frame(root) pageThree = tk.Frame(root) transferFunction = tk.Frame(root) for frame in (startpage, synthesis, darlington, pageThree, transferFunction): frame.grid(row=0, column=0, sticky='news') StartPage() Synthesisframe() Darlingtonframe() PageThreeframe() TransferFunctionframe() root.update_idletasks() # Update "requested size" from geometry manager a, a0 = str(x), x / 2 b, b0 = str(y), y / 2 root.geometry("+%d+%d" % ((root.winfo_screenwidth() / 2) - a0, (root.winfo_screenheight() / 3) - b0)) root.deiconify() root.resizable(width=False, height=False) menubar = tk.Menu(root) filemenu = tk.Menu(menubar, tearoff=0) filemenu.add_command(label="Tutorial", command=toturial) filemenu.add_command(label="About", command=About) filemenu.add_command(label="Exit", command=root.destroy) menubar.add_cascade(label="MENU", menu=filemenu) root.config(menu=menubar) root.title("LC & RC Filter") root.bind('<Escape>', lambda e: root.destroy()) root.protocol("WM_DELETE_WINDOW", root.iconify) raise_frame(startpage) root.mainloop()
class Program: """Exampleprogram to show possible usage of the module csvxmlImporter""" __importer: CsvXmlImporter __settings: dict def __init__(self): """__init__ creates the tkinter gui""" self.__settings = {} self.__importer = CsvXmlImporter() # ***--*** main window and menu band ***---*** self.__root = ThemedTk(theme=theme) self.__root.title("Csv/Xml Importer") self.__root.minsize(560, 1) menu = Menu(self.__root) self.__root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Add Files", command=self.add_files) filemenu.add_command(label="Remove All", command=self.remove_all) filemenu.add_separator() filemenu.add_command(label="Add xsl File", command=self.add_xslfile) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.exit) helpmenu = Menu(menu, tearoff=0) menu.add_cascade(label="Help", menu=helpmenu) helpmenu.add_command(label="?", command=self.ask_help) helpmenu.add_command(label="About", command=self.ask_about) # ***---*** source file frame dialog ***---*** srcfilesframe = LabelFrame(self.__root, text="Sourcefiles") buttonframe = Frame(srcfilesframe) addbutton = Button(buttonframe, text="Add Files", command=self.add_files) addbutton.pack(fill=X) removefilesbutton = Button(buttonframe, text="Remove Selected", command=self.remove_files) removefilesbutton.pack(fill=X) removeallbutton = Button(buttonframe, text="Remove All", command=self.remove_all) removeallbutton.pack(fill=X) buttonframe.grid(column=1, row=1) self.__srcfileslistbox = Listbox(srcfilesframe, selectmode="extended", width=100, height=5) self.__srcfileslistbox.grid(column=2, row=1) Label(srcfilesframe, text="Encoding").grid(column=1, row=2, sticky=E) self.__settings["encoding"] = StringVar() self.__settings["encoding"].trace_add("write", self.update_settings) encCombobox = Combobox(srcfilesframe, textvariable=self.__settings["encoding"], values=encodings, state="readonly") encCombobox.bind("<FocusOut>", self.update_settings) encCombobox.grid(column=2, row=2, pady=10) srcfilesframe.pack(fill=X) # ***---*** xsl file dialog ***---*** xslfileframe = LabelFrame(self.__root, text="XSL-File") Button(xslfileframe, text="Add .xsl", command=self.add_xslfile).grid(column=1, row=1) self.__xsllistbox = Listbox(xslfileframe, width=100, height=1) self.__xsllistbox.grid(column=2, row=1, sticky="w") buttonframe = Frame(xslfileframe) Button(buttonframe, text="Apply Parameter", command=self.apply_xslparameter).pack(fill=X) Button(buttonframe, text="Restore Default", command=self.reset_xslparameter).pack(fill=X) buttonframe.grid(column=1, row=2) box = Frame(xslfileframe) self.__xslparametertext = Text(box, height=3, width=75) self.__xslparametertext.grid(column=0, row=1, sticky="nsew") scrollbar = Scrollbar(box, command=self.__xslparametertext.yview) scrollbar.grid(column=0, row=1, sticky="nse") box.grid(column=2, row=2, sticky="we") self.__xslparametertext["yscrollcommand"] = scrollbar.set xslfileframe.pack(fill=X) # ***---*** file format settings dialog ***---*** # small help function def limit_character(entry_text): """limit_characters cuts down the characters of an entry text to one""" if len(entry_text.get()) > 0: # take only last input character and throw away the rest entry_text.set(entry_text.get()[-1]) fileformatsettingsframe = LabelFrame(self.__root, text="File Format Settings") Label(fileformatsettingsframe, text="Delimiter").grid(column=1, row=1, sticky=E) self.__settings["delimiter"] = StringVar() seperatorentry = Entry(fileformatsettingsframe, textvariable=self.__settings["delimiter"], width=1) self.__settings["delimiter"].trace_add( "write", lambda *_: limit_character(self.__settings["delimiter"])) seperatorentry.bind("<Return>", self.update_settings) seperatorentry.bind("<FocusOut>", self.update_settings) seperatorentry.grid(column=2, row=1, sticky=W, padx=15) Label(fileformatsettingsframe, text="Quotechar").grid(column=1, row=2, sticky=E) self.__settings["quotechar"] = StringVar() quotecharentry = Entry(fileformatsettingsframe, textvariable=self.__settings["quotechar"], width=1) self.__settings["quotechar"].trace_add( "write", lambda *_: limit_character(self.__settings["quotechar"])) quotecharentry.bind("<Return>", self.update_settings) quotecharentry.bind("<FocusOut>", self.update_settings) quotecharentry.grid(column=2, row=2, sticky=W, padx=15) Label(fileformatsettingsframe, text="Doublequote").grid(column=1, row=3, sticky=E) self.__settings["doublequote"] = BooleanVar() Checkbutton(fileformatsettingsframe, variable=self.__settings["doublequote"], command=self.update_settings).grid(column=2, row=3, sticky=W, padx=10) Label(fileformatsettingsframe, text="Quoting").grid(column=1, row=5, sticky=E) quotingopt = {"minimal": 0, "all": 1, "non numeric": 2, "none": 3} self.__settings["quoting"] = IntVar() for i, (key, value) in enumerate(quotingopt.items()): Radiobutton( fileformatsettingsframe, text=key, value=value, variable=self.__settings["quoting"], command=self.update_settings, ).grid( column=2 + i, row=5, padx=10, sticky=W, ) Label(fileformatsettingsframe, text="Ignore spaces at beginning").grid(column=1, row=6, sticky=E) self.__settings["skipinitialspace"] = BooleanVar() self.__settings["skipinitialspace"].set(False) Checkbutton(fileformatsettingsframe, variable=self.__settings["skipinitialspace"], command=self.update_settings).grid(column=2, row=6, sticky=W, padx=10) fileformatsettingsframe.pack(fill=X) # ***---*** preview frame ***---*** previewframe = LabelFrame(self.__root, text="Preview") self.__pdtable = Table(parent=previewframe, dataframe=self.__importer.dfx) self.__pdtable.show() previewframe.pack(fill="both", expand=True) # ***---*** export button ***---*** exportframe = LabelFrame(self.__root, text="Export") Button(exportframe, text="Export", command=self.create_exportdialog).pack() exportframe.pack(fill="both", expand=True) # save settings to check for changes on update self.__prevsettings = self.__unpack_settings(self.__settings) def run(self): """run starts the mainloop of tkinter gui""" self.__root.mainloop() def exit(self): """exit closes tkinter application""" self.__root.destroy() def add_files(self): """add_files called by user to add files via dialog""" names = askopenfilenames(title="Select .csv or .xml files", filetypes=(("any", "*.*"), ("Csv File", "*.csv"), ("Xml File", "*.xml"))) if names: try: self.__srcfileslistbox.insert(END, *names) self.__importer.update_files( *self.__srcfileslistbox.get(0, END)) except AttributeError as e: showerror(title="Error", message="No .xsl file set") except ValueError as _: showerror(title="Error", message="Could not open files") self.__srcfileslistbox.delete(0, END) self.__update_table() self.__update_dialog() def remove_files(self): """remove_files called by user to remove in listbox selected files""" itemstodelete = self.__srcfileslistbox.curselection() if itemstodelete: for i in itemstodelete: self.__srcfileslistbox.delete(i) x = self.__srcfileslistbox.get(0, END) if x: self.__importer.update_files(*x) else: self.__importer.reset() self.__update_table() def remove_all(self): """remove_all called by user to remove all imported files""" self.__srcfileslistbox.delete(0, END) self.__importer.reset() self.__update_table() def add_xslfile(self): """add_xslfile called to open .xsl file via dialog""" filename = askopenfilename(title="Select .xsl file", filetypes=(("Xsl File", "*.xsl"), )) if filename: self.__importer.set_xslfile(filename) self.__xsllistbox.insert(0, filename) self.reset_xslparameter() def apply_xslparameter(self): """apply_xslparameter reads userinput from textbox and parses input in dict""" param = self.__xslparametertext.get("1.0", END) with StringIO(param) as f: lines = [line[:-1] for line in f.readlines()] # escape_decode removes extra escapes added through reading the text d = { x.split("=")[0]: escape_decode(x.split("=")[1])[0] for x in lines if x } self.__importer.set_xslparameter(**d) if not self.__importer.dfx.empty: self.__importer.update_files() self.__update_table() def reset_xslparameter(self): """reset_xslparameter restores default values for xslparameters""" self.__xslparametertext.delete("1.0", END) param = self.__importer.get_xslparameter(default=True) s = "" for key, item in param.items(): s += repr(key + "=" + item)[1:-1] + '\n' self.__xslparametertext.insert("1.0", s) @staticmethod def __unpack_settings(settings): """__unpack_settings takes settings in form of dict with tkinter variables and unpacks them""" return dict((key, settings[key].get()) for key in settings) def __update_table(self): """__update_table updates pandastable to display the actual dataframe""" self.__pdtable.updateModel(TableModel(self.__importer.dfx)) self.__pdtable.redraw() def __update_dialog(self): """__update_dialog updates the input fields with settings from the importer""" importersettings = self.__importer.get_settings() for key in self.__settings: if key in importersettings: self.__settings[key].set(importersettings[key]) def update_settings(self, *_): """update_settings reads input fields and applies the user input to the importer""" newsettings = self.__unpack_settings(self.__settings) if newsettings != self.__prevsettings: # figure out which settings changed changedsettings = dict(newsettings.items() - self.__prevsettings.items()) self.__importer.set_settings(**changedsettings) self.__prevsettings = newsettings if not self.__importer.dfx.empty: self.__update_table() def ask_help(self): showinfo(title="Help", message="""\ To import files select Add Files For .xml import first add a .xsl file. To export select Export and set desired parameters\ """) def ask_about(self): showinfo( title="About", message="Projektarbeit Python\nAuthor: Leo Schurrer\nDate: 19/12/20" ) def create_exportdialog(self): ExportDialog(self.__importer.dfx).run()
class ServerWindow: def __init__(self): self.mainwindow = ThemedTk(theme='breeze') self.mainwindow.protocol("WM_DELETE_WINDOW", self.close) self.address = tk.StringVar() self.port = tk.IntVar() self.room_name = tk.StringVar() self.address.set("127.0.0.1") self.port.set(5000) self.room_name.set("Chat Room") self.status = { 'server': tk.StringVar(value="Incative"), 'conn': tk.StringVar(value='0 Connection(s)'), 'rooms': tk.StringVar(value='0 Room(s)'), 'verbose': tk.BooleanVar() } self.rooms = [] self.is_update = True self.__init() self.restore() def title(self): self.mainwindow.title(self.room_entry.get()) def start(self): self.title() self.mainwindow.mainloop() def __init(self): # Frame widgets self.__frame = tk.ttk.LabelFrame(self.mainwindow, text='Server Info') self.__frame.pack(side="top", padx=5, pady=5, fill='both', expand=True) self.__room_frame = tk.ttk.LabelFrame(self.mainwindow, text='Room List') self.__room_frame.pack(side='top', pady=(0, 5), padx=5, fill='both', expand=True) self.__status_frame = tk.ttk.LabelFrame(self.mainwindow, text='Status') self.__status_frame.pack(side='top', fill='x', padx=5, pady=(0, 5), expand=True) self.__verbose_frame = tk.ttk.LabelFrame(self.mainwindow, text='Verbose') # self.__verbose_frame.pack(side='top', padx=( # 0, 5), pady=5, fill='both', expand=True) # Chat Window self.verbose_window = tk.Text(self.__verbose_frame, width=60, height=10) self.scrollframe = ScrollFrame(self.__room_frame) # Status widgets tk.ttk.Label(self.__status_frame, text="Server").grid(row=0, column=0, sticky="W") tk.ttk.Label(self.__status_frame, text="Active Connection").grid(row=1, column=0, sticky="W") tk.ttk.Label(self.__status_frame, text="Rooms").grid(row=2, column=0, sticky="W") self.__status_label_server = tk.ttk.Label( self.__status_frame, textvariable=self.status['server']) self.__status_label_conn = tk.ttk.Label( self.__status_frame, textvariable=self.status['conn']) self.__status_label_rooms = tk.ttk.Label( self.__status_frame, textvariable=self.status['rooms']) self.__verbose_toggle = tk.ttk.Checkbutton( self.__status_frame, text='Verbose', variable=self.status['verbose'], command=self.toggle_verbose) # Connection Form widgets self.addr_label = tk.ttk.Label(self.__frame, text="Bind Address") self.addr_entry = tk.ttk.Entry(self.__frame, textvariable=self.address) self.port_label = tk.ttk.Label(self.__frame, text="Port") self.port_entry = tk.ttk.Entry(self.__frame, textvariable=self.port) self.room_label = tk.ttk.Label(self.__frame, text="Room Name") self.room_entry = tk.ttk.Entry(self.__frame, textvariable=self.room_name) self.listen_button = tk.ttk.Button(self.__frame, text="\u23f5 Listen", command=self.listen) self.stop_button = tk.ttk.Button(self.__frame, text="\u23f9 Stop", command=self.stop) self.room_button = tk.ttk.Button(self.__frame, text="Create", command=self.create_room) # Packing & grid widgets self.addr_label.grid(row=0, column=0, sticky="w") self.addr_entry.grid(row=0, column=1) self.port_label.grid(row=1, column=0, sticky="w") self.port_entry.grid(row=1, column=1) self.listen_button.grid(row=0, column=2, rowspan=2, sticky="NSEW", padx=2, pady=2) self.stop_button.grid(row=0, column=3, rowspan=2, sticky="NSEW", padx=2, pady=2) self.room_label.grid(row=2, column=0) self.room_entry.grid(row=2, column=1) self.room_button.grid(row=2, column=2, columnspan=2, padx=2, pady=5, sticky="NSEW") self.scrollframe.pack() self.__status_label_server.grid(row=0, column=1, padx=5, sticky="w") self.__status_label_conn.grid(row=1, column=1, padx=5, sticky="w") self.__status_label_rooms.grid(row=2, column=1, padx=5, sticky="w", pady=(0, 5)) self.__verbose_toggle.grid(row=0, column=2, rowspan=3, sticky='e') # self.verbose_window.pack(fill='both', expand=True) def insert(self, text): if self.verbose_window: self.verbose_window.insert("end", text + "\n") self.verbose_window.see('end') def save_room(self): self.title() def create_room(self, room=None): room_name = room if room is not None else self.room_entry.get() if any(room['name'] == room_name for room in self.rooms): messagebox.showwarning("Warning", "Room already exist.") elif len(room_name) not in range(3, 11, 1): messagebox.showwarning("Warning", "Room name must 3 to 10 character.") else: row = len(self.rooms) self.rooms.append({ 'name': room_name, 'connections_var': tk.StringVar(value='Connection(s) : 0'), # 'connections': 0, # 'clients': [], 'frame': [ tk.Frame(self.scrollframe.viewPort, highlightbackground='black', highlightthickness=1) ], 'data': [] }) self.rooms[row]['frame'].append( tk.ttk.Frame(self.rooms[row]['frame'][0])) self.rooms[row]['frame'].append( tk.ttk.Frame(self.rooms[row]['frame'][0])) for i, frame in enumerate(self.rooms[row]['frame']): if i == 0: frame.pack(fill='both', expand=1, padx=(5, 2), pady=(0, 5)) elif i == 1: frame.pack(side='left', pady=(5, 10)) else: frame.pack(side='right', pady=(5, 10)) self.rooms[row]['widgets'] = { 'label_name': tk.ttk.Label(self.rooms[row]['frame'][1], text=room_name), 'label_connection': tk.ttk.Label(self.rooms[row]['frame'][1], textvariable=self.rooms[row]['connections_var']), # 'enable': CustomButton(self.rooms[row]['frame'][2], text='\u23f5', width=40, height=30), # 'disable': CustomButton(self.rooms[row]['frame'][2], text='\u23f9', width=40, height=30, state='disabled'), 'chat': CustomButton(self.rooms[row]['frame'][2], text='\u2338', width=40, height=30), 'delete': CustomButton(self.rooms[row]['frame'][2], text='\u26a0', width=50, height=30), } self.rooms[row]['tips'] = { # 'enable_tip': ToolTip(self.rooms[row]['widgets']['enable'], 'Enable'), # 'disable_tip': ToolTip(self.rooms[row]['widgets']['disable'], 'Disable'), 'chat_tip': ToolTip(self.rooms[row]['widgets']['chat'], 'Chat Window'), 'delete_tip': ToolTip(self.rooms[row]['widgets']['delete'], 'Delete'), } for widget in self.rooms[row]['widgets']: if widget == 'label_connection' or widget == 'label_name': self.rooms[row]['widgets'][widget].pack(side='top') elif widget == 'delete': self.rooms[row]['widgets'][widget].pack(side='left', padx=(0, 10)) else: self.rooms[row]['widgets'][widget].pack(side='left') self.status['rooms'].set(f'{len(self.rooms)} Room(s)') def get_address(self): return (self.address.get(), int(self.port_entry.get())) def listen(self): try: self.listen_server() except socket.error as e: self.insert(str(e)) def listen_server(self): address = self.get_address() self.server = CreateServer(address) self.server.listen() self.status['server'].set(f"Listening") self.start_server(self.server) def start_server(self, server): self.room = HandleRooms(socket=self.server, window=self, name=self.room_entry.get()) self.room.start() def stop(self): try: self.store() self.server.stop() self.is_update = False self.status['server'].set("Inactive") except Exception as e: messagebox.showerror("Error", str(e)) def close(self): try: self.server.stop() self.mainwindow.destroy() except: self.mainwindow.destroy() def store(self): now = datetime.datetime.now() filename = f'{now.date()}' data = [{ key: value for key, value in room.items() if key == 'name' or key == 'data' } for room in self.rooms] if self.rooms: with bz2.BZ2File(filename + '.pbz2', 'w') as file: cPickle.dump(data, file) else: pass def restore(self): filename = os.listdir() # print(filename) if 'pbz2' in [ext.split('.')[-1] for ext in filename]: file, = [f for f in filename if '.pbz2' in f] # print(file) data = bz2.BZ2File(file, 'rb') data = cPickle.load(data) # print(data) [self.create_room(room['name']) for room in data] else: pass def toggle_verbose(self): state = self.status['verbose'].get() if state: self.__verbose_frame.pack(side='top', padx=(0, 5), pady=5, fill='both', expand=True) self.verbose_window.pack(fill='both', expand=True) else: self.__verbose_frame.pack_forget() self.verbose_window.pack_forget()
class MainGUI: def __init__(self): self.view_bool = False self.get_data(False) self.main_init() def main_init(self): self.gui_main() def main_refresh(self, all=False): self.get_data(all) if self.order_details == {}: self.listbox.delete(*self.listbox.get_children()) self.listbox.insert("", "end", text="--", values=("All orders cleared!", )) else: simple_details = [] for id in self.order_ids: string = "" for item in self.order_details.get(id): string += f"{item[1]} {item[0]}, " simple_details.append([ id, string[:40] + "..." if len(string) > 40 else string[:len(string) - 2] ]) self.listbox.delete(*self.listbox.get_children()) for simple_detail in simple_details: self.listbox.insert("", "end", text=simple_detail[0], values=(simple_detail[1], )) def gui_main(self): # Root Window Init self.window = ThemedTk(theme="radiance") self.window.geometry("435x340") self.window.title("Restaurant Management System") self.window.configure(background="#F6F4F2") self.window.resizable(0, 0) self.view_var = BooleanVar() # Heading ttk.Label(self.window, font=("default", 19, "bold"), text="Kitchen Manager").grid(row=0, column=0, sticky="w", padx=15) ttk.Separator(self.window, orient="horizontal").grid(row=1, columnspan=2, sticky="ew") # Tree View self.listbox = ttk.Treeview(self.window) self.listbox["columns"] = ("Details") self.listbox.heading("#0", text="Order No") self.listbox.heading("#1", text="Details") self.listbox.column("#0", minwidth=0, width=100) self.listbox.column("#1", minwidth=0, width=300) self.listbox.bind('<Double-1>', self.selectItem) ttk.Style().configure("Treeview", fieldbackground="#FEFEFE", background="#FEFEFE") self.main_refresh(self.view_bool) self.listbox.grid(row=2, column=0, sticky="nse", padx=15, pady=10) self.view_all = ttk.Checkbutton(self.window, text="View all orders", variable=self.view_var, command=self.cb).grid(row=3, column=0, sticky="w", padx=15) ttk.Button(self.window, text="Quit", command=self.window.destroy).grid(row=3, column=0, sticky="e", padx=15) self.window.mainloop() def cb(self): if self.view_var.get() == True: self.view_bool = True else: self.view_bool = False self.main_refresh(self.view_bool) def gui_details(self, id): # Open Details Window self.detail = ThemedTk(theme="radiance") self.detail.geometry("335x410") self.detail.title("Details") self.detail.configure(background="#F6F4F2") self.detail.resizable(0, 0) self.id = id # Heading ttk.Label(self.detail, font=("default", 19, "bold"), text="Orders").grid(row=0, column=0, sticky="w", padx=15) ttk.Separator(self.detail, orient="horizontal").grid(row=1, columnspan=2, sticky="ew", pady=(0, 5)) # Create Default Lables ttk.Label(self.detail, font=("default", 10, "bold"), anchor="e", width=18, text="Order ID : ").grid(row=2, column=0) ttk.Label(self.detail, font=("default", 10, "bold"), anchor="e", width=18, text="Customer Name : ").grid(row=3, column=0) # Create Buttons ttk.Button(self.detail, text="Mark Done", command=lambda: self.mark_done(self.id), width=33).grid(row=5, column=0, columnspan=2) ttk.Button( self.detail, text="Previous", command=lambda: self.refresh(self.detail, "prev", self.id)).grid( row=6, column=0, sticky="w", padx=15) ttk.Button( self.detail, text="Next", command=lambda: self.refresh(self.detail, "next", self.id)).grid( row=6, column=1, sticky="e", padx=15) self.tree = ttk.Treeview(self.detail) self.tree["columns"] = ("Quantity") self.tree.heading("#0", text="Name") self.tree.heading("#1", text="Quantity") self.tree.column("#0", minwidth=0, width=230) self.tree.column("#1", minwidth=0, width=70) def mark_done(self, id): conn = sqlite3.connect("login_db.db") query = f"UPDATE orders SET delivered=1 WHERE order_no={id};" conn.execute(query) conn.commit() self.detail.destroy() self.main_refresh(self.view_bool) def selectItem(self, a): curItem = self.listbox.focus() id = self.listbox.item(curItem).get("text") if id == "--": pass else: self.gui_details(id) self.refresh(self.detail, None, id) def refresh(self, detail, fun, id): # Determine Function of Refresh else do nothing orders = self.order_ids if fun == "next": # When at end, loop back to start if orders.index(id) + 1 == len(orders): id = orders[0] else: id = orders[orders.index(id) + 1] elif fun == "prev": id = orders[orders.index(id) - 1] self.id = id # Create Changing Value Lables conn = sqlite3.connect("login_db.db") query = f"SELECT * FROM orders WHERE order_no={id}" items = conn.execute(query) converted_item = tuple(items)[0] ttk.Label(self.detail, anchor="w", width=18, text=f"{converted_item[0]}").grid(row=2, column=1, padx=3) ttk.Label(self.detail, anchor="w", width=18, text=f"{converted_item[1]}").grid(row=3, column=1, padx=3) self.tree.delete(*self.tree.get_children()) for item in self.order_details.get(id): self.tree.insert("", "end", text=item[0], values=(item[1], )) for i in range(10): self.tree.insert("", "end", text="", values=("", )) self.tree.grid(row=4, column=0, columnspan=2, padx=15, pady=10) self.detail.mainloop() def get_data(self, all): self.order_details = km.db_retrieve(all) self.order_ids = km.order_ids(all)
class TestThemedTk(unittest.TestCase): def setUp(self): self.tk = ThemedTk() def tearDown(self): self.tk.destroy() def test_themes_available(self): available_themes = self.tk.get_themes() for theme in THEMES: if theme not in available_themes: raise AssertionError("Theme {} not available".format(theme)) def test_theme_setting(self): button = ttk.Button(self.tk) label = ttk.Label(self.tk) button.pack() label.pack() self.tk.update() for theme in self.tk.get_themes(): self.tk.set_theme(theme) self.tk.update() def test_custom_theme(self): if not self.tk.png_support: return for theme in self.tk.pixmap_themes: tk = ThemedTk() tk.set_theme_advanced(theme, brightness=0.2, saturation=1.4, hue=1.8) tk.destroy() return def test_toplevel_hook(self): __init__toplevel = tk.Toplevel.__init__ self.tk.set_theme("black", True, False) self.assertNotEqual(__init__toplevel, tk.Toplevel.__init__) top = tk.Toplevel(self.tk) color = ttk.Style(self.tk).lookup("TFrame", "background") self.assertIsNotNone(color) self.assertEqual(top.cget("background"), color) top.destroy() def test_tk_background(self): self.tk.config(background="white") self.tk.set_theme("black", False, True) self.assertNotEqual(self.tk.cget("background"), "white") def test_config_cget(self): self.tk.config(theme="equilux") self.assertEqual(self.tk.cget("theme"), self.tk.current_theme) self.assertEqual(self.tk.cget("theme"), "equilux") self.tk.config(themebg=True) self.assertTrue(self.tk.cget("themebg")) before = self.tk.cget("bg") self.tk.config(themebg=False) self.assertFalse(self.tk.cget("themebg")) after = self.tk["bg"] self.assertNotEqual(before, after) self.tk.config(toplevel=False) self.assertFalse(self.tk.cget("toplevel")) orig = tk.Toplevel.__init__ self.tk["toplevel"] = True self.assertTrue(self.tk.cget("toplevel")) self.assertNotEqual(orig, tk.Toplevel.__init__) self.tk.configure(toplevel=False) self.assertEqual(tk.Toplevel.__init__, orig)
nb.add(measurement_tab, text='Measurements') # displaying SOC soc = 50 soc_label = ttk.Label(hometab, text=soc) soc_label.pack() ttk.Button # buttons for choosing mode b1 = ttk.Button(hometab, text='Eco mode',command=lambda : choose_mode(0)) b1.pack(anchor='nw', padx=3, pady=2) b2 = ttk.Button(hometab, text='Normal mode', command=lambda: choose_mode(1)) b2.pack(anchor='nw', padx=3, pady=2) b3 = ttk.Button(hometab, text='Sport mode', command=lambda: choose_mode(2)) b3.pack(anchor='nw', padx=3, pady=2) q_butt = tk.PhotoImage(file=r"C:\dev\proj4\gui\modules\resized.png") lol_butt = tk.PhotoImage(file=r"C:\dev\proj4\gui\modules\lol.png") quit_button = ttk.Button(hometab, text='Closes application', command=lambda: m.destroy(), image=q_butt) quit_button.pack(anchor='se', padx=3, pady=3, side="bottom") lol_button = ttk.Button(hometab, text='Closes application', command=lambda: m.destroy(), image=lol_butt) lol_button.pack(anchor='n', padx=3, pady=3, side="top") m.mainloop() # #slave.readfrom(master, 8, stop=True)
class App: def __init__(self): self.root = ThemedTk() self.root.title("Static Map App") self.WIDTH = 1600 self.HEIGHT = 600 self.size = 600 self.root.geometry("1400x800") self.root.resizable(0, 0) ttk.Style().theme_use("black") ttk.Style().configure("TButton", font="OpenSans 13 bold", anchor="center", background="#47d1ff", foreground="white") ttk.Style().configure("TLabel") ttk.Style().configure("TEntry") ttk.Style().configure("TFrame", relief="ridge") self.frames() self.labels() self.entrys() self.buttons() self.mainloop() def frames(self): self.window_frame = ttk.Frame(self.root) self.window_frame.place(relheight=1, relwidth=1) self.info_frame = ttk.Frame(self.root) self.info_frame.place(relx=0.015, rely=0.025, relheight=0.95, relwidth=0.3) self.picture_frame = ttk.Frame(self.root) self.picture_frame.place(relx=0.4, rely=0.025, relheight=0.95, relwidth=0.583) def labels(self): self.key_label = ttk.Label(self.info_frame, text="API-Key :", font="OpenSans 13 bold") self.key_label.place(relx=0.01, rely=0.1) self.location_label = ttk.Label(self.info_frame, text="Location :", font="OpenSans 13 bold") self.location_label.place(relx=0.01, rely=0.17) self.zoom_label = ttk.Label(self.info_frame, text="Zoom Level of the Map :", font="OpenSans 13 bold") self.zoom_label.place(relx=0.01, rely=0.24) self.type_label = ttk.Label(self.info_frame, text="Type of base map :", font="OpenSans 13 bold") self.type_label.place(relx=0.01, rely=0.31) self.scale_label = ttk.Label(self.info_frame, text="Scalebar :", font="OpenSans 13 bold") self.scale_label.place(relx=0.01, rely=0.38) self.title_label = ttk.Label(self.info_frame, text="Static Map Search", font="OpenSans 15 bold", background="#47d1ff", relief="ridge", anchor="center") self.title_label.place(relx=0.01, rely=0.01, relheight=0.05, relwidth=0.97) self.location_pic_title = ttk.Label(self.picture_frame, text="Static Picture", font="OpenSans 15 bold", background="#47d1ff", relief="ridge", anchor="center") self.location_pic_title.place(relx=0.01, rely=0.01, relheight=0.05, relwidth=0.98) self.picture_label = ttk.Label(self.picture_frame, relief="ridge") self.picture_label.place(relx=0.01, rely=0.067, relheight=0.92, relwidth=0.98) self.title2_label = ttk.Label(self.info_frame, text="Static Route Search", font="OpenSans 15 bold", background="#47d1ff", relief="ridge", anchor="center") self.title2_label.place(relx=0.01, rely=0.45, relheight=0.05, relwidth=0.97) self.key2_label = ttk.Label(self.info_frame, text="API-Key :", font="OpenSans 13 bold") self.key2_label.place(relx=0.01, rely=0.54) self.location2_label = ttk.Label(self.info_frame, text="Start Location :", font="OpenSans 13 bold") self.location2_label.place(relx=0.01, rely=0.61) self.location3_label = ttk.Label(self.info_frame, text="End Location :", font="OpenSans 13 bold") self.location3_label.place(relx=0.01, rely=0.68) self.zoom2_label = ttk.Label(self.info_frame, text="Zoom Level of the Map :", font="OpenSans 13 bold") self.zoom2_label.place(relx=0.01, rely=0.75) self.type2_label = ttk.Label(self.info_frame, text="Type of base map :", font="OpenSans 13 bold") self.type2_label.place(relx=0.01, rely=0.82) self.scale2_label = ttk.Label(self.info_frame, text="Scalebar :", font="OpenSans 13 bold") self.scale2_label.place(relx=0.01, rely=0.89) def entrys(self): self.key_entry = ttk.Entry(self.info_frame, font="OpenSans 10 bold") self.key_entry.place(relx=0.2, rely=0.1, relwidth=0.78) self.location_entry = ttk.Entry(self.info_frame, font="OpenSans 10 bold") self.location_entry.place(relx=0.21, rely=0.17, relwidth=0.767) self.zoom_entry = ttk.Entry(self.info_frame, font="OpenSans 10 bold") self.zoom_entry.place(relx=0.47, rely=0.24, relwidth=0.505) self.type_entry = ttk.Entry(self.info_frame, font="OpenSans 10 bold") self.type_entry.place(relx=0.38, rely=0.31, relwidth=0.6) self.scalebar_entry = ttk.Entry(self.info_frame, font="OpenSans 10 bold") self.scalebar_entry.place(relx=0.21, rely=0.38, relwidth=0.767) self.key2_entry = ttk.Entry(self.info_frame, font="OpenSans 10 bold") self.key2_entry.place(relx=0.2, rely=0.54, relwidth=0.78) self.location2_entry = ttk.Entry(self.info_frame, font="OpenSans 10 bold") self.location2_entry.place(relx=0.317, rely=0.61, relwidth=0.66) self.location3_entry = ttk.Entry(self.info_frame, font="OpenSans 10 bold") self.location3_entry.place(relx=0.297, rely=0.68, relwidth=0.68) self.zoom2_entry = ttk.Entry(self.info_frame, font="OpenSans 10 bold") self.zoom2_entry.place(relx=0.47, rely=0.75, relwidth=0.505) self.type2_entry = ttk.Entry(self.info_frame, font="OpenSans 10 bold") self.type2_entry.place(relx=0.38, rely=0.82, relwidth=0.6) self.scalebar2_entry = ttk.Entry(self.info_frame, font="OpenSans 10 bold") self.scalebar2_entry.place(relx=0.21, rely=0.89, relwidth=0.767) def buttons(self): self.get_data = ttk.Button(self.info_frame, text="Get Location", command=lambda: self.get_location()) self.get_data.place(relx=0.14, rely=0.94, relheight=0.05, relwidth=0.7) self.information_button = ttk.Button(self.root, text="Info", command=lambda: self.show_info()) self.information_button.place(relx=0.322, rely=0.025, relwidth=0.07, relheight=0.2) self.About_button = ttk.Button(self.root, text="About") self.About_button.place(relx=0.322, rely=0.395, relwidth=0.07, relheight=0.2) self.Exit_button = ttk.Button(self.root, text="Exit", command=lambda: self.root.destroy()) self.Exit_button.place(relx=0.322, rely=0.774, relwidth=0.07, relheight=0.2) def get_location(self): try: self.key = self.key_entry.get() self.location = self.location_entry.get() self.scalebar = self.scalebar_entry.get() self.zoom = self.zoom_entry.get() self.type = self.type_entry.get() self.informations = (self.key, self.location, self.scalebar, self.zoom, self.type) self.url = "https://www.mapquestapi.com/staticmap/v5/map?key=%s¢er=%s&scalebar=%s&zoom=%s&type=%s&size=796,700" % ( self.informations) #webbrowser.open_new_tab('%s' % self.url) self.request = requests.get(self.url) with open("static_map_pic.png", "wb") as f: f.write(self.request.content) self.image = ImageTk.PhotoImage(file="static_map_pic.png") self.location_pic_title.configure(text="Static Map Picture") self.picture_label.configure(image=self.image) except: self.key2 = self.key2_entry.get() self.location2 = self.location2_entry.get() self.location3 = self.location3_entry.get() self.scalebar2 = self.scalebar2_entry.get() self.zoom2 = self.zoom2_entry.get() self.type2 = self.type2_entry.get() self.informations2 = (self.key2, self.location2, self.location3, self.scalebar2, self.zoom2, self.type2) self.url2 = "https://www.mapquestapi.com/staticmap/v5/map?key=%s&start=%s&end=%s&scalebar=%s&zoom=%s&type=%s&size=796,700" % ( self.informations2) # webbrowser.open_new_tab('%s' % self.url) self.request2 = requests.get(self.url2) with open("static_route_pic.png", "wb") as f: f.write(self.request2.content) self.image2 = ImageTk.PhotoImage(file="static_route_pic.png") self.location_pic_title.configure(text="Static Route Picture") self.picture_label.configure(image=self.image2) def show_info(self): messagebox.showinfo( "Search input Guide", "###Static Map Search###\n" "API-Key = Key\n" "Example: developer.mapquest.com\n" "Location: = Location\n" "Example: Berlin\n" "Zoom Level of the Map: 0-20\n" "Example: 15\n" "Type of base map = map, sat, hyb, light and dark\n" "Example: hyb\n" "Scalebar = true or false\n" "Example: true\n" "\n" "###Static Route Search###\n" "API-Key = Key\n" "Example: developer.mapquest.com\n" "Start Location = Start Location\n" "Example: Hamburg\n" "End Location = End Location\n" "Example: Berlin\n" "Zoom Level of the Map = 0-20\n" "Example: 13\n" "Type of base map = map, sat, hyb, light and dark\n" "Example : map\n" "Scalebar = true or false\n" "Example: false\n") def mainloop(self): self.root.mainloop()
def main(): config_exist() read_config() app = ThemedTk(theme="arc") app.config(bg="#F5F6F7") frame = Frame(app) app.title("Steam Account Switcher") accounts_label = ttk.Label(app, text="Accounts", font="Helvetica") accounts_label.place(x=95, y=10) accounts_label.config(background="#F5F6F7", foreground="#6A626D") ttk.Separator(app, orient="horizontal").place(width=330, y=37) def callback(url): webbrowser.open_new(url) author = ttk.Label(app, text=" @wadforth ", font=("Helvetica", 10), cursor="hand2") author.pack(side=RIGHT, anchor=SE) author.config(background="#F5F6F7", foreground="#6A626D") author.bind("<Button-1>", lambda e: callback("http://www.github.com/wadforth")) y_placement = 50 for item in account_list: button = ttk.Button( app, width="30", text=item, command=lambda x=item: [ x, os.system("taskkill /im steam.exe /F"), subprocess.call( "powershell.exe reg add HKCU\Software\Valve\Steam /v AutoLoginUser /t REG_SZ /d " + x + " /f" ), subprocess.call( "powershell.exe reg add HKCU\Software\Valve\Steam /v RememberPassword /t REG_DWORD /d 1 /f" ), os.system('start "" steam://open/main'), app.destroy(), ], ) button.place(y=y_placement, x=25) y_placement += 40 ttk.Button( app, text="Edit", width=4, command=lambda: [ app.destroy(), os.remove(filepath), os.rmdir(path), first_time(), ], ).place(x=190, y=5) if len(account_list) == 5: app.geometry("250x260") elif len(account_list) == 4: app.geometry("250x220") elif len(account_list) == 3: app.geometry("250x180") else: app.geometry("250x140") app.resizable(False, False) app.mainloop()
def first_time(): app = ThemedTk(theme="arc") app.config(bg="#F5F6F7") app.title("Setup") app.geometry("250x260") accounts_label = ttk.Label(app, text="Accounts - Setup", font="Helvetica") accounts_label.place(x=65, y=10) accounts_label.config(background="#F5F6F7", foreground="#6A626D") ttk.Separator(app, orient="horizontal").place(width=330, y=37) account1 = StringVar() account2 = StringVar() account3 = StringVar() account4 = StringVar() account5 = StringVar() entry1 = ttk.Entry(app, textvariable=account1, justify=CENTER).place( width=200, x=40, y=57 ) entry2 = ttk.Entry(app, textvariable=account2, justify=CENTER).place( width=200, x=40, y=87 ) entry3 = ttk.Entry(app, textvariable=account3, justify=CENTER).place( width=200, x=40, y=117 ) entry4 = ttk.Entry(app, textvariable=account4, justify=CENTER).place( width=200, x=40, y=147 ) entry5 = ttk.Entry(app, textvariable=account5, justify=CENTER).place( width=200, x=40, y=177 ) account1_label = ttk.Label(app, text="#1", font="Helvetica") account1_label.place(x=15, y=59) account1_label.config(background="#F5F6F7", foreground="#6A626D") account2_label = ttk.Label(app, text="#2", font="Helvetica") account2_label.place(x=15, y=89) account2_label.config(background="#F5F6F7", foreground="#6A626D") account3_label = ttk.Label(app, text="#3", font="Helvetica") account3_label.place(x=15, y=119) account3_label.config(background="#F5F6F7", foreground="#6A626D") account4_label = ttk.Label(app, text="#4", font="Helvetica") account4_label.place(x=15, y=149) account4_label.config(background="#F5F6F7", foreground="#6A626D") account5_label = ttk.Label(app, text="#5", font="Helvetica") account5_label.place(x=15, y=179) account5_label.config(background="#F5F6F7", foreground="#6A626D") config_label = ttk.Label(app, text="Config Location", font=("Helvetica", 10)) config_label.place(x=17, y=215) config_label.config(background="#F5F6F7", foreground="#6A626D") config_location = ttk.Label(app, text=path, font=("Helvetica", 7)) config_location.place(x=15, y=239) config_location.config(background="#F5F6F7", foreground="#6A626D") def write_file(): with open(filepath, "w") as file: file.write(account1.get() + "\n") if len(account2.get()) != 0: file.write(account2.get() + "\n") if len(account3.get()) != 0: file.write(account3.get() + "\n") if len(account4.get()) != 0: file.write(account4.get() + "\n") if len(account5.get()) != 0: file.write(account5.get()) ttk.Button( app, text="Save", width=10, command=lambda: [ os.makedirs(path), os.open(filepath, os.O_CREAT), write_file(), app.destroy(), main(), ], ).place(x=155, y=205) ttk.Entry(app) app.resizable(False, False) app.mainloop()
class AppEntrance(object): """进行打包的可视化外壳""" prograss_int = 0 def __init__(self): """ if exist_ttkthemes: # self.rootwindow = tk.Tk() self.rootwindow = ThemedTk(theme="arc") else: self.rootwindow = tk.Tk() self.rootwindow.title("") """ if exist_ttkthemes: # self.rootwindow = tk.Tk() self.rootwindow = ThemedTk(theme="arc") else: self.rootwindow = tk.Tk() self.rootwindow.title("") # self.rootwindow = tk.Tk() # self.rootwindow.title("") # self.rootwindow.title("GISPOT") # self.rootwindow.update_idletasks() # self.rootwindow.overrideredirect(True) # self.rootwindow.tk_setPalette(background="#f5f6f7") # 一次性修改所有背景颜色 newGUI.screen_cetre(self.rootwindow, width=hyini.width, height=hyini.height) self.rootwindow.iconbitmap(default=icon) self.rootwindow.resizable(1, 1) # self.rootwindow.attributes('-topmost', 0) self.gradient_bar() self.upgrade_from_github() # ------------------------------------- # 主界面左侧图标工具栏 # Frame的实际大小不仅仅受width控制,如果其中有其它部件, # 以其它部件大小为准 self.main_face = tk.Frame(self.rootwindow, relief="sunken", width=55, height=600, bd=1) self.main_face.pack(side="left", fill="both", expand=True) # self.toolbar.place(x=0,y=0) # 初始界面右侧的交互界面的框架 interface_frame # self.interface_frame = tk.Frame(self.rootwindow, relief="groove",width= 900, height = 600) # self.interface_frame.pack(side="right", expand=True, fill="both") # self.interface_frame.place(x=55,y=0) # 绑定退出弹窗与退出功能,实现退出功能 self.rootwindow.protocol("WM_DELETE_WINDOW", self.on_closing) # 界面 # self.run_menu() # self.run_toolbar_viewer() tnb = interface.ttknotebook(self.main_face) interface.ToolSet(tnb.notebook2) self.rootwindow.mainloop() def gradient_bar(self): self.gradient_canv = newGUI.GradientCanvas(self.rootwindow, "#ffc851", "#808000", relief="flat") self.gradient_canv.pack(side="bottom", anchor=tk.SE, fill="x") self.gradient_canv.create_text(32, 10, text="gispot 1") def upgrade_from_github(self): def open_u(): update_url = r"https://github.com/hygnic/GisCat/archive/master.zip" weberopen(update_url, new=0, autoraise=True) # self.image_octacat = tk.PhotoImage(file=gispotpath.PngIcon.github) self.image_octacat = ImageTk.PhotoImage( Image.open(gppath.PngIcon.github)) ap_button = newGUI.HoverButton(master=self.gradient_canv, command=open_u, bd=2, image=self.image_octacat, width=15, height=15) # ap_button = ttk.Button(master=self.gradient_canv, # command=open_u, # image=self.image_octacat) ap_button.pack(side='top', expand='yes', anchor="se") # ---------------------------------------- def button_config(self): def open_u(): import webbrowser update_url = r"https://github.com/hygnic/GisCat/archive/master.zip" webbrowser.open(update_url, new=0, autoraise=True) ap_button = ttk.Button(text=u"获取更新", command=open_u) ap_button.pack(side='top', expand='yes', anchor="se") def on_closing(self): # 退出确认功能,防止误触发 if tkMessageBox.askokcancel("Quit", " Do you want to quit?"): self.rootwindow.destroy()
class Cadastro_Produtos(): """ Classe principal - chama a janela window com todos os widgets. """ db_name = 'database.db' def __init__(self): """ Inicializador da janela principal. """ self.window = ThemedTk(theme='plastik') self.window.title("Cadastro de Produtos em Tkinter") self.window.resizable(0, 0) self.window.geometry(self.centraliza_window(568, 500)) self.frame_principal = tk.Frame(self.window) self.frame_principal.pack(fill=BOTH) self.label_espaco = tk.Label(self.frame_principal) self.label_espaco.grid(row=0, column=1, pady=4) self.label_nome = tk.Label(self.frame_principal, text='Nome do produto:') self.label_nome.grid(row=1, column=1, padx=10) self.entry_nome = tk.Entry(self.frame_principal, width=45) self.entry_nome.grid(row=1, column=2, pady=4) self.entry_nome.focus() self.label_preco = tk.Label(self.frame_principal, text='Preço do produto:') self.label_preco.grid(row=2, column=1, padx=10) self.entry_preco = tk.Entry(self.frame_principal, width=10) self.entry_preco.grid(row=2, column=2, pady=4, sticky=W) self.button_cadastrar = tk.Button(self.frame_principal, text='CADASTRAR', width=15, command=lambda: self.adicionar(self)) self.button_cadastrar.grid(row=2, column=2, padx=5, pady=15, sticky=E) self.button_cadastrar.bind('<Return>', self.adicionar) self.separator = tk.Separator(self.window, orient='horizontal') self.separator.pack(fill='x') self.frame_pesquisar = tk.Frame(self.window) self.frame_pesquisar.pack(fill='x') self.frame_espaco = tk.Frame(self.frame_pesquisar) self.frame_espaco.pack(pady=30) self.label_pesquisar = tk.Label(self.frame_pesquisar, text='Pesquisar:').pack(side=LEFT, padx=20) self.entry_pesquisar = tk.Entry(self.frame_pesquisar, width=30) self.entry_pesquisar.pack(pady=10, side=LEFT) self.button_pesquisar = tk.Button(self.frame_pesquisar, text='Ok', command=self.pesquisar) self.button_pesquisar.pack(side=LEFT, padx=5) self.button_limpar = tk.Button(self.frame_pesquisar, text='Limpar', command=self.limpar) self.button_limpar.pack(side=LEFT, padx=5) self.frame_treeview = tk.Frame(self.window) self.frame_treeview.pack(fill='x') self.treeview = tk.Treeview(self.frame_treeview, columns=('id', "produto", 'preco'), show='headings') self.treeview.column('id', minwidth=0, width=30) self.treeview.column('produto', minwidth=0, width=250) self.treeview.column('id', minwidth=0, width=100) self.treeview.heading('id', text='ID') self.treeview.heading('produto', text='PRODUTO') self.treeview.heading('preco', text='PREÇO') self.treeview.grid(row=1, column=1) # scrollbar self.scrollbar = tk.Scrollbar(self.frame_treeview, orient="vertical", command=self.treeview.yview) self.scrollbar.grid(row=1, column=2, ipady=76) self.treeview.configure(yscrollcommand=self.scrollbar.set) self.frame_botoes = tk.Frame(self.window) self.frame_botoes.pack(side=BOTTOM, pady=10) self.button_excluir = tk.Button(self.frame_botoes, text='EXCLUIR', width=15, command=self.deletar) self.button_excluir.pack(side=LEFT) self.button_editar = tk.Button(self.frame_botoes, text='EDITAR', width=15, command=self.window_editar) self.button_editar.pack(side=LEFT, padx=5) self.button_sair = tk.Button(self.frame_botoes, text='SAIR', width=15, command=lambda: self.window.destroy()) self.button_sair.pack(side=LEFT) self.visualizar_registros() self.window.mainloop() def executa_banco(self, query, parameters=()): """ Executa o banco de dados, o mesmo leva duas variáveis. query - instrução para executar o banco de dados, ex.: 'SELECT * FROM product ORDER BY id'. parameters - recebe os parametros para a execução da query; parameters é uma tupla. """ with sqlite3.connect(self.db_name) as conn: cursor = conn.cursor() query_result = cursor.execute(query, parameters) conn.commit() return query_result def visualizar_registros(self): """ Pega todos os registros e coloca dentro da Treeview """ records = self.treeview.get_children() for element in records: self.treeview.delete(element) query = 'SELECT * FROM product ORDER BY id' db_rows = self.executa_banco(query) for row in db_rows: self.treeview.insert('', 'end', text=row[0], values=(row[0], row[1], row[2])) self.entry_pesquisar.delete(0, END) def validar(self): """ Verifica se as duas entradas não estão vazias """ return len(self.entry_nome.get()) != 0 and len( self.entry_preco.get()) != 0 def pesquisar(self): """ Realiza a pesquisa usando o método LIKE do SQL """ parameters = (self.entry_pesquisar.get() + '%', ) query = 'SELECT * FROM product WHERE name LIKE ?' db_rows = self.executa_banco(query, parameters) records = self.treeview.get_children() for element in records: self.treeview.delete(element) for row in db_rows: self.treeview.insert('', 'end', text=row[0], values=(row[0], row[1], row[2])) def limpar(self): """ Limpa a entry pesquisar. """ self.entry_pesquisar.delete(0, END) self.visualizar_registros() def adicionar(self, event): """ Adiciona nova entrada no banco de dados. """ if self.validar(): query = 'INSERT INTO product VALUES(NULL, ?, ?)' name = self.entry_nome.get().title() price = self.entry_preco.get() parameters = (name, price) self.executa_banco(query, parameters) self.entry_nome.delete(0, END) self.entry_preco.delete(0, END) self.mensagem( 'info', 'Atenção', 'Produto {} cadastrado:'.format(self.entry_nome.get())) else: self.mensagem('erro', 'Atenção', 'Favor preencher todos os campos.') self.entry_nome.focus() self.entry_nome.focus() self.visualizar_registros() def deletar(self): """ Deleta o item selecionado na Treeview. """ if not self.treeview.item(self.treeview.selection())['text']: self.mensagem('erro', 'Atenção', 'Selecione um item para excluir.') else: name_item = self.treeview.item(self.treeview.selection())['values'] msgBox = mb.askquestion( 'Atenção', 'Tem certeza que deseja excluir "{}"? Este processo é irreversível.' .format(name_item[1])) if msgBox == 'no': pass else: id = self.treeview.item(self.treeview.selection())['text'] query = 'DELETE FROM product WHERE id = ?' self.executa_banco(query, (id, )) self.visualizar_registros() self.mensagem('info', 'Atenção', '{} deletado.'.format(name_item[1])) def window_editar(self): """ Chama a janela de edição. """ if not self.treeview.item(self.treeview.selection())['text']: self.mensagem('erro', 'Atenção', 'Selecione um item para editar.') else: selecao = self.treeview.item(self.treeview.selection())['values'] id = selecao[0] name = selecao[1] price = selecao[2] self.edit_wind = Toplevel() self.edit_wind.title('Editando "{}"'.format(name)) self.edit_wind.geometry('550x170') self.edit_wind.transient(self.window) self.edit_wind.focus_force() self.edit_wind.grab_set() self.frame_principal = tk.Frame(self.edit_wind) self.frame_principal.pack(fill=BOTH) self.label_espaco = tk.Label(self.frame_principal) self.label_espaco.grid(row=0, column=1, pady=4) self.label_nome = tk.Label(self.frame_principal, text='Nome do produto:') self.label_nome.grid(row=1, column=1, padx=10) self.entry_nome = tk.Entry(self.frame_principal, width=45) self.entry_nome.grid(row=1, column=2, pady=4) self.entry_nome.focus() self.label_preco = tk.Label(self.frame_principal, text='Preço do produto:') self.label_preco.grid(row=2, column=1, padx=10) self.entry_preco = tk.Entry(self.frame_principal, width=10) self.entry_preco.grid(row=2, column=2, pady=4, sticky=W) self.button_salvar = tk.Button(self.frame_principal, text='SALVAR', width=15, command=self.editar_registros) self.button_salvar.grid(row=5, column=1) #self.button_salvar.bind('<Return>', self.editar_registros) self.button_cancelar = tk.Button( self.frame_principal, text='CANCELAR', width=15, command=lambda: self.edit_wind.destroy()) self.button_cancelar.grid(row=5, column=2, pady=30, sticky=W) self.entry_nome.insert(0, name) self.entry_preco.insert(0, price) def editar_registros(self): """ Substitui no banco de dados o registro anterior selecionado pelo registro editado. """ selecao = self.treeview.item(self.treeview.selection())['values'] id = selecao[0] name = selecao[1] old_price = selecao[2] new_name = self.entry_nome.get().title() new_price = self.entry_preco.get() parameters = (new_name, new_price, name, old_price) query = 'UPDATE product SET name=?, price=? WHERE name=? AND price=?' self.executa_banco(query, parameters) self.edit_wind.destroy() self.mensagem('info', 'Atenção', 'Cadastro "{}" editado com sucesso!'.format(name)) self.visualizar_registros() def mensagem(self, tipoMsg, title, msg): """ Exibe mensagens de alerta ao usuário, o mesmo pode ser de erro ou atenção. """ if tipoMsg == "erro": mb.showerror(title, msg) else: mb.showinfo(title, msg) def centraliza_window(self, comprimento, altura): """ Dimensiona e centraliza a janela. recebe duas variáveis: comprimento - a largura da janela altura - a altura da janela """ # Dimensões da janela self.comprimento = comprimento self.altura = altura # Resolução da tela self.comprimento_screen = self.window.winfo_screenwidth() self.altura_screen = self.window.winfo_screenheight() # Posição da janela self.pos_x = (self.comprimento_screen / 2) - (self.comprimento / 2) self.pos_y = (self.altura_screen / 2) - (self.altura / 2) - 10 self.window.geometry("{}x{}+{}+{}".format( int(self.comprimento), int(self.altura), int(self.pos_x), int(self.pos_y), ))
if __name__ == '__main__': master = ThemedTk(theme="plastik") master.geometry('1280x990') master.title("Translator") # the icon master.iconbitmap('transicon.ico') # internet permission try: if not (ur.urlopen('https://google.com')): raise ConnectionError('No Internet connection') except: # exception handling master.withdraw() messagebox.showwarning(title='Error', message='No Internet Connection') master.destroy() exit(-1) # reading json file with open('languages.json', 'r') as j: data = json.load(j) swapped_data = dict((v, k) for k, v in data.items()) text = ttk.Label(master, text='Enter the word: ', font='sansSerif').grid(row=0, column=0) # entry of word to be translated entry = ttk.Entry(master) entry.grid(row=0, column=1) ttk.Label(master, text='Choose the language: ', font='sansSerif').grid(row=1, column=0)
class MusicPlayer(): def __init__(self): self.musicFullPaths = {} self.musicFilename = {} self.muted = FALSE self.musicStatus = False self.volume = 1 self.fileName = "s" self.statusText = "" self.mutedButton = False self.stoped = TRUE self.threadExit = TRUE self.musicIndex = 0 super().__init__() # ITFT1 plastik self.windows = ThemedTk(theme="itft1") windows = self.windows windows.geometry('920x350') windows.resizable(0, 0) windows.title("Music Player") windows.iconbitmap(MAIN_DIR + "images/main.ico") # windows.configure(background="red") windows.grid_rowconfigure(0, weight=1) windows.grid_columnconfigure(0, weight=1) self.mainFrame = Frame(windows) self.mainFrame.pack(fill=BOTH) self.rightFrame = Frame(self.mainFrame) self.rightFrame.pack(side=RIGHT, padx=10, pady=10) self.leftFrame = Frame(self.mainFrame) self.leftFrame.pack(padx=40, pady=10) self.topFrame = Frame(self.rightFrame) self.topFrame.pack(padx=10, pady=10) self.middleFrame = Frame(self.rightFrame) self.middleFrame.pack(padx=10, pady=10) # self.bottomFrame = Frame(self.mainFrame) # self.bottomFrame.pack(side=BOTTOM, fill=X) self.createIcon(windows) # მუდვილი ციკლი ფლეირეის დახურვამდე windows.mainloop() def createIcon(self, windows): menubar = Menu(windows) windows.config(menu=menubar) subMenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="File", menu=subMenu) subMenu.add_command(label="Import/Open", command=self.importFile) subMenu.add_command(label="Exit", command=self.exitWindows) subMenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Help", menu=subMenu) subMenu.add_command(label="About Us", command=self.messageBox) subMenu.add_command(label="Exit", command=self.exitWindows) playImage = PhotoImage(file=MAIN_DIR + "images//play.png") playButton = ttk.Button(self.middleFrame, image=playImage, command=self.playMusic) playButton.image = playImage playButton.grid(row=0, column=1, padx=10, pady=10) stopImage = PhotoImage(file=MAIN_DIR + "images/stop.png") stopButton = ttk.Button(self.middleFrame, image=stopImage, command=self.stopMusic) stopButton.image = stopImage stopButton.grid(row=0, column=2, padx=10, pady=10) pauseImage = PhotoImage(file=MAIN_DIR + "images/pause.png") pauseButton = ttk.Button(self.middleFrame, image=pauseImage, command=self.pauseMusic) pauseButton.image = pauseImage pauseButton.grid(row=0, column=3, padx=10, pady=10) resetImage = PhotoImage(file=MAIN_DIR + "images/reset.png") resetButton = ttk.Button(self.middleFrame, image=resetImage, command=self.resetMusic) resetButton.image = resetImage resetButton.grid(row=0, column=4, padx=10, pady=10) self.unmuteImage = PhotoImage(file=MAIN_DIR + "images/sound.png") self.mutedButton = ttk.Button(self.middleFrame, image=self.unmuteImage, command=self.muteMusic) self.mutedButton.image = self.unmuteImage self.mutedButton.grid(row=0, column=5, padx=10, pady=10) self.volumeControl = ttk.Scale(self.rightFrame, from_=0, to=100, orient=HORIZONTAL, command=self.setVolume) self.volumeControl.set(100) self.volumeControl.pack(padx=10, pady=10) self.statusText = ttk.Label(self.windows, text="Start", anchor=E) self.statusText.pack(side=BOTTOM) statusBar2 = ttk.Label(self.windows, text="Welcome! ©COPYRIGHT 2020", relief=SUNKEN).pack(side=BOTTOM, fill=X) self.lb = ttk.Label(self.topFrame, text="--:--") self.lb.pack(pady=10, padx=10) self.lb2 = ttk.Label(self.topFrame, text="Time : --:--") self.lb2.pack(pady=10, padx=10) self.playListBox = Listbox(self.leftFrame) self.playListBox.pack(fill=X, expand=True, padx=10, pady=10) self.musicAddButton = ttk.Button(self.leftFrame, text="Add Track", command=self.importFile) self.musicAddButton.pack(side=LEFT, pady=10, padx=10) self.musicRemoveButton = ttk.Button( self.leftFrame, text="Remove Track", command=self.musicDeteleFromPlaylist) self.musicRemoveButton.pack(pady=10, padx=10) windows.wm_protocol("WM_DELETE_WINDOW", self.exitWindows) def exitWindows(self): print("closed") self.stopMusic() self.threadExit = FALSE self.windows.destroy() def playMusic(self): filePath = self.cursorSelection() mixer.init() if self.musicStatus and self.stoped: # print(self.stoped) mixer.music.play() self.stoped = FALSE self.threadExit = FALSE self.musicInfo() self.threadExit = TRUE try: paused except NameError as e: try: if filePath: mixer.music.load(filePath) self.statusText[ 'text'] = f'Playing :{os.path.basename(self.fileName)}' mixer.music.set_volume(self.volume) mixer.music.play() self.musicStatus = True self.musicInfo() except Exception as e: # print(e) tkinter.messagebox.showwarning( "Warrning : File Could't Found ! ", "Please import music file first and then try again. ") else: self.unpauseMusic() self.threadExit = FALSE self.musicInfo() self.threadExit = TRUE def stopMusic(self): self.threadExit = FALSE try: mixer.music.stop() self.stoped = TRUE self.musicInfo() except Exception as e: pass self.statusText['text'] = "..." def pauseMusic(self): if self.musicStatus: self.threadExit = FALSE global paused paused = TRUE mixer.music.pause() self.statusText['text'] = "Paused " self.musicInfo() def unpauseMusic(self): if self.musicStatus: mixer.music.unpause() self.statusText[ 'text'] = f'Playing :{os.path.basename(self.fileName)}' self.threadExit = FALSE self.musicInfo() self.threadExit = TRUE # def import_music(self): # ttk.Label(self.windows, text="ss").grid(row=0, column=1) def setVolume(self, val): if self.musicStatus: self.volume = float(val) / 100 mixer.music.set_volume(self.volume) else: self.volume = float(val) / 100 def messageBox(self): # აქვს სხვადასხვა ტიპის შეტყობინება warrning, error, info... tkinter.messagebox.showinfo("About Us", "this is 4th grade student project.") def importFile(self): self.fileName = tkinter.filedialog.askopenfilename( filetypes=[("Media files", "*.acc *.mp3 *.wav *.wma")]) self.addPlaylist() # print(self.fileName) def resetMusic(self): if self.musicStatus: mixer.music.play() def muteMusic(self): if self.muted: self.mutedButton.image = self.unmuteImage self.mutedButton = ttk.Button(self.middleFrame, image=self.unmuteImage, command=self.muteMusic) self.mutedButton.grid(row=0, column=5, padx=10, pady=10) self.volumeControl.set(100) self.muted = FALSE else: muteImage = PhotoImage(file="E:/Music_Player/icon/no-sound.png") self.mutedButton.image = muteImage self.mutedButton = ttk.Button(self.middleFrame, image=muteImage, command=self.muteMusic) self.mutedButton.grid(row=0, column=5, padx=10, pady=10) self.volumeControl.set(0) self.muted = TRUE def musicInfo(self): musicPath = self.cursorSelection() if musicPath: song = MP3(musicPath) self.songLength = song.info.length min, sec = divmod(self.songLength, 60) min = round(min) sec = round(sec) # timeFomrat = '{}:{}'.format( # str(round(min)).zfill(2), str(round(sec)).zfill(2)) self.timeFomrat = '{:02d}:{:02d}'.format(round(min), round(sec)) # print(timeFomrat) self.musicPlayTime = min * 60 + sec self.lb['text'] = f'Playing : {os.path.basename(musicPath)[:-4]}' self.lb2['text'] = "Time : " + self.timeFomrat self.th = threading.Thread(target=self.startCount, args=(min, sec, self.timeFomrat, self.lb2)) self.th.start() def startCount(self, min, sec, times, label): while self.musicPlayTime > 0 and self.threadExit: min, sec = divmod(self.musicPlayTime, 60) timeFomrat = '{:02d}:{:02d}'.format(round(min), round(sec)) self.musicPlayTime -= 1 time.sleep(1) # self.lb2['text'] = "Time : " + timeFomrat + " / " + self.timeFomrat self.lb2['text'] = "Time : " + self.timeFomrat def addPlaylist(self): musicName = os.path.basename(self.fileName)[:-4] print(musicName, self.fileName) # self.importFile() if self.fileName != "": trackInPlaylist = False for name in enumerate(self.musicFilename): if name[1] == musicName: trackInPlaylist = True if not trackInPlaylist: self.playListBox.insert(self.musicIndex, musicName) self.musicFilename[f'{musicName}'] = self.musicIndex self.musicFullPaths[str(self.musicIndex)] = self.fileName self.musicIndex += 1 else: tkinter.messagebox.showinfo("Already in playlist", "Track is Already in Playlist") def cursorSelection(self): if self.playListBox.curselection(): musicName = self.playListBox.get(self.playListBox.curselection()) id = 0 id = self.playListBox.curselection()[0] for name, i in self.musicFilename.items(): if name == musicName: id = i musicPath = self.musicFullPaths[f'{id}'] return musicPath else: tkinter.messagebox.showinfo("Select Music", "Please Select Music !") return False def musicDeteleFromPlaylist(self): music = self.playListBox.get(self.playListBox.curselection()) if self.playListBox.curselection(): musicId = self.playListBox.curselection()[0] self.playListBox.delete(musicId) for i, path in self.musicFullPaths.items(): if music == os.path.basename(path)[:-4]: musicId = i # print("---------------------", i) del self.musicFilename[os.path.basename( self.musicFullPaths[f'{musicId}'])[:-4]] del self.musicFullPaths[str(musicId)]
class GUI: e1 = '' e2 = '' e3 = '' thread_list = [] MAX = 50 def __init__(self): self.window = ThemedTk(theme="arc") # arc breeze self.window.title("Web Scraping") self.window.configure(background="white") self.setInputs() self.setButtons() self.name = '' self.min1 = '' self.max1 = '' self.ans = [] def start(self): self.window.mainloop() def setInputs(self): Label(self.window, text="Enter Category ", font=("Arial", 15), background="white", foreground="black").grid(row=2, padx=20, pady=10) Label(self.window, text="Enter Min Price ", font=("Arial", 15), background="white", foreground="black").grid(row=4, padx=20, pady=10) Label(self.window, text="Enter Max Price ", font=("Arial", 15), background="white", foreground="black").grid(row=6, padx=20, pady=10) Label(self.window, text="", font=("Arial", 15), background="white").grid(row=0) self.e1 = tk.Entry(self.window) self.e1.grid(row=2, column=1) self.e2 = tk.Entry(self.window) self.e2.grid(row=4, column=1) self.e3 = tk.Entry(self.window) self.e3.grid(row=6, column=1) def setButtons(self): tk.Button(self.window, text=' Search ', bg="#e0e0d1", command=self.running).grid(row=8, column=1, sticky=tk.W, padx=20, pady=20) tk.Button(self.window, text=' Exit ', bg="#e0e0d1", command=quit).grid(row=8, column=2, sticky=tk.W, padx=20, pady=20) # running() @staticmethod def callback(url): print(url) webbrowser.open_new(url) def on_change(self, e): print(e.widget.get()) @staticmethod def readAnsFromCSV(name_of_file): data0 = [] with open(name_of_file, 'r') as f: data1 = csv.reader(f) for row in data1: data0.append(row) return data0[1:] def do(self): obj = merged_code.result(self.name.strip(), self.min1, self.max1) self.ansfile = obj.getResult() print("answer file " + self.ansfile) self.ans = self.readAnsFromCSV(self.ansfile) print('result ' + str(len(self.ans))) time.sleep(0.01) print(self.ans) self.loading.quit() self.MAX = 0 def loading(self): self.loading = ThemedTk(theme="arc") # arc breeze self.loading.title("Loading") self.loading.configure(background="white") self.loading.geometry("260x140") self.loading_labe = Label(self.loading, text="", background="white").grid(row=0) self.loading_label = Label(self.loading, text="Please Wait ...", font=("Arial", 15), background="white", foreground="blue").grid(row=1, pady=10, padx=30) self.progress = Progressbar(self.loading, orient=HORIZONTAL, length=200, mode='indeterminate') self.progress.grid(row=2, pady=10, padx=30) k = 10 while self.MAX != 0: self.progress['value'] = k k += 1 time.sleep(0.01) self.loading.update() #self.progress.stop() #self.progress.grid_forget() self.loading.destroy() self.loading.mainloop() class Splash(tk.Toplevel): def __init__(self, parent): tk.Toplevel.__init__(self, parent) self.title("Splash") def running(self): self.name = self.e1.get() self.min1 = float(self.e2.get()) self.max1 = float(self.e3.get()) thread = threading.Thread(target=self.do) thread1 = threading.Thread(target=self.loading) thread1.start() thread.start() # thread1.start() self.thread_list.append(thread) self.thread_list.append(thread1) for th in self.thread_list: th.join() self.show_entry_fields() def show_entry_fields(self): print(self.ans) self.flag = 0 for i in range(len(self.ans)): if self.flag == 0: Label(self.window, text="Model", font=("Arial", 15), background="white", foreground="#000099").grid(row=10 + i, column=0, padx=25, pady=10) Label(self.window, text="Original Price", font=("Arial", 15), background="white", foreground="#000099").grid(row=10 + i, column=1, padx=25, pady=10) Label(self.window, text="Flipkart Price", font=("Arial", 15), background="white", foreground="#000099").grid(row=10 + i, column=2, padx=25, pady=10) Label(self.window, text="Rating", font=("Arial", 15), background="white", foreground="#000099").grid(row=10 + i, column=3, padx=25, pady=10) Label(self.window, text="Number of Reviews", font=("Arial", 15), background="white", foreground="#000099").grid(row=10 + i, column=4, padx=25, pady=10) Label(self.window, text="Link", font=("Arial", 15), background="white", foreground="#000099").grid(row=10 + i, column=5, padx=25, pady=10) self.flag = 111 if len(self.ans[i][0]) > 40: titletemp = self.ans[i][0][:40] + '...' else: titletemp = self.ans[i][0] b1 = Label(self.window, text=titletemp, font=("Arial", 12), background="white", foreground="black") # assign price 1 b1.grid(row=12 + i, column=0, padx=25, pady=7.5) b2 = Label(self.window, text=self.ans[i][1], font=("Arial", 12), background="white", foreground="black") # assign price 1 b2.grid(row=12 + i, column=1, padx=25, pady=7.5) b3 = Label(self.window, text=self.ans[i][2], font=("Arial", 12), background="white", foreground="black") # assign price 2 b3.grid(row=12 + i, column=2, padx=25, pady=7.5) b4 = ttk.Label(self.window, text=self.ans[i][3], font=("Arial", 12), background="white", foreground="black") # assign ratings b4.grid(row=12 + i, column=3, padx=25, pady=7.5) b5 = ttk.Label(self.window, text=self.ans[i][4], font=("Arial", 12), background="white", foreground="black") # assign reviews b5.grid(row=12 + i, column=4, padx=25, pady=7.5) b6 = tk.Button( self.window, text="Click Here to know more", bg="white", fg="blue", command=lambda aurl=self.ans[i][5]: self.callback(aurl)) b6.grid(row=12 + i, column=5, padx=25, pady=7.5) self.window.state("zoomed") self.w = self.window.winfo_screenwidth() self.h = self.window.winfo_screenheight() self.window.geometry("%dx%d+0+0" % (self.w, self.h))
def main(): global message message = "" if "alarm.mp3" not in os.listdir("."): print("alarm.mp3 not found please check it out") time.sleep(5) raise Exception("alarm.mp3 not found please check it out") LARGE_FONT = ("Verdana", 12) root = ThemedTk(theme="adapta") root.title('HOTSPOT') root.bind('<Escape>', lambda e: root.destroy()) root.protocol("WM_DELETE_WINDOW", root.iconify) root.update_idletasks() try: root.iconbitmap('icon.ico') except: pass home = ttk.Frame(root) home.grid(row=0, column=0, sticky='news') home.rowconfigure([0], weight=1) home.columnconfigure([0, 1], weight=1) server = ttk.Frame(root) server.grid(row=0, column=0, sticky='news') server.rowconfigure([0, 1, 2, 3], weight=1) server.columnconfigure([0], weight=1) status5 = ttk.Label(server, text="", font=LARGE_FONT, anchor=tk.CENTER) status5.grid(row=2, column=0, sticky=tk.N + tk.S + tk.E + tk.W) status7 = ttk.Label(server, text="", font=LARGE_FONT, anchor=tk.CENTER) status7.grid(row=1, column=0, sticky=tk.N + tk.S + tk.E + tk.W) progress2 = ttk.Progressbar(server, orient="horizontal", mode="determinate", cursor='spider') progress2.grid(row=3, column=0, sticky=tk.N + tk.S + tk.E + tk.W) progress2["maximum"] = 100 button3 = ttk.Button(server, text="Start", width=15, command=lambda: Thread(target=lambda: makeserver( status7, progress2, server)).start()) button3.grid(row=1, column=2, sticky=tk.N + tk.S + tk.E + tk.W) button3 = ttk.Button(home, text="Recieve", width=15, command=lambda: raise_frame(server, "R", status5)) button3.grid(row=0, column=0, sticky=tk.N + tk.S + tk.E + tk.W) button4 = ttk.Button(home, text="Send", width=15, command=lambda: raise_frame(page, "S", status6)) button4.grid(row=0, column=1, sticky=tk.N + tk.S + tk.E + tk.W) page = ttk.Frame(root) page.grid(row=0, column=0, sticky='news') page.rowconfigure([0, 1, 2], weight=1) page.columnconfigure([0], weight=1) progress = ttk.Progressbar(page, orient="horizontal", mode="determinate", cursor='spider') progress.grid(row=1, column=0, sticky=tk.N + tk.S + tk.E + tk.W) progress["maximum"] = 100 status6 = ttk.Label(page, text="", font=LARGE_FONT, anchor=tk.CENTER) status6.grid(row=2, column=0, sticky=tk.N + tk.S + tk.E + tk.W) startpage = ttk.Frame(page) startpage.grid(row=0, column=0, sticky='news') startpage.rowconfigure([0, 1, 2], weight=1) startpage.columnconfigure([0, 1, 2], weight=1) HOST = ttk.Entry(startpage) HOST.grid(row=1, column=1, sticky=tk.N + tk.S + tk.E + tk.W) PORT = ttk.Entry(startpage) PORT.grid(row=2, column=1, sticky=tk.N + tk.S + tk.E + tk.W) PORT.insert(tk.END, '65432') button = ttk.Button( startpage, text="send", width=15, command=lambda: Thread(target=lambda: connect(page, progress, HOST.get( ), int(PORT.get()))).start()) button.grid(row=2, column=2, sticky=tk.N + tk.S + tk.E + tk.W) status = ttk.Label(startpage, text="click for connecting and sending", font=LARGE_FONT, anchor=tk.CENTER) status.grid(row=0, column=0, sticky=tk.N + tk.S + tk.E + tk.W) status1 = ttk.Label(startpage, text="", font=LARGE_FONT, anchor=tk.CENTER) status1.grid(row=0, column=2, sticky=tk.N + tk.S + tk.E + tk.W) status2 = ttk.Label(startpage, text="", font=LARGE_FONT, anchor=tk.CENTER) status2.grid(row=0, column=1, sticky=tk.N + tk.S + tk.E + tk.W) status3 = ttk.Label(startpage, text="IP ", font=LARGE_FONT, anchor=tk.CENTER) status3.grid(row=1, column=0, sticky=tk.N + tk.S + tk.E + tk.W) status4 = ttk.Label(startpage, text="PORT", font=LARGE_FONT, anchor=tk.CENTER) status4.grid(row=2, column=0, sticky=tk.N + tk.S + tk.E + tk.W) button2 = ttk.Button(startpage, text="open file", width=15, command=lambda: Open(progress)) button2.grid(row=1, column=2, sticky=tk.N + tk.S + tk.E + tk.W) center(root) menubar = tk.Menu(root) filemenu = tk.Menu(menubar, tearoff=False) filemenu.add_command(label="Home", command=lambda: raise_frame(home)) filemenu.add_command(label="Exit", command=root.destroy) menubar.add_cascade(label="MENU", menu=filemenu) root.config(menu=menubar) root.deiconify() root.resizable(width=False, height=False) raise_frame(home) root.mainloop()
#!/usr/bin/python from Tkinter import * from ttkthemes import ThemedTk class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): ok = Button(dialog) print "hi there, everyone!", ok root = ThemedTk(theme="arc") app = App(root) root.mainloop() root.destroy() # optional; see description below