def main(): def funcExit(): message_box = messagebox.askquestion("Exit", "Do you want to exit?", icon='warning') if message_box == "yes": root.destroy() def funcAddBook(): open_add_book = add_book.AddBook() def funcAddMember(): open_add_member = add_member.AddMember() root = ThemedTk() root.get_themes() root.set_theme("arc") app = Main(root) #MenuBar menu_bar = Menu(root) root.config(menu=menu_bar) file = Menu(menu_bar, tearoff=0) menu_bar.add_cascade(label="File", menu=file) file.add_command(label="Add a Book", command=funcAddBook) file.add_command(label="Add a Member", command=funcAddMember) file.add_command(label="Show Member") file.add_command(label="Exit", command=funcExit) root.title("Library Management System") root.geometry("1280x720+450+150") root.resizable(False, False) root.iconbitmap("image/book_tk.ico") root.mainloop()
class Window: def __init__(self): self.Root = ThemedTk(theme="blue") self.Root.config(bg='steel blue3') self.Root.title('Monster Fight!!!') self.TopFrame = ttk.Frame(self.Root) self.BottomFrame = ttk.Frame(self.Root) self.TopFrame.pack(side='top', fill='both', padx=60, pady=60) self.BottomFrame.pack(side='bottom', fill='both') self.StrongAttackButton = ttk.Button( self.BottomFrame, text='Strong Attack', command=lambda: UseAbility('StrongAttack')) self.QuickAttackButton = ttk.Button( self.BottomFrame, text='Quick Attack', command=lambda: UseAbility('QuickAttack')) self.HealButton = ttk.Button(self.BottomFrame, text='Heal', command=lambda: UseAbility('Heal')) self.BlockButton = ttk.Button(self.BottomFrame, text='Block', command=lambda: UseAbility('Block')) self.SumitButton = ttk.Button(self.BottomFrame, text='Submit', command=self.NamingMonster) self.MonsterNameLable = ttk.Label(self.BottomFrame) self.MonsterNameForm = ttk.Entry(self.TopFrame) self.TextonScreen = ttk.Label( self.TopFrame, text= 'Please Type your monster name, if you blank a monster name will be randomly picked for you' ) def NamingMonster(self): if (self.MonsterNameForm.get()): Player.Name = self.MonsterNameForm.get() print(Player.Name) self.TextonScreen.pack_forget() self.SumitButton.pack_forget() self.MonsterNameForm.pack_forget() def NameScreen(self, Target): self.TextonScreen.pack() self.SumitButton.pack() self.MonsterNameForm.pack() def MainBattleScreen(self): self.StrongAttackButton.pack() self.QuickAttackButton.pack() self.HealButton.pack() self.BlockButton.pack() self.MonsterNameLable.pack() def UseAbility(self, Move): Player.Move = Move
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()
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()
chk_state.set(True) #set check state chk = Checkbutton(window, text='Choose', var=chk_state) chk.grid(column=0, row=0) menu = Menu(window) new_item = Menu(menu) new_item.add_command(label='New') menu.add_cascade(label='File', menu=new_item) window.config(menu=menu) from tkinter.ttk import Progressbar from tkinter import ttk style = ttk.Style() style.theme_use('default') style.configure("black.Horizontal.TProgressbar", background='black') bar = Progressbar(window, length=200, style='black.Horizontal.TProgressbar') bar['value'] = 70
mycursor = mydb.cursor() #abrir ventana en el centro def centrar_ventana(ventana): windowWidth = ventana.winfo_reqwidth() windowHeight = ventana.winfo_reqheight() positionRight = int(ventana.winfo_screenwidth()/2 - windowWidth/2) positionDown = int(ventana.winfo_screenheight()/3 - windowHeight/3) ventana.geometry("+{}+{}".format(positionRight, positionDown)) root = ThemedTk(theme="breeze") root.title("Biblioteca Parra") root.tk.call('wm', 'iconphoto', root._w, PhotoImage(file='book.png')) root.geometry("305x200") root.config(bg="white") centrar_ventana(root) #Ventana para registrar usuario def open_registro(): def popup_usuario_agregado(): messagebox.showinfo("Listo", "Usuario agregado con exito!") def agregar_usuario(): #conectandome a la base de datos mydb = mysql.connector.connect( host="localhost",
from ttkthemes import ThemedTk import math REC_WIDTH = 600 REC_HEIGHT = 200 RECTANGLE_COLOUR = "#3fc1c9" RECTANGLE_TEXT_COLOUR = "#364f6b" BACKGROUND_COLOUR = "#f5f5f5" RED = "#fc5185" YELLOW = "#ffde7d" WIDGET_WIDTH = 95 font_data = ("TkMenuFont", 20, "normal") window = ThemedTk(theme="adapta") window.title("Speedest") window.config(padx=100, pady=100, background=BACKGROUND_COLOUR) brain = TestBrain() # ---------------------------------------------------------------------------------------------------------------------- def show_time(event): time = str(math.ceil(float(scale_variable.get()))) time_val_label.config(text=f"{time}s") def start_test(): playsound("sounds/select_sound.mp3", block=False) controlls_frame.grid_remove() test_frame.grid(row=1, column=0, pady=(20, 0)) test_entery.focus()
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()
from scripts.frequency import TestFrequency import pandas as pd from pandastable import Table, TableModel import tkinter.scrolledtext as scrolledtext from ttkthemes import ThemedTk root = ThemedTk(theme='breeze') # tema root.title("Sistema de inventarios") # titulo # tamaño de anchura de toda la ventana del ordenador screen_width = root.winfo_screenwidth() # tamaño de la altura toda la ventana del ordenador screen_height = root.winfo_screenheight() root.geometry(f"{screen_width}x{screen_height}") menubar = Menu(root) # se crea el menu root.config(menu=menubar) # ?? helpmenu = Menu(menubar, tearoff=0) menubar.add_command(label="Generador y pruebas") menubar.add_command(label="Sistema de inventarios") menubar.add_cascade(label="Mas", menu=helpmenu) # Menu de ayuda y demas informacion helpmenu.add_command(label='Ayuda') helpmenu.add_command(label='Acerca del metodo') helpmenu.add_command(label='Formulas') helpmenu.add_command(label='Informacion de las pruebas') helpmenu.add_command(label='Integrantes') # Metodo para generador df = None
class MusicPlayer(): def __init__(self): pygame.mixer.init() self.w = ThemedTk(theme='black') self.w.title('Music Player') self.w.resizable(0, 0) self.w.geometry('300x400+800+300') self.w.config(bg=window_bg_color) # Images: self.img_add = tk.PhotoImage(file='assets/add.png') self.img_remove = tk.PhotoImage(file='assets/remove.png') self.img_prev = tk.PhotoImage(file='assets/previous.png') self.img_play = tk.PhotoImage(file='assets/play.png') self.img_pause = tk.PhotoImage(file='assets/pause.png') self.img_next = tk.PhotoImage(file='assets/next.png') # Widget creation starts: self.listb_playlist = tk.Listbox(self.w, bg=playlist_bg_color, fg=playlist_font_color, font=playlist_font, selectbackground=playlist_selected_bg, selectforeground=playlist_selected_fg, height=14) self.frame_modbtns = ttk.Frame(self.w) self.btn_remove = ttk.Button(self.frame_modbtns, image=self.img_remove, command=self.delete_track) self.btn_add = ttk.Button(self.frame_modbtns, image=self.img_add, command=self.select_dir) self.frame_navbtns = ttk.Frame(self.w) self.btn_prev = ttk.Button(self.frame_navbtns, image=self.img_prev, command=lambda: self.select_track('prev')) self.btn_play = ttk.Button(self.frame_navbtns, image=self.img_play, command=self.play_track) self.btn_next = ttk.Button(self.frame_navbtns, image=self.img_next, command=lambda: self.select_track('next')) self.scale_vol = ttk.Scale(self.w, from_=0, to=1, value=1, command=self.set_volume) # Widget creation ends. # Widget placing starts: self.listb_playlist.pack(fill='x', padx=10, pady=10) self.frame_modbtns.pack(pady=10) self.btn_remove.grid(row=0, column=1) self.btn_add.grid(row=0, column=0) self.frame_navbtns.pack(pady=10) self.btn_prev.grid(row=0, column=0) self.btn_play.grid(row=0, column=1) self.btn_next.grid(row=0, column=2) self.scale_vol.pack(fill='x', padx=10, pady=5) # Widget placing ends. self.w.mainloop() def select_dir(self): ''' Establishes the directory where the mp3 files are stored and inserts the names of the files in the playlist. ''' try: change_files_dir(filedialog.askdirectory()) files = os.listdir(files_dir) self.listb_playlist.delete(0, tk.END) for f in files: if f.split('.')[-1] == 'mp3': self.listb_playlist.insert(tk.END, str(f)) except FileNotFoundError: pass def delete_track(self): ''' Deletes the current selected item from the playlist. ''' self.listb_playlist.delete(tk.ANCHOR) def select_track(self, direction): ''' Selects the next or previous item of the playlist, based on the current selected item. -direction: Receives either "next" or "prev" to establish where is the selection anchor is going to move. ''' try: if direction == "next": track_index = self.listb_playlist.curselection()[0] + 1 elif direction == "prev": track_index = self.listb_playlist.curselection()[0] - 1 if (track_index >= 0 and track_index < self.listb_playlist.size()): self.listb_playlist.select_clear(0, tk.END) self.listb_playlist.activate(track_index) self.listb_playlist.select_set(track_index) self.listb_playlist.selection_anchor(track_index) self.listb_playlist.yview(track_index) except IndexError: pass def play_track(self): ''' Plays and stops the music file. ''' try: if rep_status == 0: pygame.mixer.music.load(files_dir + '/' + self.listb_playlist.get(tk.ANCHOR)) self.btn_play.config(image=self.img_pause) pygame.mixer.music.play() change_rep_status(1) elif rep_status == 1: pygame.mixer.music.pause() self.btn_play.config(image=self.img_play) change_rep_status(0) except pygame.error: pass def set_volume(self, var): ''' Changes the volume of the music played. *It receives no arguments when called. ''' pygame.mixer.music.set_volume(self.scale_vol.get())
from pygame import mixer from mutagen.mp3 import MP3 as mp3 from tkinter import ttk # Normal Tkinter.* widgets are not themed! from ttkthemes import ThemedTk mixer.init() # root = Tk() root = ThemedTk(theme="arc") root.title("Music Player - [YYScoop.com]") root.iconbitmap("images/favicon.ico") root.geometry("600x484") root.resizable(0, 0) menubar = Menu(root, bg="#ccba41") root.config(menu=menubar, bg="#FFFFFF") # current_music = "" current_music_path = "sample/Sample Song mp3.mp3" pause_status = False stop_status = False mute_status = False tread_status = False reset_tread = False audio_length = 0.0 time_tread = threading.Thread() time_counter = "unactive" playlist_count = 1 playlist = []
def next_image(): global img_no try: if len(paths) != 0 and img_no < len(paths) - 1: img_no += 1 set_image() except: pass root = ThemedTk(theme='arc') root.title('Photos') root.geometry('800x600+230+30') root.minsize(800, 600) root.iconbitmap('./res/icon.ico') root.config(bg='white') # Variables img_no = 0 paths = [] # Frames photo_frame = LabelFrame(root, borderwidth=10, bg='white') photo_frame.pack(expand=True, fill='both') btn_frame = Frame(root, bg='white') btn_frame.pack(side=BOTTOM, pady=10) # Label for image lblText = Label(photo_frame, text='Add photos to browse',
class MainForm(): def __init__(self): """ Inicializa as variaveis usadas e também carrega o form principal """ # Dicionário de ambientes (aba + exame) self.envDict = {} # Dicionário de exames self.examDict = {} # Lista de threads para carregar os exames self.loaderList = [] self.envActive = None self.setForm() self.root.mainloop() def setForm(self): """ Basicamente chama os metodos de construção do form, separado por estrutura (menus, abas, etc) """ self.setRoot() self.setMainFrame() self.setEditMenu() self.setNotebook() self.setTopMenu() def setRoot(self): self.root = ThemedTk(theme="Adapta") self.root.rowconfigure(0, weight=1) self.root.columnconfigure(0, weight=1) self.root.state('zoomed') def setMainFrame(self): self.mainFrame = ttk.Frame(self.root) self.mainFrame.grid(row=0, column=0, sticky=tk.NSEW) self.mainFrame.rowconfigure(1, weight=1) self.mainFrame.columnconfigure(0, weight=1, uniform="mainframe") self.mainFrame.columnconfigure(1, weight=4, uniform="mainframe") self.mainFrame.bind(("<Escape>", self.clearCursor)) def setEditMenu(self): self.drawThickness = tk.DoubleVar(self.root) self.editMenu = ttk.Frame(self.mainFrame) self.editMenu.grid(row=1, column=0, sticky=tk.NSEW) #self.editMenu.columnconfigure(0,weight=1) ttk.Button(self.editMenu, text=btns.RECTANGLE, command=lambda: self.cbRoi(Shape.RECTANGLE)).grid( row=1, column=0, sticky=tk.NW) ttk.Button(self.editMenu, text=btns.CIRCLE, command=lambda: self.cbRoi(Shape.CIRCLE)).grid(row=2, column=0, sticky=tk.NW) ttk.Button(self.editMenu, text=btns.DRAW, command=lambda: self.cbDraw()).grid(row=3, column=0, sticky=tk.NW) ttk.Button(self.editMenu, text=btns.ZOOM_IN, command=lambda: self.cbZoom(True)).grid(row=4, column=0, sticky=tk.NW) ttk.Button(self.editMenu, text=btns.ZOOM_OUT, command=lambda: self.cbZoom(False)).grid(row=5, column=0, sticky=tk.NW) ttk.Scale(self.editMenu, orient=tk.HORIZONTAL, variable=self.drawThickness).grid(row=3, column=1, sticky=tk.NW) def setNotebook(self): self.notebook = ttk.Notebook(self.mainFrame, name=txt.NOTEBOOK) self.notebook.grid(row=1, column=1, sticky=tk.NSEW) self.root.update() self.notebook.bind("<<NotebookTabChanged>>", self.onEnvChange) def setTopMenu(self): #self.menubar = tk.Menu(self.root,tearoff=False) self.ttkMenubar = ttk.Menubutton(self.root) self.menubar = tk.Menu(self.root, tearoff=False) self.ttkMenubar['menu'] = self.menubar self.fileMenu = tk.Menu(self.menubar, tearoff=False) self.menubar.add_cascade(label=lblsTop.FILE, underline=0, menu=self.fileMenu) self.fileMenu.add_command(label=lblsTop.LOADEXAM, underline=0, compound=tk.LEFT, command=self.loadExam) self.root.config(menu=self.menubar) def loader(self, examID, dicomList): """ Alvo da thread para criação de novos ambientes (abas) """ self.envActive = Environment(examID, dicomList) self.loadImageNotebook() def loadExam(self): """ Carrega os exames através do handler """ examDict = dcmHandler.openDicomFiles() for examID, dicomList in examDict.items(): self.loader(examID, dicomList) # t = Thread(target=self.loader,args=(img,)) # loaderList.append(t) # t.start() def onEnvChange(self, event): print(self.notebook.index('current')) self.envActive = self.envDict[self.notebook.index( self.notebook.select())] self.clearCursor() def cbRoi(self, shape): cnv = self.envActive.resultCanvas cnv.bind( "<ButtonPress-1>", lambda event: edit.callbackRoi( env=self.envActive, event=event, shape=shape)) cnv.bind("<B1-Motion>", lambda event: edit.onMoveRoi(env=self.envActive, event=event)) cnv.bind( "<ButtonRelease-1>", lambda event: edit.releaseRoi(env=self.envActive, event=event)) def cbDraw(self): cnv = self.envActive.resultCanvas # cnv.bind("<ButtonPress-1>", lambda event: edit.callbackDraw(event=event)) cnv.bind( "<B1-Motion>", lambda event: edit.onMoveDraw(event=event, env=self.envActive, thickness=self.drawThickness.get())) # cnv.bind("<ButtonRelease-1>", lambda event: edit.releaseDraw(event=event)) def cbZoom(self, zoomIn): cnv = self.envActive.resultCanvas cnv.bind( "<ButtonRelease-1>", lambda event: edit.zoom( env=self.envActive, zoomIn=zoomIn, event=event)) def loadImageNotebook(self): """ Create a image in the notebook for the environment. The image is loaded in a tab in the notebook Input: Environment (env) Output: Frame inside the tab where the image is set (frm) """ try: # Cria o frame e o canvas do exame usando o frame # definido como tab dentro do notebook self.envActive.createExamViewer( self.createTab(self.envActive.examID)) self.envActive.updateImage() # self.envDict[len(self.notebook.tabs())-1] = self.envActive # self.notebook.select(len(self.notebook.tabs())-1) self.envDict[len(self.notebook.tabs())] = self.envActive self.root.update() self.notebook.select(len(self.notebook.tabs()) - 1) except Exception as ex: printLog(LOGTYPE.ERROR_LOAD_IMG_NOTEBOOK, ex) def createTab(self, exam): frm = ttk.Frame(self.notebook, name=exam) self.notebook.add(frm, text=exam) frm.rowconfigure(0, weight=1) frm.columnconfigure(0, weight=2, uniform='notebook') frm.columnconfigure(1, weight=1, uniform='notebook') return frm def clearCursor(self): frmName = self.notebook.select() frm = self.root.nametowidget(frmName) for cnvName in frm.children[txt.EXAMIMAGE].children: # Pega o canvas atual cnv = self.root.nametowidget(".".join( (frmName, txt.EXAMIMAGE, cnvName))) cnv.unbind("<ButtonPress-1>") cnv.unbind("<B1-Motion>") cnv.unbind("<ButtonRelease-1>")
from image_master import ImageMaster from tkinter import ttk from tkinter import filedialog import tkinter as tk from ttkthemes import ThemedTk import math from tkinter import colorchooser from tkinter import messagebox from reinit_app import reinit_app GREY = "#dddddd" FONT_DATA = ("TkMenuFont", 10, "normal") window = ThemedTk(theme="arc", background=True) window.iconphoto(False, tk.PhotoImage(file='assets/images/default_imgs/icon.png')) window.title("OpenWater") window.config(padx=50, pady=50) image_controller = ImageMaster() font_colour = ("black", "black") text_rotation_angle = 0 def plus_angle(): global text_rotation_angle text_rotation_angle += 10 rotation_label.config(text=f"{text_rotation_angle}°") def minus_angle(): global text_rotation_angle text_rotation_angle -= 10 rotation_label.config(text=f"{text_rotation_angle}°")
compound=LEFT, accelerator='Ctrl+N') firstMenu.add_command(label="Save", image=saveImg, compound=LEFT, accelerator='Ctrl+P') firstMenu.add_separator() firstMenu.add_command(label="Exit", image=exitImg, compound=LEFT, accelerator='Esc', command=exitApp) mainmenu.add_cascade(label="File", menu=firstMenu) mainmenu.add_cascade(label="Help") root.config(menu=mainmenu) tc = ttk.Combobox(root, values=THEMES) tc.pack(anchor=SW, side=LEFT) tc.set("Change theme") tc.bind("<<ComboboxSelected>>", lambda e: change_theme(tc.get())) #------------ adding some widgets to see theme effects--------------- l1 = ttk.Label(text="Label 1", width=15, font=15).pack(side=TOP, anchor=SW) l2 = ttk.Label(text="Label 2", width=15, font=15).pack(side=TOP, anchor=SW, pady=20) l3 = ttk.Label(text="Label 3", width=15, font=15).pack(side=TOP, anchor=SW) b1 = ttk.Button(text="Button 1", width=15, style='C.TButton').pack(side=TOP, anchor=SW, pady=20)
from imutils import paths from datetime import datetime from ttkthemes import ThemedTk import shutil #initialize the model Recognize = recognize(0.5, 0.8) #initialize the embedding model extractEmbed = extract_embeddings() #Set up GUI #window = tk.Tk() #Makes main window window = ThemedTk(theme="equilux") window.title("Facial Recognition Surveillance System") window.iconbitmap("logo3_icon.ico") window.config(background="#292929") #"#121212")#"#242424") #print(window.style) #style.configure("BW.TLabel", foreground="black", background="white") #window.config(background="#FFFFFF") #window.bind('<<ThemeChanged>>', lambda event: print('theme changed in root and across all widgets!')) ''' Style = ttk.Style() print(Style.theme_use()) Style.theme_use("clam") print(Style.theme_use()) ''' #print(ttk.Style().theme_names()) style = ttk.Style() style.theme_use("equilux") print(style.lookup("TButton", "foreground", default="white"))
cleanAll() main.wrapperHelp.pack(expand="yes", fill="both") def openGenerator(): cleanAll() main.wrapperGeneratorTests.pack(fill="both") def openInv(): cleanAll() main.wrapperSimulatorInv.pack(fill="both", expand="yes") menubar = Menu(root) # se crea el menu root.config(menu=menubar) # helpmenu = Menu(menubar, tearoff=0) menubar.add_command(label="Generador y pruebas", command=openGenerator) menubar.add_command(label="Comerciante y manzanas", command=openInv) # menubar.add_command(label="Prueba de volados", command=openVolados) menubar.add_cascade(label="Mas", menu=helpmenu) # Menu de ayuda y demas informacion helpmenu.add_command(label='Ayuda', command=openHelp) helpmenu.add_command(label='Acerca del metodo') helpmenu.add_command(label='Formulas') helpmenu.add_command(label='Informacion de las pruebas') helpmenu.add_command(label='Integrantes') NavigationToolbar2Tk.toolitems = [ t for t in NavigationToolbar2Tk.toolitems if t[0] not in ('Subplots', 0)
def main(): print("Scanner App Started...") # UI Updating Method def update_left_header_label(value): """UI Updating Method :param value: value to be set in left header """ if value is None: # if the provided value is none, then update to the default header host_count = DataShare.get_hosts_total() host_count_text = f"({host_count}) Hosts Scanned".format() left_frame_header_label_var.set(host_count_text) else: # else left_frame_header_label_var.set(value) def update_left_header_label_random_waiting_msg(): """Update waiting header randomly""" random_waiting_responses = [ "This may take a while...", "I'm sorry this will be a while...", "Scanning...", "Scanning in Process..." ] update_left_header_label(random.choice(random_waiting_responses)) def reset_left_header_label(): """Update left header with number of hosts scanned""" host_count = DataShare.get_hosts_total() host_count_text = f"({host_count}) Hosts Scanned".format() left_frame_header_label_var.set(host_count_text) def reload_hosts_tableview(): """Update hosts box with scanned hosts""" # hosts_listbox.delete(0, tk.END) sorted_scanned_hosts = None # Sort according to the Host Sort Setting reverse_sort = False if System.Settings.get_host_sort_type() == System.SortType.alphaDESC: reverse_sort = True if DataShare.get_hosts(): sorted_scanned_hosts = sorted(DataShare.get_hosts(), key=lambda x: (x.get_display_name()), reverse=reverse_sort) if sorted_scanned_hosts is None: return # Update hosts to the sorted version to ensure details on select are correct DataShare.set_hosts(sorted_scanned_hosts) reset_left_header_label() data = list( map( lambda host: (host.get_ip(), host.get_display_name(), host.get_vendor()), sorted_scanned_hosts)) # We need to reverse the data shown here because the table view will display the data in the reversed order # this is needed so that clicking the tableview will result in the correct host being selected: Task189 hosts_table_view.reload_data(data[::-1]) def scan_thread_completion(): """Scan given inputs, update associated ui, and save scan data""" scan_start_date = datetime.datetime.now() update_left_header_label("Scan in process...") scan_button.config(state="disabled") waiting_scanner1 = STimer.do_after( update_left_header_label_random_waiting_msg, 15) waiting_scanner2 = STimer.do_after( update_left_header_label_random_waiting_msg, 30) waiting_scanner3 = STimer.do_after( update_left_header_label_random_waiting_msg, 45) ports = f'{port_start_entry_var.get()}-{port_end_entry_var.get()}' hosts = scan_host_entry_var.get() scanner = Scanner(hosts, ports) set_host(scanner.get_scan_details(System.Settings.get_scan_type())) set_cpes_vulns(scanner.get_cpes()) scan_button.config(state="normal") scan_details_view.check_vulnerabilities_button.config(state="normal") scan_end_date = datetime.datetime.now() timedelta = scan_end_date - scan_start_date timedelta.total_seconds() last_row_id = df.DBFunctions.save_scan(scan_start_date, timedelta.total_seconds()) for host in get_hosts(): df.DBFunctions.save_host(host, last_row_id) query = "SELECT * FROM Hosts WHERE ScanID = ?" host_tuple = df.DBFunctions.get_all_where(query, (last_row_id, )) hosts_with_ID = [] for id_host in host_tuple: temp = Host(id_host[0], id_host[1], "Old Host", id_host[5], id_host[3], id_host[4], id_host[6], id_host[2]) hosts_with_ID.append(temp) set_host(hosts_with_ID) ip_list = [*DataShare.get_cpes()] cpe_list = DataShare.get_cpes() for ip in ip_list: for item in hosts_with_ID: if item.get_ip() == ip: cpe_list[item.get_id()] = cpe_list.pop(ip) DataShare.set_cpes(cpe_list) cves_with_host = df.DBFunctions.query_cves(cpe_list) for i in cves_with_host: for j in i: df.DBFunctions.save_cve_by_host(i, j) update_left_header_label(f"Scan finished in {timedelta} seconds") STimer.do_after(reset_left_header_label, 2) waiting_scanner1.cancel() waiting_scanner2.cancel() waiting_scanner3.cancel() def set_host(h): """Set scanned hosts for ui :param h: hosts found """ if h: DataShare.set_hosts(h) reload_hosts_tableview() def get_hosts(): """Get scanned hosts""" return DataShare.get_hosts() def set_cpes_vulns(c): """Set vulnerabilities from cps""" print("Main 172 set_cpes_vulns cpes:\n") print(c) DataShare.set_cpes(c) # Sort according to the Vulnerability Sort Setting reverse_sort = False if System.Settings.get_vuln_sort_type() == System.SortType.alphaDESC: reverse_sort = True sorted_vulns = sorted(df.DBFunctions.query_cves(c), reverse=reverse_sort) print('From Main 184, sorted_vulns: ', sorted_vulns) DataShare.set_vulns(sorted_vulns) # reload ui # Click Handlers def on_scan(): """Click handler for scan btn to start scanner thread""" # MAKE SURE TO VALIDATE INPUT scan_thread = SThread(0, "SCAN_THREAD_1", 5, scan_thread_completion) scan_thread.start() def on_select_scan(id): query = "SELECT * FROM Hosts WHERE ScanID = ?" params = (id, ) data = df.DBFunctions.get_all_where(query, params) test = df.DBFunctions.retrieve_scanID_data(id) print('\n\n\n\nGetting Data\n') print(data) print('\n') print(test) # these need to be set, but not sure if the cpes and vulns are differentiate # by scans like hosts are # todo: set cpes and vulns in DataShare print('\n\n\n\nCPES') #todo this changes depending on if a scan has been run print(DataShare.get_cpes()) print('\n\nVULNS') #todo these are 2.2 cpes... print(DataShare.get_vulns()) print('\n\n\n\n') curr_hosts = [] # for each host scanned for host_raw in data: host_id = host_raw[0] ip = host_raw[1] state = "Old Host" mac = host_raw[2] os_gen = host_raw[3] os_family = host_raw[4] name = host_raw[5] vendor = host_raw[6] curr_hosts.append( Host(host_id, ip, state, name, os_family, os_gen, vendor, mac)) set_host(curr_hosts) def find_exploit(cve): if cve: if exploit_view: exploit_view.update_cve(cve) else: print('No CVE selected') def update_exploit_tab(cve): main_note_book.select(2) exploit_view.cve_var.set(cve) exploit_view.on_search() def on_host_tableview_select(event): """Click handler to update right ui when user clicks on a host in left box""" index = hosts_table_view.get_selected_index() hosts = DataShare.get_hosts() scan_details_view.host_name_entry_var.set( hosts[index].get_display_name()) scan_details_view.mac_address_entry_var.set( hosts[index].get_mac_address()) scan_details_view.port_number_entry_var.set(hosts[index].get_ip()) def donothing(): filewin = Toplevel(root) button = Button(filewin, text="Do nothing button") button.pack() def update_import(): # Only takes json currently. path = askopenfilename(title='Select Database file to import...', # defaultextension='.db', filetypes=(("database files", "*.db"),("datafeeds", "*.json"),("all files", "*.*"))) path = askopenfilename(title='Select Database file to import...', filetypes=[('Json', '*.json')]) # ntpath for os compatibility with differing separators # head and tail if path ends in backslash head, tail = ntpath.split(path) fname = tail or ntpath.basename(head) if fname.endswith('.json'): # for use to support multiple file types # elif json_fp.endswith(('.json', '.db', '.xml'): df.DBFunctions.import_NVD_JSON(fname) else: tk.messagebox.showerror("Error", "File must be of type: json") # Set up tree columns to display IP and Device Names after a completed scan class TreeColumns(enum.Enum): name = 0 mac_address = 1 @staticmethod def display_name_for_column(col): display_names = { 0: "IP", 1: "Name", } return display_names[col] @staticmethod def all_cases(): cases = [] for col in TreeColumns: cases.append(TreeColumns.display_name_for_column(col.value)) return cases # Setup root ui root = ThemedTk() root.ttkStyle = ThemedStyle() theme = System.Settings.get_theme() root.ttkStyle.set_theme(theme) root.title("AnyScan") root.grid_rowconfigure(0, weight=1) root.grid_columnconfigure(1, weight=1) ################# # Setup LeftFrame ################# left_frame = ttk.Frame(root) left_frame.grid(row=0, column=0, sticky="nsew") left_frame.grid_rowconfigure(1, weight=1) left_frame.grid_columnconfigure(1, weight=1) # Setup Left Frame header Label left_frame_header_label_var = tk.StringVar() update_left_header_label(None) left_frame_header_label = ttk.Label( left_frame, textvariable=left_frame_header_label_var) left_frame_header_label.grid(row=0, column=0) # Setup Left Frame Host TableView sections_tuple = TreeColumns.all_cases() data = [] hosts_table_view = TableView(left_frame, 1, sections_tuple, data) hosts_table_view.bind_method('<ButtonRelease-1>', on_host_tableview_select) reload_hosts_tableview() # Setup scan host frame scan_host_frame = ttk.Frame(left_frame) scan_host_frame.grid(row=2, column=0) # Setup scan host label scan_host_label = ttk.Label(scan_host_frame, text="Hosts:") scan_host_label.grid(row=0, column=0) # Setup scan host entry scan_host_entry_var = tk.StringVar() scan_host_entry_var.set("192.168.1.0/28") scan_host_entry = ttk.Entry(scan_host_frame, textvariable=scan_host_entry_var) scan_host_entry.grid(row=0, column=1) # Setup scan port label frame scan_port_label_frame = ttk.Frame(left_frame) scan_port_label_frame.grid(row=3, column=0) # Setup scan port label port_start_label = ttk.Label(scan_port_label_frame, text="Start Port") port_start_label.grid(row=0, column=0, padx=(0, 8)) port_end_label = ttk.Label(scan_port_label_frame, text="End Port") port_end_label.grid(row=0, column=1, padx=(8, 0)) # Setup scan port frame scan_port_frame = ttk.Frame(left_frame) scan_port_frame.grid(row=4, column=0) # Setup scan port entries port_start_entry_var = tk.StringVar() port_start_entry_var.set("21") port_start_entry = ttk.Entry(scan_port_frame, width=4, textvariable=port_start_entry_var) port_start_entry.grid(row=0, column=0, padx=(0, 16)) port_end_entry_var = tk.StringVar() port_end_entry_var.set("30") port_end_entry = ttk.Entry(scan_port_frame, width=4, textvariable=port_end_entry_var) port_end_entry.grid(row=0, column=1, padx=(16, 0)) scan_button_frame = ttk.Frame(left_frame) scan_button_frame.grid(row=5, column=0) # Setup Left frame scan button scan_button = ttk.Button(scan_button_frame, text="Scan", command=on_scan) scan_button.grid(row=0, column=0, pady=(8, 8)) ################# # Setup RightFrame ################# # Setup Notebook for right frame rows = 0 while rows < 50: root.columnconfigure(rows + 1, weight=1) rows += 1 # Setup Root Notebook main_note_book = ttk.Notebook(root) main_note_book.grid(row=0, column=1, columnspan=50, rowspan=49, sticky="NESW") # Setup Scan Details Tab scan_details_view = ScanDetailsView() scan_details_tab = scan_details_view.get_view(main_note_book) main_note_book.add(scan_details_tab, text="Scan Details") # Setup Vulnerabilities Tab vulnerabilities_view = VulnerabilitiesView() vulnerabilities_tab = vulnerabilities_view.get_view(main_note_book) main_note_book.add(vulnerabilities_tab, text="Vulnerabilities") vulnerabilities_view.on_selected_cve = find_exploit vulnerabilities_view.move_to_exploit = update_exploit_tab # Setup Exploits Tab exploit_view = ExploitView() exploit_tab = exploit_view.get_view(main_note_book) main_note_book.add(exploit_tab, text='Exploits') # Setup Scan History Tab scan_history_view = ScanHistoryView() scan_history_tab = scan_history_view.get_view(main_note_book) main_note_book.add(scan_history_tab, text="Scan History") scan_history_view.on_selected_scan_completion = on_select_scan # File Menu Bar menubar = Menu(root) # create menu bar filemenu = Menu(menubar, tearoff=0) # create a menu to add some stuff too # Save Vulnerability in file menu bar savemenu = Menu(menubar, tearoff=0) savemenu.add_command(label="Save Vulnerability", command=VulnPopup.new_popup) filemenu.add_cascade(label='Save', menu=savemenu) # DB import in file menu bar importmenu = Menu(menubar, tearoff=0) importmenu.add_command(label="Database", command=update_import) filemenu.add_cascade(label="Import", menu=importmenu) filemenu.add_separator() # more prettiness # Scan settings in file menu bar settingsmenu = Menu(menubar, tearoff=0) settingsmenu.add_command(label="Scan Settings", command=scan_details_view.on_settings) filemenu.add_cascade(label='Settings', menu=settingsmenu) filemenu.add_separator() # pretty # Helper method to change application themes def change_theme(theme): root.ttkStyle.set_theme(theme) System.Settings.set_theme(theme) # Added the ability for the user to change themes from the cascading file menu themes_menu = Menu(menubar, tearoff=0) themes_menu.add_command(label="Alt", command=lambda: change_theme("alt")) themes_menu.add_command(label="Aqua", command=lambda: change_theme("aqua")) themes_menu.add_command(label="Clam", command=lambda: change_theme("clam")) themes_menu.add_command(label="Classic", command=lambda: change_theme("classic")) themes_menu.add_command(label="Default", command=lambda: change_theme("default")) themes_menu.add_command(label="Equilux", command=lambda: change_theme("equilux")) themes_menu.add_separator() themes_menu.add_command(label="Scidblue", command=lambda: change_theme("scidblue")) themes_menu.add_command(label="Scidgreen", command=lambda: change_theme("scidgreen")) themes_menu.add_command(label="Scidgrey", command=lambda: change_theme("scidgrey")) themes_menu.add_command(label="Scidmint", command=lambda: change_theme("scidmint")) themes_menu.add_command(label="Scidpink", command=lambda: change_theme("scidpink")) themes_menu.add_command(label="Scidpurple", command=lambda: change_theme("scidpurple")) themes_menu.add_command(label="Scidsand", command=lambda: change_theme("scidsand")) filemenu.add_cascade(label='Change Theme', menu=themes_menu) filemenu.add_separator() filemenu.add_command(label="Exit", command=root.quit) editmenu = Menu(menubar, tearoff=0) # create another menu to add some stuff too editmenu.add_command(label="Undo", command=donothing) menubar.add_cascade(label="File", menu=filemenu) # add file to menu bar # On macOS there are some default things added to this menu, but are not added to the same menu # under File. menubar.add_cascade(label='Edit', menu=editmenu) # add edit to menu bar too, for fun # Run the program with UI root.config(menu=menubar) root.geometry("1600x1000") root.minsize(800, 500) # add this to ensure app comes to front on start up root.lift() root.attributes('-topmost', True) root.after_idle(root.attributes, '-topmost', False) # start GUI root.mainloop()
# only add a true file to playlist not an empty file or none type if filename: playlist.insert(index, filename) play_list.insert(index, filename_path) def delete_song(): selected_song = playlist.curselection() # plays selected song selected_song = int(selected_song[0]) playlist.delete(selected_song) # delete song from listbox play_list.pop(selected_song) # remove song from the playlist # menu submenu = Menu(root) root.config(menu=submenu) filemenu = Menu(submenu, tearoff=0, bg="brown") submenu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="open file", command=browse_file) filemenu.add_command(label="exit", command=root.destroy) aboutus = Menu(submenu, tearoff=0, bg="brown") submenu.add_cascade(label="About", menu=aboutus) aboutus.add_command(label="About us", command=about) statusbar = Label( root, text="Welcome to AfroBit", font="monospace 12 italic", anchor="w", background="brown", padx=3,
s.configure("TButton", anchor=tk.CENTER) height = root.winfo_screenheight() width = root.winfo_screenwidth() root.title("ChotaPacket") root.geometry("%dx%d+0+0" % (width, height)) # Adding an image icon to root that works both on all os # if iconbitmap is used then in UBUNUTU only black and white images of xbm format can be used root.tk.call( "wm", "iconphoto", root._w, tk.PhotoImage(file="download (1).png"), ) root.config(bg="#002b36") # Function to Override the default exit before in root # Now a pop appears first def on_closing(): quit_root = messagebox.askyesno("Quit", "Do you really want to quit?") if quit_root == 1: root.destroy() else: return # Protocol for Overriding the default exit behaviour
import tkinter as tk from tkinter import ttk from ttkthemes import ThemedTk raiz = ThemedTk(theme="equilux") raiz.title("Mi primer Interfaz") raiz.geometry("280x260") raiz.resizable(0, 0) letra = "Helvetica 12 bold" raiz.config(bg="black") # Label dato1 = ttk.Label(raiz, text="Numero 1 ", font=letra) dato2 = ttk.Label(raiz, text="Numero 2 ", font=letra) resultado = ttk.Label(raiz, text="Resultado ", font=letra) # StringVar var1 = tk.StringVar() var2 = tk.StringVar() var3 = tk.StringVar() # Entry campo_texto1 = ttk.Entry(raiz, textvariable=var1, justify="center", width=14, font=letra) campo_texto2 = ttk.Entry(raiz, textvariable=var2, justify="center", width=14, font=letra) campo_texto3 = ttk.Entry(raiz, textvariable=var3,
from tkinter import * from tkinter import ttk from ttkthemes import ThemedTk import pandas as pd import os from tkinter.filedialog import askopenfile, asksaveasfilename win = ThemedTk(theme="aqua") win.title("Notepad") win.geometry("720x480") win.minsize(720, 480) win.config(background='#272C35') def open_file(): blank.delete("1.0", END) file = askopenfile(mode='r', filetypes=[('All', '*'), ('Text files', '*.txt'), ('Hyper Text Language Markup', '*.html'), ('Comma-Separated Values', '*.csv')]) if file is not None: text = file.read() blank.insert("1.0", text) def save_file(): notepad_text = blank.get("1.0", "end-1c") file = asksaveasfilename(title="Save", filetypes=[('All', '*'), ('Text files', '*.txt'), ('Hyper Text Language Markup', '*.html'),
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()
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)
#color theme def change_theme(): chosen_theme = theme_choice.get() color_tuple = color_dict.get(chosen_theme) fg_color, bg_color = color_tuple[0], color_tuple[1] text_editor.config(background=bg_color, fg=fg_color) count = 0 for i in color_dict: color_theme.add_radiobutton(label = i, image =color_icons[count], variable = theme_choice,compound = tk.LEFT,command = change_theme) count += 1 main_application.config(menu = main_menu) main_application.protocol('WM_DELETE_WINDOW',exit_func) #shortcuts main_application.bind("<Control-n>",new_file) main_application.bind("<Control-o>",open_file) main_application.bind("<Control-s>",save_file) main_application.bind("<Control-Alt-s>",save_as) main_application.bind("<Control-q>",exit_func) main_application.bind("<Control-f>",find_function) main_application.bind("<Control-b>",change_bold) main_application.bind("<Control-i>",change_italic) main_application.bind("<Control-u>",underline_text) main_application.bind("<Control-Alt-x>",clear_all) main_application.bind("<Control-z>",undo) main_application.bind("<Control-y>",redo)
# By RΨST-4M 🚀 # EightSoft Academy from tkinter import * from tkinter import messagebox from tkinter import ttk # Normal Tkinter.* widgets are not themed! from ttkthemes import ThemedTk root = ThemedTk(theme="breeze") root.title("Menu Bar") root.iconbitmap('examples/photos/icon.ico') root.geometry("400x400") # Crate a Menu my_menu = Menu(root) root.config(menu=my_menu) # Create a functions for commands def command_new(): """When you press File->New ... the following function code will work""" ttk.Label(root, text="You Clicked New ...").pack() def command_cut(): ttk.Label(root, text="Awesome, it is working!").pack() def question(): response = messagebox.askquestion("Question", "Do you liked Menu Bars?") if response == "yes":
import pyqrcode from tkinter import * import tkinter.ttk as ttk from ttkthemes import ThemedTk from PIL import Image, ImageTk win = ThemedTk(theme="equilux") win.title("QR Code Generator") win.config(background="#181818") def Generate(): text = entryl.get() qr = pyqrcode.create(text) file_name = "my qrcode" save_path = r'C:\Users\Jeceey\Downloads\ ' name = save_path + file_name + '.png' qr.png(name, scale=10) image = Image.open(name) image = image.resize((400, 400), Image.ANTIALIAS) image = ImageTk.PhotoImage(image) win.imagelabel.config(image=image) win.imagelabel = image text = ttk.Label(win, text="Enter text or link :") text.grid(row=0, column=0, padx=0, pady=3) entryl = ttk.Entry(win, width=40) entryl.grid(row=0, column=1, padx=3, pady=3)
self.btnfrm[2].place(x=960, y=150, width=304, height=64, anchor='center') self.btnfrm[3].place(x=1163, y=118, width=304, height=64) self.btnfrm[4].place(x=1822, y=118, width=304, height=64, anchor='ne') root.bind('<Enter>', self.button_on_enter) root.bind('<Leave>', self.button_on_leave) #will be useful in the future ''' distribution_of_cases = distribution_of_cases(root) distribution_of_cases.place(x=0, y=0, width=1200, height=700) ''' root = ThemedTk(theme='breeze') root.geometry('1920x1080') root.config(bg='#191919') root.title('Covid-19 Data Analysis') root.state('zoomed') app = main() app.widget() root.mainloop() quit()
class MainWindow: def __init__(self): self.rootpath = '.\\' # self.root = mtTkinter.Tk() self.root = ThemedTk(theme="breeze") self.initFiles() self.initMainWindowUI() self.style = ttk.Style() # print(self.style.theme_names()) # self.style.theme_use('xpnative') def run(self): self.root.mainloop() def initFiles(self): files = [ 'out_input.dir', 'out_output.dir', 'out_exe.dir', 'empty.tgen', 'in_input.dir', 'in_exe.dir','script.tgen', 'tgenValidation.log' ] for file in files: filePath = self.rootpath + 'appdata\\files\\' + file if not isfile(filePath): f = open(filePath, 'w+') f.close() def initMainWindowUI(self): self.root.title('Testcase Generator') # self.root.iconbitmap('favicon.ico') self.root.iconbitmap(self.rootpath + 'appdata\\images\\favicon.ico') w = 655 # width for the Tk root h = 610 # height for the Tk root # get screen width and height ws = self.root.winfo_screenwidth() # width of the screen hs = self.root.winfo_screenheight() # height of the screen # calculate x and y coordinates for the Tk root window x = (ws/2) - (w/2) y = (hs/2) - (h/2) # set the dimensions of the screen # and where it is placed self.root.geometry('%dx%d+%d+%d' % (w, h, x, y)) self.root.resizable(0, 0) menubar = Menu(self.root) self.root.config(menu=menubar) # settings_menu = Menu(menubar, tearoff=0) # menubar.add_cascade(label="Format", menu=settings_menu) # settings_menu.add_command(label="Input File") # settings_menu.add_separator() # settings_menu.add_command(label="Output File") about_menu = Menu(menubar) menubar.add_cascade(label="About", command=self.openAbout) self.tabs = ttk.Notebook(self.root) self.tabs.pack() self.inputGeneratorTab = inputGenerator.InputGenerator(self.tabs) self.outputGeneratorTab = outputGenerator.OutputGenerator(self.root, self.tabs) self.tabs.add(self.inputGeneratorTab.app, text="Input Generator") self.tabs.add(self.outputGeneratorTab.app, text="Output Generator") def openAbout(self): self.about = about.About()