class About: def __init__(self, parent): self.parent = parent self.style = Style() self.style.theme_use('clam') self.root = Toplevel() self.root.title('pyEdit - About') self.root.resizable(False, False) self.root.minsize(200, 50) self.root.columnconfigure(0, weight=1) self.root.bind('<Expose>', lambda e: Utils.on_expose(self)) self.root.wm_protocol('WM_DELETE_WINDOW', lambda: Utils.on_close(self)) self.label_app_name = Label(self.root, text='pyEdit (Lightweight IDE)') self.label_app_name.grid(column=0, row=0, sticky='nsew', ipadx=5, ipady=5) self.label_author = Label(self.root, text='Author: Marek Kouřil') self.label_author.grid(column=0, row=1, sticky='nsew', ipadx=5, ipady=5) self.label_year = Label(self.root, text='2016') self.label_year.grid(column=0, row=2, sticky='nsew', ipadx=5, ipady=5) self.label_course = Label(self.root, text='\'URO\' course') self.label_course.grid(column=0, row=3, sticky='nsew', ipadx=5, ipady=5)
def __init__(self, widget): self.widget = widget self.widget.bind('<Enter>', self.show) self.widget.bind('<Leave>', self.hide) self.tooltip = None style = Style() style.configure('tt.TLabel', background='#fbfbf4', foreground='#333333')
def __init__(self, widget): self.widget = widget self.widget.bind("<Enter>", self.show) self.widget.bind("<Leave>", self.hide) self.tooltip = None style = Style() style.configure("tt.TLabel", background="#fbfbf4", foreground="#333333")
def __init__(self, parent): Notebook.__init__(self, parent, style='Type.TNotebook') logger = logging.getLogger(__name__) s = Style() s.configure('Type.TNotebook', tabposition="se") self.page_tiborcim = Frame(self) self.page_python = Frame(self) self.add(self.page_tiborcim, text='Tiborcim') self.add(self.page_python, text='Python') self.text_tiborcim = CimTiborcimText(self.page_tiborcim, self) self.vbar_python = Scrollbar(self.page_python, name='vbar_python') self.xbar_python = Scrollbar(self.page_python, name='xbar_python', orient="horizontal") self.text_python = Text(self.page_python, wrap="none", state="disabled", borderwidth='0p') self.vbar_python['command'] = self.text_python.yview self.vbar_python.pack(side="right", fill="y") self.text_python['yscrollcommand'] = self.vbar_python.set self.xbar_python['command'] = self.text_python.xview self.xbar_python.pack(side="bottom", fill="x") self.text_python['xscrollcommand'] = self.xbar_python.set self.text_python.pack(expand=1, fill="both") self.viewmode = "tiborcim" self.saved = True self.filename = None
def set_theme_defaults(cls, master, theme_name='default', style_name=None): style = Style(master) if style_name is None: style_name = cls.STYLE_NAME style.theme_settings(theme_name, { style_name: cls.STYLE_DEFAULTS })
class Main(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.info = {} self.window = None self.size = (640, 480) self.fields = [] self.init_ui() def init_ui(self): self.parent.title("Node Writer") self.style = Style() self.style.theme_use("alt") self.pack(fill="both", expand=True) menubar = Menu(self.parent) self.parent.config(menu=menubar) menubar.add_command(label="New", command=self.onNew) menubar.add_command(label="Show Info", command=self.get_info) menubar.add_command(label="Exit", command=self.quit) self.canvas = Canvas(self, background="white", width=self.size[0], height=self.size[1]) self.canvas.pack(fill="both", expand=1) self.canvas.bind("<Motion>", self.move_boxes) def move_boxes(self, event): print(event.x, event.y) """ x, y = (event.x-1, event.y-1) x1, y1, x2, y2 = self.canvas.bbox("test") if x > x1 and y > y1 and x < x2 and y < y2: print("Hit") else: print("Missed") """ def onNew(self): new = Node(self, "Node_entry") label = new.insert_entry_field("Labels") label2 = new.insert_entry_field("Labels2") text = new.insert_text_field("Text") new.ok_cancel_buttons() def get_info(self): x, y = (self.size[0]/2, self.size[1]/2) for i in self.info: label_frame= LabelFrame(self, text="name") label_frame.pack(fill="y") for entry in self.info[i]["Entry"]: frame = Frame(label_frame) frame.pack(fill="x") label = Label(label_frame, text=self.info[i]["Entry"][entry], width=6) label.pack(side="left", anchor="n", padx=5, pady=5) for text in self.info[i]["Text"]: frame = Frame(label_frame) frame.pack(fill="x") label = Label(label_frame, text=self.info[i]["Text"][text], width=6) label.pack(side="left", anchor="n", padx=5, pady=5) window = self.canvas.create_window(x, y, window=label_frame, tag="test")
def __init__(self, title="", message="", button="Ok", image=None, checkmessage="", style="clam", **options): """ Create a messagebox with one button and a checkbox below the button: parent: parent of the toplevel window title: message box title message: message box text button: message displayed on the button image: image displayed at the left of the message checkmessage: message displayed next to the checkbox **options: other options to pass to the Toplevel.__init__ method """ Tk.__init__(self, **options) self.resizable(False, False) self.title(title) s = Style(self) s.theme_use(style) if image: Label(self, text=message, wraplength=335, font="Sans 11", compound="left", image=image).grid(row=0, padx=10, pady=(10, 0)) else: Label(self, text=message, wraplength=335, font="Sans 11").grid(row=0, padx=10, pady=(10, 0)) b = Button(self, text=button, command=self.destroy) b.grid(row=2, padx=10, pady=10) self.var = BooleanVar(self) c = Checkbutton(self, text=checkmessage, variable=self.var) c.grid(row=1, padx=10, pady=0, sticky="e") self.grab_set() b.focus_set() self.wait_window(self)
class MainWindow(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.grid() self.init_ui() self.wallhandler = WallHandler() self.reddit = Reddit() def init_ui(self): self.parent.title("Papers") self.style = Style() self.style.theme_use("clam") frame = Frame(self, relief=RAISED, borderwidth=1) frame.grid(row=0, column=0) label = Label(frame, text="Change Wallpaper") label.grid(row=0, column=0) button = Button(frame, text="Change", command=self.change) button.grid(row=1, column=0) label = Label(frame, text="Fetch Wallpapers") label.grid(row=2, column=0) button = Button(frame, text="Fetch", command=self.fetch) button.grid(row=3, column=0) def change(self): self.wallhandler.run() def fetch(self): self.reddit.run()
class MainWindow(Frame): """ Macro class for the main program window """ def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.parent.title('PyNBTx %s' % __version__) self.style = Style() self.style.theme_use('default') self.style.configure('TButton', padding=0) self.pack(fill=BOTH, expand=1) self.menu = MainMenu(root) self.toolbar = ToolBar(self) self.tree = Treeview(self, height=20) self.tree_display = TreeDisplay(self.tree) self.ui_init() def ui_init(self): root['menu'] = self.menu self.toolbar.pack(anchor=NW, padx=4, pady=4) self.tree.column('#0', width=300) self.tree.pack(fill=BOTH, anchor=NW, padx=4, pady=4)
def main(): ''' Runs main application GUI. ''' logger = get_logger() logger.info('pyDEA started as a GUI application.') root = Tk() root.report_callback_exception = show_error # load logo if "nt" == os.name: iconfile = pkg_resources.resource_filename(PACKAGE, 'pyDEAlogo.ico') root.wm_iconbitmap(bitmap=iconfile) else: iconfile = pkg_resources.resource_filename(PACKAGE, 'pyDEAlogo.gif') img = PhotoImage(file=iconfile) root.tk.call('wm', 'iconphoto', root._w, img) # change background color of all widgets s = Style() s.configure('.', background=bg_color) # run the application app = MainFrame(root) root.protocol("WM_DELETE_WINDOW", (lambda: ask_quit(app))) center_window(root, root.winfo_screenwidth() - root.winfo_screenwidth()*0.15, root.winfo_screenheight() - root.winfo_screenheight()*0.15) root.mainloop() logger.info('pyDEA exited.')
def create_frame(self): frame_style = Style() frame_style.theme_use('alt') frame_style.configure("TFrame", relief='raised') self.frame = Frame(self.window, style="frame_style.TFrame") self.frame.rowconfigure(1) self.frame.columnconfigure(1) self.frame.grid(row=0, column=0)
class poly_pocket(Frame): def __init__(self): window = Tk() self.parent = window window.geometry("800x600+50+50") Frame.__init__(self, window) self.baseline = 0 self.initUI() window.mainloop() def initUI(self): # Initialize and name Window self.parent.title("Poly Pocket") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) def new_baseline(): return def old_baseline(): return def test(baseline): return def spark_connect(): return def leap_connect(): return def quit(): self.parent.destroy() return welcome = "Welcome to Poly Pocket!" welcome_label = Label(self, text=welcome, font=("Helvetica", 24)) welcome_label.place(x=5, y=5) welcome_label.pack() baseline_button = Button(self, text="New Baseline", command=new_baseline()) recover_baseline_button = Button(self, text="Recover Baseline", command=old_baseline()) test_button = Button(self, text="Conduct Test", command=test(self.baseline)) connect_leap_button = Button(self, text="Establish Leap Connection", command=leap_connect) connect_spark_button = Button(self, text="Establish Spark Connection", command=spark_connect) exit_button = Button(self, text="Quit", command=quit) baseline_button.place(relx=0.5, rely=0.3, anchor=CENTER) recover_baseline_button.place(relx=0.5, rely=0.4, anchor=CENTER) test_button.place(relx=0.5, rely=0.5, anchor=CENTER) connect_leap_button.place(relx=0.5, rely=0.6, anchor=CENTER) connect_spark_button.place(relx=0.5, rely=0.7, anchor=CENTER) exit_button.place(relx=0.5, rely = 0.8, anchor=CENTER)
def initUI(self, mainFrame): """initialize the User Interface""" # styles style = Style() style.configure("GRN.TLabel", background="#ACF059") style.configure("GRN.TFrame", background="#ACF059") style.configure("BLK.TFrame", background="#595959") # create top frame topFrame = Frame(mainFrame, style="GRN.TFrame", padding=8) topFrame.pack(fill=BOTH, side=TOP) # create black border borderFrame = Frame(mainFrame, style="BLK.TFrame") borderFrame.pack(fill=BOTH, side=TOP) # create add player frame addPlayerFrame = Frame(mainFrame, padding=8) addPlayerFrame.pack(side=TOP) # create text field for add button self.nameFieldVar = StringVar() self.playerNameEntry = Entry(addPlayerFrame, textvariable = self.nameFieldVar) self.playerNameEntry.pack(side=LEFT) # create add player button addButton = Button(addPlayerFrame, text="Add player") addButton.pack(side=LEFT) # create choose game list self.currentGame = StringVar() self.currentGame.set(self.gameList[0]) gameDropDown = OptionMenu(mainFrame, self.currentGame, self.gameList[0], *self.gameList) gameDropDown.pack(side=TOP) # create start game button startGameButton = Button(mainFrame, text="Start") startGameButton.bind("<Button-1>", self.startGame) startGameButton.pack(side=TOP) # create label and set text self.playerString = StringVar() self.playerString.set(self.buildPlayerHeaderString()) headerLabel = Label(topFrame, textvariable=self.playerString, style="GRN.TLabel") headerLabel.pack(side=TOP) addButton.bind("<Button-1>", self.onAddPlayerClick) self.playerNameEntry.bind("<Key>", self.onAddPlayerEnter) #set focus self.playerNameEntry.focus()
class Help: def __init__(self, parent): self.parent = parent self.style = Style() self.style.theme_use('clam') self.root = Toplevel() self.root.title('pyEdit - Help') self.root.resizable(False, False) self.root.minsize(200, 50) self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) self.root.bind('<Expose>', lambda e: Utils.on_expose(self)) self.root.wm_protocol('WM_DELETE_WINDOW', lambda: Utils.on_close(self)) self.text = self.get_content() self.font = font.Font(family='Monospace', size=10, weight='normal') self.font_spacing = None self.font_spacing = self.font.metrics('descent') self.text_widget = Text(self.root, relief='flat', bd=0, font=self.font) self.text_widget.grid(column=0, row=0, sticky='nsew') self.text_widget.delete('1.0', 'end') self.text_widget.insert('1.0', self.text) self.text_widget.config(state='disabled') self.scrollbar = Scrollbar(self.root, bd=0, orient='vertical', command=self.text_widget.yview) self.scrollbar.grid(column=1, row=0, sticky='nsew') self.text_widget.config(yscrollcommand=self.scrollbar.set) def get_content(self): text = '' try: file = open(self.parent.current_dir + '/help.txt', 'r') file.seek(0, 2) size = file.tell() file.seek(0, 0) text = file.read(size) file.close() except IOError: print('IOError while reading help text.') return text
def __init__(self, master, version): Frame.__init__(self, master) master.title(version[:-5]) # MAKE IT LOOK GOOD style = Style() style.configure("atitle.TLabel", font="tkDefaultFont 12 bold italic") # CREATE AND SET VARIABLES self.version = version self.description = None self.logo = None self.status_lbl = StringVar() # TO HOLD STATUS VARIABLE IN STATUSBAR # CREATE ROOT MENUBAR menubar = Menu(self.master) self.master["menu"] = menubar self.master.option_add("*tearOff", False) # CREATE FILE MENU self.menu_file = Menu(menubar, name="file") self.menu_file.add_separator() self.menu_file.add_command(label="Exit", accelerator="Alt-F4", command=self.master.destroy) menubar.add_cascade(menu=self.menu_file, label="File", underline=0) # CREATE HELP MENU menu_help = Menu(menubar, name="help") menu_help.add_command(label="About", command=self.show_about) menubar.add_cascade(menu=menu_help, label="Help", underline=0) # CREATE BUTTON BAR self.button_bar = Frame(self.master, relief="groove", padding="0 1 0 2") self.button_bar.grid(sticky="ew") # SETUP PRIMARY FRAME FOR WIDGETS self.frame = Frame(self.master, padding="25") self.frame.grid(sticky="nsew") # CREATE STATUS BAR Separator(self.master).grid(row=8, sticky="ew") self.status_bar = Frame(self.master, padding="8 0 0 1") self.status_bar.grid(row=9, sticky="ews") Label(self.status_bar, textvariable=self.status_lbl).grid(row=0, column=0, padx="0 7") Label(self.status_bar, text=self.version[-5:]).grid(row=0, column=8) Sizegrip(self.status_bar).grid(row=0, column=9, sticky="e") # CONFIGURE AUTO-RESIZING self.master.columnconfigure(0, weight=1) self.master.rowconfigure(1, weight=1) self.frame.columnconfigure(0, weight=1) # self.frame.rowconfigure(0, weight=1) self.status_bar.columnconfigure(1, weight=1)
def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.music_root = '' self.query_path = '' self.extractor = Extractor(n_frames=40, n_blocks=100, learning_rate=0.00053, verbose=True) self.style = Style() self.style.theme_use("default") padx = 2 pady = 2 root_select_button = Button(self, text="Select a directory") root_select_button.pack(fill=tkinter.X, padx=padx, pady=pady) root_select_button.bind("<Button-1>", self.set_music_root) analyze_button = Button(self, text="Analyze") analyze_button.pack(fill=tkinter.X, padx=padx, pady=pady) analyze_button.bind("<Button-1>", self.analyze) query_select_button = Button(self, text="Select a file") query_select_button.pack(fill=tkinter.X, padx=padx, pady=pady) query_select_button.bind("<Button-1>", self.set_query_path) search_button = Button(self, text="Search similar songs") search_button.pack(fill=tkinter.X, padx=padx, pady=pady) search_button.bind("<Button-1>", self.search_music) self.pack(fill=BOTH, expand=1)
def initUI(self): self.parent.title("Windows") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(3, weight=1) self.rowconfigure(5, pad=7) lbl = Label(self, text="Windows") lbl.grid(sticky=W, pady=4, padx=5) area = Text(self) area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N) abtn = Button(self, text="Activate") abtn.grid(row=1, column=3) cbtn = Button(self, text="Close") cbtn.grid(row=2, column=3, pady=4) hbtn = Button(self, text="Help") hbtn.grid(row=5, column=0, padx=5) obtn = Button(self, text="OK") obtn.grid(row=5, column=3)
def initUI(self): self.parent.title("Windows") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(6, weight=1) self.rowconfigure(5, pad=7) lbl = Label(self, text="BookManager") lbl.grid(sticky=W, pady=4, padx=5) self.area = Text(self) #WHITE TEXT BOX self.area.grid(row=1, column=0, columnspan=3, rowspan=4, padx=5, sticky=E+W+S+N) abtn = Button(self, text="add", command=self.press_add) abtn.grid(row=1, column=3) srcbtn = Button(self, text="search", command=self.press_search) srcbtn.grid(row=2, column=3, pady=3) rbtn = Button(self, text="remove", command=self.press_remove) rbtn.grid(row=3, column=3, pady=3) sbtn = Button(self, text="show all", command=self.press_show) sbtn.grid(row=4, column=3, pady=3)
def initUI(self): self.username = '' self.r = praw.Reddit(USERAGENT) self.parent.title("") self.style = Style() self.style.theme_use("clam") self.pack(fill=BOTH, expand = 1) self.labelU = Label(self, text="U:") self.labelP = Label(self, text="P:") self.entryUsername = Entry(self) self.entryUsername.config(relief='flat') self.entryUsername.focus_set() self.entryUsername.bind('<Return>', lambda event: self.login(self.entryUsername.get())) self.entryUsername.bind('<Up>', lambda event: self.entryUsername.insert(0, self.username)) self.quitbutton = Button(self, text="Quit", command= lambda: self.quit()) self.quitbutton.config(width=6) self.labelKarma = Label(self, text = '•') self.labelKarma.grid(row = 3, column = 1) self.labelU.grid(row=0, column=0) self.entryUsername.grid(row=0, column=1) self.quitbutton.grid(row=2, column=1, pady=4) self.usernamelabel = Label(self, text='') self.usernamelabel.grid(row=1, column=1)
def __init__(self, parent, case, val_ou_pos, **options): """ créer le Toplevel 'À propos de Bracelet Generator' """ Toplevel.__init__(self, parent, **options) self.withdraw() self.type = val_ou_pos # clavier pour rentrer une valeur ou une possibilité self.overrideredirect(True) self.case = case self.transient(self.master) self.style = Style(self) self.style.configure("clavier.TButton", font="Arial 12") self.boutons = [[Button(self, text="1", width=2, style="clavier.TButton", command=lambda: self.entre_nb(1)), Button(self, text="2", width=2, style="clavier.TButton", command=lambda: self.entre_nb(2)), Button(self, text="3", width=2, style="clavier.TButton", command=lambda: self.entre_nb(3))], [Button(self, text="4", width=2, style="clavier.TButton", command=lambda: self.entre_nb(4)), Button(self, text="5", width=2, style="clavier.TButton", command=lambda: self.entre_nb(5)), Button(self, text="6", width=2, style="clavier.TButton", command=lambda: self.entre_nb(6))], [Button(self, text="7", width=2, style="clavier.TButton", command=lambda: self.entre_nb(7)), Button(self, text="8", width=2, style="clavier.TButton", command=lambda: self.entre_nb(8)), Button(self, text="9", width=2, style="clavier.TButton", command=lambda: self.entre_nb(9))]] for i in range(3): for j in range(3): self.boutons[i][j].grid(row=i, column=j) self.protocol("WM_DELETE_WINDOW", self.quitter) self.resizable(0, 0) self.attributes("-topmost", 0)
def __init__(self, parent): self.parent = parent self.style = Style() self.style.theme_use('clam') self.root = Toplevel() self.root.title('pyEdit - Help') self.root.resizable(False, False) self.root.minsize(200, 50) self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) self.root.bind('<Expose>', lambda e: Utils.on_expose(self)) self.root.wm_protocol('WM_DELETE_WINDOW', lambda: Utils.on_close(self)) self.text = self.get_content() self.font = font.Font(family='Monospace', size=10, weight='normal') self.font_spacing = None self.font_spacing = self.font.metrics('descent') self.text_widget = Text(self.root, relief='flat', bd=0, font=self.font) self.text_widget.grid(column=0, row=0, sticky='nsew') self.text_widget.delete('1.0', 'end') self.text_widget.insert('1.0', self.text) self.text_widget.config(state='disabled') self.scrollbar = Scrollbar(self.root, bd=0, orient='vertical', command=self.text_widget.yview) self.scrollbar.grid(column=1, row=0, sticky='nsew') self.text_widget.config(yscrollcommand=self.scrollbar.set)
class PwRd(Frame): def __init__(self,parent): Frame.__init__(self, parent,background="white") self.parent = parent self.initUI() def initUI(self): self.parent.title("Start") self.style=Style() self.style.theme_use("default") frame = Frame(self,relief=RAISED,borderwidth=1,background="white") frame.pack(fill=BOTH, expand=1) self.pack(fill=BOTH, expand=1) closeButton = Button(self, text="Close",command=self.quit) closeButton.pack(side=RIGHT, padx=5, pady=5) okButton = Button(self, text="OK") okButton.pack(side=RIGHT)
def init_ui(self): self.parent.title("Node Writer") self.style = Style(self) # This doesn't seem to self.style.theme_use("alt") # do anything in Windows. self.pack(fill="both", expand=True) self.menubar = TopMenuBar(self) self.parent.config(menu=self.menubar)
def main(): log = logging.getLogger() log.setLevel(logging.ERROR) parser = argparse.ArgumentParser(description='Run stuff') parser.add_argument('--server', action='store_true', default=False) parser.add_argument('--debug', action='store_true', default=False) parser.add_argument('--file_root', default=os.path.expanduser('~')) parser.add_argument('--full', action='store_true', default=False) args = parser.parse_args() if args.debug: log.setLevel(logging.DEBUG) root = Tk() config = Config() config.full_screen = args.full config.set_file_root(os.path.expanduser(args.file_root)) s = Style() s.configure('Treeview', rowheight=config.tree_item_height) s.configure('TButton', font='Helvetica 16') s.configure('Vertical.TScrollbar', arrowsize=config.sb_size) if args.server: fs = FileServer(config.web_port, config) fs.run(debug=True) else: root.title('copilot') app = HomeFrame(root, config) root.mainloop()
def initUI(self): self.parent.title("Book Manager") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.columnconfigure(0, pad=3) self.columnconfigure(1, pad=3) self.columnconfigure(2, pad=3) self.rowconfigure(0, pad=3) self.rowconfigure(1, pad=3) self.rowconfigure(2, pad=3) self.rowconfigure(3, pad=3) self.rowconfigure(4, pad=3) self.rowconfigure(5, pad=3) self.rowconfigure(6, pad=3) self.input_bname='' self.input_aname='' self.input_price=0 self.delete='' lb_bookname = Label(self, text="bookname:") lb_bookname.grid(row=0, column =0 ,sticky=W, pady=4, padx=5) self.entry_bookname = Entry(self) self.entry_bookname.grid(row=0, column = 1 ) lb_author = Label(self, text="author:") lb_author.grid(row=0, column =2,sticky=W, pady=4, padx=5) self.entry_author = Entry(self) self.entry_author.grid(row=0, column = 3 ) lb_price = Label(self, text="price:") lb_price.grid(row=0, column =4 ,sticky=W, pady=4, padx=5) self.entry_price = Entry(self) self.entry_price.grid(row=0, column = 5 ,padx=15) abtn = Button(self, text="Add", command=lambda:self.clicked_add()) abtn.grid(row=0, column=6) sbtn = Button(self, text="Serach", command = lambda:self.clicked_search()) sbtn.grid(row=1, column=6, pady=4) dbtn = Button(self, text="Delete", command = lambda:self.clicked_delete()) dbtn.grid(row=2, column=6, pady=4) self.lb = Listbox(self) self.lb.grid(row=3,column = 0, columnspan = 6,rowspan= 4, sticky = E+W+S+N) self.lb.bind("<<ListboxSelect>>", self.onSelect)
def __init__(self, parent, motspiller): Frame.__init__(self, parent) self.parent = parent self.spiller = motspiller self.resultat = [] self.resultat_label = StringVar() self.resultat_label.set("Beskrivelse av siste spill kommer her") self.style = Style() self.fig = None
class MM_Window(Frame): def __init__(self, parent): Frame.__init__(self, parent, background="white") self.parent = parent self.parent.title("Centered window") self.pack(fill=BOTH, expand=1) self.centerWindow() self.initUI() def initUI(self): self.parent.title("Quit button") self.style = Style() self.style.theme_use("default") # self.pack(fill=BOTH, expand=1) quitButton = Button(self, text="Quit", command=self.quit) quitButton.place(x=200, y=50) buttons_list = [] g=0 c=0 for i in range(1,52): crnt_button = Label(self, text=str(i),background=FF0000) crnt_button.grid(row=g, column=c) buttons_list.append(crnt_button) c += 1 if i%10 ==0: g +=1 c=0 def centerWindow(self): w = 290 h = 150 sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - w)/2 y = (sh - h)/2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
def initUI(self): self.parent.title("GPA Calculator") self.style = Style() self.style.theme_use("default") frame = Frame(self, relief=RAISED, borderwidth=1) frame.pack(fill=BOTH, expand=True) self.pack(fill=BOTH, expand=True) calculateButton = Button(self, text="Calculate", command=lambda: self.onPressCalc) calculateButton.pack(side=RIGHT, padx=5, pady=5)
class GPACalc(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def onPressCalc(): print("Hello world") def initUI(self): self.parent.title("GPA Calculator") self.style = Style() self.style.theme_use("default") frame = Frame(self, relief=RAISED, borderwidth=1) frame.pack(fill=BOTH, expand=True) self.pack(fill=BOTH, expand=True) calculateButton = Button(self, text="Calculate", command=lambda: self.onPressCalc) calculateButton.pack(side=RIGHT, padx=5, pady=5)
def _create_ui(self): self.pygubu_builder = Builder() self.pygubu_builder.add_from_file(path.join(SCRIPT_DIR, "forms", "secondary_window.ui")) self.style = Style() self.canvas = list() self.predator_draw_object = [None, None, None, None] self.current_background_color = BACKGROUND_COLOR self.setup()
class PTMFrame(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("PTM Generator v0.3") self.style = Style() self.style.theme_use("default") self.fitter_filepath_str = "" self.currlistidx = -1 frame1 = Frame(self, relief=RAISED, borderwidth=1) frame1.pack(fill=BOTH, expand=True) self.listbox = Listbox(frame1, width=40) self.listbox.pack(side=LEFT, fill=Y, padx=5, pady=5, ipadx=5, ipady=5) self.imageview = Label(frame1) self.imageview.pack(side=LEFT, fill=BOTH, expand=True) frame11 = Frame(frame1) self.selectFilesButton = Button(frame11, text="Select Files", command=self.selectfiles) self.selectFilesButton.pack(fill=X, padx=5, pady=5) self.shootAgainButton = Button(frame11, text="Shoot Again", command=self.shootAgain) self.shootAgainButton.pack(fill=X, padx=5, pady=5) self.listbox.bind('<<ListboxSelect>>', self.onselect) frame11.pack(fill=X) frame2 = Frame(self, relief=RAISED, borderwidth=1) frame2.pack(fill=X) self.workdir_label = Label(frame2, text='Folder to Watch') self.workdir_label.pack(side=LEFT, fill=X, padx=5, pady=5) self.workdir_text = Entry(frame2, text='') self.workdir_text.pack(side=LEFT, fill=X, expand=True, padx=5, pady=5) self.workdirButton = Button(frame2, text="Select Folder", command=self.selectworkdir) self.workdirButton.pack(side=LEFT, fill=X, padx=5, pady=5) self.workdir_text.delete(0, END) dirname = shell.SHGetFolderPath(0, shellcon.CSIDL_MYPICTURES, None, 0) self.workdir_text.insert(0, dirname) p = Path(dirname) self.workingpath = p frame3 = Frame(self, relief=RAISED, borderwidth=1) self.fitter_label = Label(frame3, text='PTMFitter') self.fitter_label.pack(side=LEFT, fill=X, padx=5, pady=5) self.fitter_text = Entry(frame3, text='', textvariable=self.fitter_filepath_str) self.fitter_text.pack(side=LEFT, fill=X, expand=True, padx=5, pady=5) self.ptmButton = Button(frame3, text="PTMFitter", command=self.PTMfitter) self.ptmButton.pack(side=LEFT, fill=X, padx=5, pady=5) frame3.pack(fill=X) frame4 = Frame(self, relief=RAISED, borderwidth=1) self.COM_label = Label(frame4, text='Port') self.COM_label.pack(side=LEFT, fill=X, padx=5, pady=5) # Create a Tkinter variable self.varSerialPort = StringVar(root) # Dictionary with options choices = [] arduino_ports = [ p.device for p in serial.tools.list_ports.comports() if 'CH340' in p.description ] #for p in serial.tools.list_ports.comports(): # pass #print( p.description) for p in arduino_ports: choices.append(p) if len(arduino_ports) > 0: self.varSerialPort.set(choices[0]) # set the default option self.serial_exist = True else: choices.append("NONE") self.varSerialPort.set(choices[0]) # set the default option self.serial_exist = False self.popupMenu = OptionMenu(frame4, self.varSerialPort, *choices) self.popupMenu.pack(side=LEFT, fill=X, padx=5, pady=5) self.LEDControlButton = Button(frame4, text="LEDControl", command=self.LEDControl) self.LEDControlButton.pack(side=LEFT, fill=X, padx=5, pady=5) self.shootAllButton = Button(frame4, text="Shoot All", command=self.shootAll) self.shootAllButton.pack(side=LEFT, fill=X, padx=5, pady=5) self.generateButton = Button(frame4, text="Generate PTM File", command=self.generatePTM) self.generateButton.pack(side=LEFT, fill=X, padx=5, pady=5) #self.testButton = Button(frame4, text="Test",command=self.test) #self.testButton.pack( side=LEFT, fill=X,padx=5, pady=5) if (not self.serial_exist): self.shootAllButton["state"] = "disabled" self.LEDControlButton["state"] = "disabled" self.shootAgainButton["state"] = "disabled" # on change dropdown value frame4.pack(fill=X) self.pack(fill=BOTH, expand=True) options = {} options['initialdir'] = 'C:\\' options['mustexist'] = False options['parent'] = self.parent options['title'] = 'This is a title' #self.serial = serial.Serial() self.filelist = [] fitter = Path.cwd().joinpath("ptmfitter.exe") if fitter.exists(): self.fitter_filepath = fitter self.fitter_text.delete(0, END) self.fitter_text.insert(0, str(fitter)) print() def LEDControl(self): if (not self.serial_exist): return self.openSerial() d = LEDDialog(self) self.closeSerial() return def shootAgain(self): if (not self.serial_exist): print("no serial") return if self.currlistidx < 0: print("not selected") return manager.busy() before = dict([(f, None) for f in os.listdir(str(self.workingpath))]) self.openSerial() msg = "SHOOT," + str(self.currlistidx + 1) self.sendSerial(msg) time.sleep(7) msg = "OFF" self.sendSerial(msg) ret_msg = self.receiveSerial() after = dict([(f, None) for f in os.listdir(str(self.workingpath))]) added = [f for f in after if not f in before] print(added) if (added): fn = added[0] pfn = Path(self.workingpath, fn) filename = self.process_filename(pfn) self.listbox.delete(self.currlistidx) self.listbox.insert(self.currlistidx, filename) self.filelist[self.currlistidx] = filename self.setimage(filename) self.update() self.closeSerial() return def PTMfitter(self): filename = filedialog.askopenfilename(initialdir=".", title="Select file") filepath = Path(filename) if filepath.exists(): self.fitter_filepath = filepath self.fitter_filepath_str = str(filepath) #print( self.fitter_filepath_str ) self.fitter_text.delete(0, END) self.fitter_text.insert(0, str(filepath)) #self.fitter_label.text = str( filepath ) #self.fitter_text.text = str( filepath ) def selectworkdir(self): #print( "open") currdir = str(self.workingpath) dirname = filedialog.askdirectory(initialdir=currdir, title="Select folder") p = Path(dirname) self.currdirname = p.parts[-1] #self.workingdir = str(p) self.workingpath = p #self.workdir_text.text = str(p) self.workdir_text.delete(0, END) self.workdir_text.insert(0, str(p)) self.imageview.image = None self.filelist = [] self.listbox.delete(0, 'end') def selectfiles(self): #print( "open") currdir = str(self.workingpath) filenames = filedialog.askopenfilenames(initialdir=currdir, title="Select files") lst = list(filenames) #lst.sort() self.filelist = [] self.listbox.delete(0, 'end') if len(lst) > 0: i = 1 for fn in lst: print(str(fn)) filename = self.process_filename(fn) self.listbox.insert(i, str(filename)) self.filelist.append(filename) #self.text_input3.text += ",".join([str(coord) for coord in lp[i-1]]) i += 1 def process_filename(self, fn): filename = os.path.normpath(fn) p = Path(filename) if p.suffix in ['.JPG', '.jpg']: new_p = p.with_suffix('.jpg') return str(new_p) def opendir(self): currdir = str(self.workingpath) dirname = filedialog.askdirectory(initialdir=currdir, title="Select directory") p = Path(dirname) self.currdirname = p.parts[-1] #self.workingdir = str(p) self.workingpath = p #self.workdir_text.text = str(p) self.workdir_text.delete(0, END) self.workdir_text.insert(0, str(p)) self.imageview.image = None self.filelist = [] if p.is_dir(): self.listbox.delete(0, 'end') i = 1 for x in p.iterdir(): if not x.is_dir(): if x.suffix in ['.JPG', '.jpg']: new_x = x.with_suffix('.jpg') self.listbox.insert(i, str(new_x.name)) self.filelist.append(new_x) #self.text_input3.text += ",".join([str(coord) for coord in lp[i-1]]) i += 1 else: pass #print( x.suffix) #print(dirname) def generatePTM(self): if self.listbox.size() != 50: messagebox.showerror(message="Must be 50 image files!") #print( "must be 50 files") return ret_str = "50\n" for i in range(50): ret_str += str(self.filelist[i]) + " " + " ".join( [str(f) for f in lp_list[i]]) + "\n" options = {} options['initialdir'] = 'C:\\' options['mustexist'] = False options['parent'] = self options['title'] = 'Save light position file' netfilename = self.workingpath.parts[-1] lpfilename = Path(self.workingpath, netfilename + ".lp") # file = open(str(lpfilename), 'w') file.write(ret_str) file.close() saveoptions = {} saveoptions['defaultextension'] = '.ptm' saveoptions['filetypes'] = [('all files', '.*'), ('PTM files', '.ptm')] saveoptions['initialdir'] = self.workingpath saveoptions['initialfile'] = netfilename + '.ptm' ptmfilename = Path( filedialog.asksaveasfilename(**saveoptions)) # mode='w',**options) #print( ptmfilename ) execute_string = " ".join([ str(self.fitter_filepath), "-i", str(lpfilename), "-o", str(ptmfilename) ]) #print( execute_string ) subprocess.call([ str(self.fitter_filepath), "-i", str(lpfilename), "-o", str(ptmfilename) ]) def openSerial(self): if (not self.serial_exist): return self.serial = serial.Serial(self.varSerialPort.get(), 9600, timeout=2) time.sleep(2) return def closeSerial(self): self.serial.close() return def sendSerial(self, msg): msg = "<" + msg + ">" print(msg) self.serial.write(msg.encode()) def receiveSerial(self): return_msg = self.serial.readline() print(return_msg) return return_msg def test(self): manager.busy() before = dict([(f, None) for f in os.listdir(str(self.workingpath))]) print(before) for i in range(10): time.sleep(5) after = dict([(f, None) for f in os.listdir(str(self.workingpath))]) added = [f for f in after if not f in before] removed = [f for f in before if not f in after] if added: print("Added: ", ", ".join(added)) for fn in added: filename = Path(self.workingpath, fn) self.listbox.insert(END, filename) self.filelist.append(filename) self.setimage(filename) self.update() else: self.listbox.insert(END, 'NONE') self.filelist.append('NONE') self.update() before = after manager.notbusy() def shootAll(self): if (not self.serial_exist): return manager.busy() before = dict([(f, None) for f in os.listdir(str(self.workingpath))]) self.openSerial() for i in range(50): msg = "SHOOT," + str(i + 1) self.sendSerial(msg) time.sleep(7) ret_msg = self.receiveSerial() after = dict([(f, None) for f in os.listdir(str(self.workingpath))]) added = [f for f in after if not f in before] if added: print("Added: ", ", ".join(added)) for fn in added: pfn = Path(self.workingpath, fn) filename = self.process_filename(pfn) self.listbox.insert(END, filename) self.filelist.append(filename) self.setimage(filename) self.update() else: self.listbox.insert(END, 'NONE') self.filelist.append('NONE') self.update() before = after #print(ret_msg) self.sendSerial("OFF") self.closeSerial() manager.notbusy() def onselect(self, evt): w = evt.widget index = int(w.curselection()[0]) self.currlistidx = index #print( "index=",index) value = w.get(index) #print('You selected item %d: "%s"' % (index, value)) if (value == 'NONE'): return self.setimage(value) self.shootAgainButton["state"] = "normal" def busy(self): #print( "busy") self.parent.config(cursor="wait") self.parent.update() def notbusy(self): #print( "not busy") self.parent.config(cursor="") self.parent.update() def setimage(self, filename): manager.busy() ts_start = time.time() img = Image.open(filename) ts_middle1 = time.time() orig_w, orig_h = img.size new_w = self.imageview.winfo_width() new_h = self.imageview.winfo_height() #print( orig_w, orig_h, new_w, new_h ) scale_w = orig_w / new_w scale_h = orig_h / new_h scale = max(scale_w, scale_h) new_w = int(orig_w / scale) - 4 new_h = int(orig_h / scale) - 4 new_img = img.resize((new_w, new_h)) ts_middle2 = time.time() tkImg = ImageTk.PhotoImage(new_img) self.imageview.configure(image=tkImg) self.imageview.image = tkImg new_w2 = self.imageview.winfo_width() new_h2 = self.imageview.winfo_height() #print( orig_w, orig_h, new_w, new_h, new_w2, new_h2 ) ts_end = time.time() #print( "1, 2, 3", ts_middle1 - ts_start, ts_middle2 - ts_middle1, ts_end - ts_middle2, ts_end - ts_start ) manager.notbusy()
self.set(value - resolution + 1) elif evt.y > curr_y + self.sliderlength / 2: self.set(value + resolution - 1) if __name__ == "__main__": root = Tk() len_val = 400 from_val = 0 to_val = 255 tick_val = 10 dig_val = 2 res_val = 5 style = Style() style.theme_use('default') style.configure('my.Vertical.TScale') fr = Frame(root) fr.pack(fill='y') ttks = TtkScale(fr, from_=from_val, to=to_val, orient='vertical', tickinterval=tick_val, digits=dig_val, style='my.Vertical.TScale', resolution=res_val) ttks.pack(fill='y', pady=5, padx=40)
def __init__(self, parent, length=0, from_=0, to=255, orient='vertical', variable=0, digits=None, tickinterval=None, command=None, style=None, showvalue=True, resolution=1): self.from_ = from_ self.to = to self.variable = variable self.length = length self.command = command self.parent = parent super().__init__(parent, length=length, from_=from_, to=to, orient=orient, variable=variable, command=command, style=style) self.digits = digits self.tickinterval = tickinterval self.showvalue = showvalue self.resolution = resolution # set sliderlength st = Style(self) self.bw_val = bw_val = st.lookup('Vertical.Scale.trough', 'borderwidth') self.sliderlength = sliderlength = 32 if showvalue: self.configure(command=self.display_value) def_font = font.nametofont('TkDefaultFont') # if from_ more than to swap values if from_ < to: pass else: from_, to = to, from_ data = np.arange(from_, (to + 1 if tickinterval >= 1 else to + tickinterval), tickinterval) self.data = data = np.round(data, 1) range_vals = tuple(data) len_rvs = len(range_vals) lspace = def_font.metrics('linespace') len_rvs = len(range_vals) data_size = len_rvs * lspace space_size = len_rvs * 3 sizes = data_size + space_size min_len = (sizes if sizes % 50 == 0 else sizes + 50 - sizes % 50) self.len_val = len_val = min_len if length < min_len else length self.configure(length=len_val) self.rel_min = rel_min = (sliderlength / 2 + bw_val) / len_val self.rel_max = rel_max = 1 - (sliderlength / 2 - bw_val) / len_val if range_vals[-1] == to: pass else: max_rv = range_vals[-1] self.mult_y = mult_y = ((max_rv - from_) * rel_max / (to - from_)) self.bind("<Button-1>", self.resolve) self.build(from_, to, rel_min, rel_max, range_vals, len_rvs)
def __init__(self): log.info(f'{__name__} has been initialized.') self.window = Tk() self.window.title(f"FIB v{current_version}") self.window.geometry("380x225") self.style = Style() # if sys.platform == "win32": # self.style.theme_use('winnative') self.window.minsize(380, 200) self.window.wait_visibility(self.window) self.windowWidth = self.window.winfo_reqwidth() self.windowHeight = self.window.winfo_reqheight() # Gets both half the screen width/height and window width/height self.positionRight = int(self.window.winfo_screenwidth() / 2 - self.windowWidth / 2) self.positionDown = int(self.window.winfo_screenheight() / 2 - self.windowHeight / 2) self.window.geometry("+{}+{}".format(self.positionRight, self.positionDown)) self.window.grid_columnconfigure(0, weight=1) self.window.resizable(0, 0) self.window.attributes("-topmost", True) self.window.protocol("WM_DELETE_WINDOW", self.on_closing) self.main_menu = Menu(self.window) self.file_menu = Menu(self.main_menu, tearoff=0) # self.file_menu.add_command(label="Save") self.file_menu.add_command(label="Exit", command=self.menu_exit) self.help_menu = Menu(self.main_menu, tearoff=0) self.help_menu.add_command(label="About", command=self.menu_about) self.help_menu.add_command(label="Change License Key", command=self.menu_change_license) self.main_menu.add_cascade(label="File", menu=self.file_menu) self.main_menu.add_cascade(label="Help", menu=self.help_menu) self.window.config(menu=self.main_menu) self.info_label = Label(self.window, text="STOP BOT: SHIFT + ESC", font=("Helvetica", 16)) self.info_label.grid(column=0, row=0, padx=15, pady=10, columnspan=2) self.btn1 = Button(self.window, text="GENERAL OPTIONS", command=self.options_win, width=50) self.btn1.grid(column=0, row=1, padx=15, pady=5, columnspan=2) self.btn2 = Button(self.window, text="CONFIGURE PARTY", command=self.party_win, width=50) self.btn2.grid(column=0, row=2, padx=15, pady=0, columnspan=2) self.gobtn = Button(self.window, text="<--- START --->", command=self.ready_set_go, width=50) self.gobtn.config(foreground="white", background="blue") self.gobtn.grid(column=0, row=3, padx=15, pady=20, columnspan=2) # self.window.bind('<Control-n>', self.party_win) # self.window.after(300, self.status_win) self.window.mainloop()
class Tooltip(Toplevel): """ Tooltip class """ def __init__(self, parent, **kwargs): """ Create a tooltip with given parent. KEYWORD OPTIONS title, alpha, padx, pady, font, background, foreground, image, text """ Toplevel.__init__(self, parent) if 'title' in kwargs: self.title(kwargs['title']) self.transient(parent) self.attributes('-type', 'tooltip') self.attributes('-alpha', kwargs.get('alpha', 0.75)) self.overrideredirect(True) self.configure(padx=kwargs.get('padx', 4)) self.configure(pady=kwargs.get('pady', 4)) self.font = Font(self, kwargs.get('font', '')) self.style = Style(self) if 'background' in kwargs: bg = kwargs['background'] self.configure(background=bg) self.style.configure('tooltip.TLabel', background=bg) if 'foreground' in kwargs: self.style.configure('tooltip.TLabel', foreground=kwargs['foreground']) self.im = kwargs.get('image', None) self.label = Label(self, text=kwargs.get('text', ''), image=self.im, style='tooltip.TLabel', font=self.font, wraplength='6c', compound=kwargs.get('compound', 'left')) self.label.pack() def configure(self, **kwargs): if 'text' in kwargs: self.label.configure(text=kwargs.pop('text')) if 'image' in kwargs: self.label.configure(image=kwargs.pop('image')) if 'background' in kwargs: self.style.configure('tooltip.TLabel', background=kwargs['background']) if 'foreground' in kwargs: fg = kwargs.pop('foreground') self.style.configure('tooltip.TLabel', foreground=fg) if 'alpha' in kwargs: self.attributes('-alpha', kwargs.pop('alpha')) if 'font' in kwargs: font = Font(self, kwargs.pop('font')) self.font.configure(**font.actual()) Toplevel.configure(self, **kwargs) def config(self, **kw): self.configurere(**kw) def cget(self, key): if key in ['text', 'image']: return self.label.cget(key) elif key == 'font': return self.font elif key == 'alpha': return self.attributes('-alpha') elif key in ['foreground', 'background']: return self.style.lookup('tooltip.TLabel', key) else: return Toplevel.cget(self, key)
'Instructions:\n\n1. Please click the [Build database] button to set up the database for the first time\n \ \n2.Input the sequence to be aligned into the text box or select the sequence file through the [Select file] button \ \n\n3.Select the database to be compared and the comparison method.\n\n4.Set the e-value Value, output format and number of threads.The default e-value =1e-5, and the default output format is 0 and the default of threads is 4\n \ \n5.(Optional) Any other command of BLAST like: -max_target_seqs 20 \n\n6.Click [Start] button for comparison, and the comparison results will be displayed here and saved in result.txt\n\n7.Alignment time depends on sequence size and computer performance \ \n') def mkdb_window_cmd(): make_db() top = Tk() top.title('BlastGUI') top.geometry('960x640') style = Style() fnfa = '' fndb = '' db_typeList = get_db_name() db_type = Combobox(top, text='Select', values=db_typeList, font=('', 13)) db_type.place(relx=0.129, rely=0.106, relwidth=0.11) blast_typeList = [ 'blastn', 'blastp', 'blastx', 'tblastn', 'tblastx', ] blast_typeVar = StringVar(value='blastn')
def main_menu(self): root = tk.Tk() root.title("Pathfinding") left = tk.Frame(root, bg="#b3b3b6", width=200, height=200) left.pack_propagate(False) tk.Label(left, text="1: Choose algorthm.", fg="black", bg="#b3b3b6", anchor="center", justify="center").pack() left.grid(column=0, row=0, pady=5, padx=10, sticky="n") sepl = Separator(root, orient="vertical") sepl.grid(column=1, row=0, sticky="ns") sty = Style(root) sty.configure("TSeparator", background="#eaeaef") center = tk.Frame(root, bg="#b3b3b6", width=200, height=200) center.pack_propagate(False) tk.Label(center, text="2: Choose level.", fg="black", bg="#b3b3b6").pack() center.grid(column=2, row=0, pady=5, padx=10, sticky="n") sepr = Separator(root, orient="vertical") sepr.grid(column=3, row=0, sticky="ns") bfs_button = tk.Button(left, text="Breadth First Search", bg="#D6AA5B", command=lambda *args: self.set_algo("bfs"), width=15) bfs_button.grid(row=0, column=0) d_button = tk.Button(left, text="Dijkstra", command=lambda *args: self.set_algo("d"), width=15) d_button.grid(row=1, column=0) a_button = tk.Button(left, text="A* Pathfinder", command=lambda *args: self.set_algo("a"), width=15) a_button.grid(row=2, column=0) level11_button = tk.Button(center, text="1-1", command=lambda *args: self.set_level("1-1")) level11_button.grid(row=0, column=0) level12_button = tk.Button(center, text="1-2", command=lambda *args: self.set_level("1-2")) level12_button.grid(row=1, column=0) level13_button = tk.Button(center, text="1-3", command=lambda *args: self.set_level("1-3")) level13_button.grid(row=2, column=0) level14_button = tk.Button(center, text="1-4", command=lambda *args: self.set_level("1-4")) level14_button.grid(row=3, column=0) level21_button = tk.Button(center, text="2-1", command=lambda *args: self.set_level("2-1")) level21_button.grid(row=0, column=1) level22_button = tk.Button(center, text="2-2", command=lambda *args: self.set_level("2-2")) level22_button.grid(row=1, column=1) level23_button = tk.Button(center, text="2-3", command=lambda *args: self.set_level("2-3")) level23_button.grid(row=2, column=1) level24_button = tk.Button(center, text="2-4", command=lambda *args: self.set_level("2-4")) level24_button.grid(row=3, column=1) execute_button = tk.Button(root, text="Run!", bg="green", command=lambda *args: self.run(self.algo, self.level)) execute_button.grid(row=0, column=4, padx=5) root.mainloop()
def initUI(self): self.parent.title("PTM Generator v0.3") self.style = Style() self.style.theme_use("default") self.fitter_filepath_str = "" self.currlistidx = -1 frame1 = Frame(self, relief=RAISED, borderwidth=1) frame1.pack(fill=BOTH, expand=True) self.listbox = Listbox(frame1, width=40) self.listbox.pack(side=LEFT, fill=Y, padx=5, pady=5, ipadx=5, ipady=5) self.imageview = Label(frame1) self.imageview.pack(side=LEFT, fill=BOTH, expand=True) frame11 = Frame(frame1) self.selectFilesButton = Button(frame11, text="Select Files", command=self.selectfiles) self.selectFilesButton.pack(fill=X, padx=5, pady=5) self.shootAgainButton = Button(frame11, text="Shoot Again", command=self.shootAgain) self.shootAgainButton.pack(fill=X, padx=5, pady=5) self.listbox.bind('<<ListboxSelect>>', self.onselect) frame11.pack(fill=X) frame2 = Frame(self, relief=RAISED, borderwidth=1) frame2.pack(fill=X) self.workdir_label = Label(frame2, text='Folder to Watch') self.workdir_label.pack(side=LEFT, fill=X, padx=5, pady=5) self.workdir_text = Entry(frame2, text='') self.workdir_text.pack(side=LEFT, fill=X, expand=True, padx=5, pady=5) self.workdirButton = Button(frame2, text="Select Folder", command=self.selectworkdir) self.workdirButton.pack(side=LEFT, fill=X, padx=5, pady=5) self.workdir_text.delete(0, END) dirname = shell.SHGetFolderPath(0, shellcon.CSIDL_MYPICTURES, None, 0) self.workdir_text.insert(0, dirname) p = Path(dirname) self.workingpath = p frame3 = Frame(self, relief=RAISED, borderwidth=1) self.fitter_label = Label(frame3, text='PTMFitter') self.fitter_label.pack(side=LEFT, fill=X, padx=5, pady=5) self.fitter_text = Entry(frame3, text='', textvariable=self.fitter_filepath_str) self.fitter_text.pack(side=LEFT, fill=X, expand=True, padx=5, pady=5) self.ptmButton = Button(frame3, text="PTMFitter", command=self.PTMfitter) self.ptmButton.pack(side=LEFT, fill=X, padx=5, pady=5) frame3.pack(fill=X) frame4 = Frame(self, relief=RAISED, borderwidth=1) self.COM_label = Label(frame4, text='Port') self.COM_label.pack(side=LEFT, fill=X, padx=5, pady=5) # Create a Tkinter variable self.varSerialPort = StringVar(root) # Dictionary with options choices = [] arduino_ports = [ p.device for p in serial.tools.list_ports.comports() if 'CH340' in p.description ] #for p in serial.tools.list_ports.comports(): # pass #print( p.description) for p in arduino_ports: choices.append(p) if len(arduino_ports) > 0: self.varSerialPort.set(choices[0]) # set the default option self.serial_exist = True else: choices.append("NONE") self.varSerialPort.set(choices[0]) # set the default option self.serial_exist = False self.popupMenu = OptionMenu(frame4, self.varSerialPort, *choices) self.popupMenu.pack(side=LEFT, fill=X, padx=5, pady=5) self.LEDControlButton = Button(frame4, text="LEDControl", command=self.LEDControl) self.LEDControlButton.pack(side=LEFT, fill=X, padx=5, pady=5) self.shootAllButton = Button(frame4, text="Shoot All", command=self.shootAll) self.shootAllButton.pack(side=LEFT, fill=X, padx=5, pady=5) self.generateButton = Button(frame4, text="Generate PTM File", command=self.generatePTM) self.generateButton.pack(side=LEFT, fill=X, padx=5, pady=5) #self.testButton = Button(frame4, text="Test",command=self.test) #self.testButton.pack( side=LEFT, fill=X,padx=5, pady=5) if (not self.serial_exist): self.shootAllButton["state"] = "disabled" self.LEDControlButton["state"] = "disabled" self.shootAgainButton["state"] = "disabled" # on change dropdown value frame4.pack(fill=X) self.pack(fill=BOTH, expand=True) options = {} options['initialdir'] = 'C:\\' options['mustexist'] = False options['parent'] = self.parent options['title'] = 'This is a title' #self.serial = serial.Serial() self.filelist = [] fitter = Path.cwd().joinpath("ptmfitter.exe") if fitter.exists(): self.fitter_filepath = fitter self.fitter_text.delete(0, END) self.fitter_text.insert(0, str(fitter)) print()
internal widget placed inside of labelframe. ''' from tkinter import Tk, PhotoImage from tkinter.ttk import Style, Label, Frame, LabelFrame from RunState import run_state root = Tk() fr = Frame(root) fr.grid(column=0, row=0, sticky='nsew') img2 = PhotoImage("frame-d", file='../images/piratz/frame-d.png') img1 = PhotoImage("frame", file='../images/piratz/frame.png') style = Style() # both theme_create and theme_settings worked style.theme_create( "yummy", parent="clam", settings={ #style.theme_settings('default', { # start of theme extract 'Labelframe.border': { "element create": ('image', "frame", ('disabled', "frame-d"), { 'border': 5, 'sticky': "nsew" }) } #'padding':5, # end of theme extract - don't forget to add comma at end when inserting })
# Fix for setting text colour for Tkinter 8.6.9 # From: https://core.tcl.tk/tk/info/509cafafae # # Returns the style map for 'option' with any styles starting with # ('!disabled', '!selected', ...) filtered out. # style.map() returns an empty list for missing options, so this # should be future-safe. return [ elm for elm in st1.map('Treeview', query_opt=option) if elm[:2] != ('!disabled', '!selected') ] root = Tk() st1 = Style() st1.theme_use('default') st1.map('Treeview', foreground=fixed_map('foreground'), background=fixed_map('background')) fact = font.Font(font="TkDefaultFont").metrics('linespace') st1.configure('font.Treeview', rowheight=fact, font=font.nametofont("TkDefaultFont")) # determine Heading font based on TkDefaultFont def_font = font.nametofont('TkDefaultFont') font_family = def_font.actual()['family'] font_size = def_font.actual()['size'] + 1
def init_objects(self): def _redo(text_object): var = text_object.edit_redo def _undo(text_object): var = text_object.edit_undo self.s = Style(self.root) self.s.theme_use('default') self.s.layout( "LabeledProgressbar", [( 'LabeledProgressbar.trough', { 'children': [ ('LabeledProgressbar.pbar', { 'side': 'left', 'sticky': 'ns' }), ( "LabeledProgressbar.label", # label inside the bar { "sticky": "" }) ], 'sticky': 'nswe' })]) self.s.configure("LabeledProgressbar", background='#06b025') self.font_title = ('consolas', 14) self.font_specs = ('consolas', 11) # variables used on proccess self.link = StringVar() self.save_path = StringVar() self.save_path.set(os.path.expanduser('~/Downloads')) self.title_var = StringVar() self.lb_title = Label(self.root, textvariable=self.title_var, font="consolas 14 bold") self.lb_title.grid(row=0, column=0, columnspan=3, padx=(10, 20)) self.d_descr_link = StringVar() self.descr_link = Label(self.root, textvariable=self.d_descr_link, font="consolas 11") self.descr_link.grid(row=1, column=0) self.d_lab_one = StringVar() self.lab_one = Label(self.root, textvariable=self.d_lab_one, font="Consolas 10") self.lab_one.grid(row=2, column=0) # frame for text where put the links self.my_frame = Frame(self.root) self.my_scroll = Scrollbar(self.my_frame, orient=VERTICAL) self.my_text = Text(self.my_frame, width=55, height=8, font=self.font_specs, yscrollcommand=self.my_scroll.set, undo=True) self.my_text.bind('<Control-z>', _undo(self.my_text)) self.my_text.bind('<Control-y>', _redo(self.my_text)) self.my_text.bind("<Button-3>", lambda event, text_element=self.my_text: self.popup( event=event, element=text_element)) self.my_scroll.config(command=self.my_text.yview) self.my_scroll.pack(side=RIGHT, fill=Y) self.my_frame.grid(row=3, column=0, padx=10) self.my_text.pack() # adding buttons self.button_frame = Frame(self.root) self.button_frame.grid(row=4, column=0, padx=10, pady=10) # clear button self.d_clear_button = StringVar() self.clear_button = Button(self.button_frame, textvariable=self.d_clear_button, command=self.clear_text) self.clear_button.grid(row=0, column=0, padx=10) self.d_start_down_btn = StringVar() self.start_down_btn = Button(self.button_frame, textvariable=self.d_start_down_btn, command=self.launch_down, fg="blue") self.start_down_btn.grid(row=0, column=1, padx=10) #stop button self.button_frame1 = Frame(self.root) self.button_frame1.grid(row=4, column=1, padx=10, pady=10) self.d_stop_button = StringVar() self.stop_button = Button(self.button_frame1, textvariable=self.d_stop_button, command=self.stop_download, fg="red") self.stop_button.grid(row=0, column=0, padx=10) self.stop_button.grid_remove() self.d_lb_save_in = StringVar() self.lb_save_in = Label(self.root, textvariable=self.d_lb_save_in, font="Consolas 11") self.lb_save_in.grid(row=1, column=1) # frame for path and button self.search_frame = Frame(self.root) self.search_frame.grid(row=2, column=1, sticky='w', padx=10) self.path_saver = Entry(self.search_frame, textvariable=self.save_path, width=65) self.path_saver.grid(row=0, column=0, sticky='w') self.d_brownse_btn = StringVar() self.browse_btn = Button(self.search_frame, textvariable=self.d_brownse_btn, command=self.browse_button) self.browse_btn.grid(row=0, column=1) # format file option # options frame self.option_format = IntVar() self.option_buttons = Frame(self.root) self.option_buttons.grid(row=5, column=0, sticky='w', padx=10) self.R1 = Radiobutton(self.option_buttons, text="Video", variable=self.option_format, value=1) self.R1.grid(row=0, column=1) self.R2 = Radiobutton(self.option_buttons, text="Audio", variable=self.option_format, value=2) self.R2.grid(row=0, column=2) # set value on audio self.option_format.set(2) # adding status frame self.status_frame = Frame(self.root, bd=1, relief=SUNKEN) self.status_frame.grid(row=6, column=0, columnspan=3, sticky=W + E, pady=(20, 0)) Label(self.status_frame, text="EA Yt Downloader", font="consolas 11 bold").grid(row=0, column=0, padx=10) self.status_text = StringVar() self.status_text_label = Label(self.status_frame, textvariable=self.status_text, font="consolas 11").grid(row=0, column=1, sticky='e') # adding status bar self.my_progress = ttk.Progressbar(self.status_frame, orient=HORIZONTAL, length=250, mode='determinate', style="LabeledProgressbar") self.my_progress.grid(row=0, column=2, sticky='e') # hiding progressbar self.my_progress.grid_remove() # debug text self.deb_frame = Frame(self.root) self.scr_deb = Scrollbar(self.deb_frame, orient=VERTICAL) self.my_text1 = Text(self.deb_frame, state='disabled', width=55, height=8, yscrollcommand=self.scr_deb.set, bg="white") self.scr_deb.config(command=self.my_text1.yview) self.scr_deb.pack(side=RIGHT, fill=Y) self.deb_frame.grid(row=3, column=1, columnspan=2, padx=10) self.my_text1.pack(side=LEFT, fill=BOTH, expand=YES) self.menubar = Menubar(self) self.statusbar = Statusbar(self) self.set_values()
def initUI(self): self.master.title("Calculator") Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10') self.columnconfigure(0, pad=3) self.columnconfigure(1, pad=3) self.columnconfigure(2, pad=3) self.columnconfigure(3, pad=3) self.rowconfigure(0, pad=3) self.rowconfigure(1, pad=3) self.rowconfigure(2, pad=3) self.rowconfigure(3, pad=3) self.rowconfigure(4, pad=3) entry = Entry(self) entry.grid(row=0, columnspan=4, sticky=W + E) cls = Button(self, text="Cls") cls.grid(row=1, column=0) bck = Button(self, text="Back") bck.grid(row=1, column=1) lbl = Button(self) lbl.grid(row=1, column=2) clo = Button(self, text="Close") clo.grid(row=1, column=3) sev = Button(self, text="7") sev.grid(row=2, column=0) eig = Button(self, text="8") eig.grid(row=2, column=1) nin = Button(self, text="9") nin.grid(row=2, column=2) div = Button(self, text="/") div.grid(row=2, column=3) fou = Button(self, text="4") fou.grid(row=3, column=0) fiv = Button(self, text="5") fiv.grid(row=3, column=1) six = Button(self, text="6") six.grid(row=3, column=2) mul = Button(self, text="*") mul.grid(row=3, column=3) one = Button(self, text="1") one.grid(row=4, column=0) two = Button(self, text="2") two.grid(row=4, column=1) thr = Button(self, text="3") thr.grid(row=4, column=2) mns = Button(self, text="-") mns.grid(row=4, column=3) zer = Button(self, text="0") zer.grid(row=5, column=0) dot = Button(self, text=".") dot.grid(row=5, column=1) equ = Button(self, text="=") equ.grid(row=5, column=2) pls = Button(self, text="+") pls.grid(row=5, column=3) self.pack()
def init_window(self): # Create main window self.master = Tk() self.master.title('Regularity Rally Timer') # Resize window. self.master.state('zoomed') self.w = self.master.winfo_screenwidth() self.h = self.master.winfo_screenheight() # Init font variable. self.font = tk_font.Font(family="Helvetica", size=36, weight="bold") # Create menu menu_bar = Menu(self.master) file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label='New', command=self.new_cb) file_menu.add_command(label='Exit', command=self.master.quit) menu_bar.add_cascade(label="File", menu=file_menu) extras_menu = Menu(menu_bar, tearoff=0) extras_menu.add_command(label='Set new start time', command=None) extras_menu.add_command(label='Manage Config Files', command=None) extras_menu.add_command(label='Options', command=None) menu_bar.add_cascade(label="Extras", menu=extras_menu) self.master.config(menu=menu_bar) # Init Widgets. # TODO: Resize and anchor Labels. # Information row. row_count = 0 self.l_state = Label(self.master, text='Select Configuration', font=self.font) self.l_state.grid(row=row_count, column=0) self.l_mark = Label(self.master, text='', font=self.font) self.l_mark.grid(row=row_count, column=1) self.t_laps = Text(self.master, width=20, font=("Consolas", 32)) self.t_laps.grid(row=row_count, column=2, rowspan=3) self.master.grid_rowconfigure(row_count, weight=1) # Labels row. row_count += 1 self.l_cur_lap = Label(self.master, text='Current Lap', anchor='w', font=self.font) self.l_cur_lap.grid(row=row_count, column=0) self.l_set_lap = Label(self.master, text='Current Set Lap', anchor='w', font=self.font) self.l_set_lap.grid(row=row_count, column=1) self.master.grid_rowconfigure(row_count, weight=1) # Time display row. row_count += 1 self.l_cur_lap_disp = Label(self.master, text='__:__:__._', anchor='w', font=self.font) self.l_cur_lap_disp.grid(row=row_count, column=0) self.l_set_lap_disp = Label(self.master, text='__:__:__._', anchor='w', font=self.font) self.l_set_lap_disp.grid(row=row_count, column=1) self.master.grid_rowconfigure(row_count, weight=1) # Progressbar and countdown row. row_count += 1 # Create the progressbar style to be labeled. self.style_progress = Style(self.master) self.style_progress.layout("LabeledProgressbar", [('LabeledProgressbar.trough', {'children': [('LabeledProgressbar.pbar', {'side': 'left', 'sticky': 'ns'}), ("LabeledProgressbar.label", # label inside the bar {"sticky": ""})], 'sticky': 'nswe'})]) self.bar_progress = Progressbar(self.master, orient='horizontal', length=1000, mode='determinate', style="LabeledProgressbar") self.bar_progress.grid(row=row_count, column=0, columnspan=3, ipady=25) # Column configuration. self.master.grid_columnconfigure(0, weight=1) self.master.grid_columnconfigure(1, weight=1) # Define Binds. self.master.bind('1', self.one_cb) self.master.bind('2', self.two_cb) # Start master mainloop. self.master.after(10, self.gui_update) self.master.mainloop()
fr = Frame(root) fr.grid(column=0, row=0, sticky='nsew') # image aliases changed img1 = PhotoImage("combo-n", file='../images/lime/combo-n.png') img3 = PhotoImage("combo-d", file='../images/lime/combo-d.png') img7 = PhotoImage("arrspd-h", file='../images/lime/arrspd-h.png') img8 = PhotoImage("arrspd-d", file='../images/lime/arrspd-d.png') img9 = PhotoImage("arrspd-n", file='../images/lime/arrspd-n.png') img10 = PhotoImage("arrspd-p", file='../images/lime/arrspd-p.png') img11 = PhotoImage("arrspu-h", file='../images/lime/arrspu-h.png') img12 = PhotoImage("arrspu-d", file='../images/lime/arrspu-d.png') img13 = PhotoImage("arrspu-n", file='../images/lime/arrspu-n.png') img14 = PhotoImage("arrspu-p", file='../images/lime/arrspu-p.png') style = Style() # both theme_create and theme_settings worked style.theme_create( "yummy", parent="clam", settings={ #style.theme_settings('alt', { # start of theme extract "Spinbox.field": { "element create": ( "image", 'combo-n', ('readonly', 'disabled', 'combo-d'), { 'sticky': 'nsew', 'border': [4],
class Window(Frame): # Define settings upon initialization. Here you can specify def __init__(self, master, im): # parameters that you want to send through the Frame class. Frame.__init__(self, master) # reference to the master widget, which is the tk window self.master = master # with that, we want to then run init_window, which doesn't yet exist self.init_window(im) # Creation of init_window def init_window(self, im): # changing the title of our master widget self.master.title("Best Flight Management System") self.style = Style() self.style.theme_use("default") # allowing the widget to take the full space of the root window self.pack(fill=BOTH, expand=True) self.showBtn() # creating a menu instance===================================== menu = Menu(self.master) self.master.config(menu=menu) # create the file object) file = Menu(menu) # adds a command to the menu option, calling it exit, and the # command it runs on event is client_exit file.add_command(label="Exit", command=self.client_exit) # added "file" to our menu menu.add_cascade(label="File", menu=file) # create the file object) edit = Menu(menu) # adds a command to the menu option, calling it exit, and the # command it runs on event is client_exit # edit.add_command(label="Show Text", command=self.showText) # added "file" to our menu menu.add_cascade(label="Edit", menu=edit) def showImg(self, im): info = '' self.image = ImageTk.PhotoImage(im) info += "All Routes Available" image_label = Label( self, image=self.image, bd=0) # <--- will not work if 'image = ImageTk.PhotoImage(im)' image_label.grid(row=1, column=0, columnspan=2, rowspan=len(df.index) + 2, padx=1, sticky=E + W + N) self.showText(info) def updateImg(self, im, i): img = main(i) print("updating Map") info = '' df = pd.read_csv('cities.csv') if i is len(df.index) or i is 9: self.image = ImageTk.PhotoImage(main(0)) info += "Starting city >> " + df.loc[0, "City"] else: self.image = ImageTk.PhotoImage(img) if i is not 0: info += "Route from " + df.loc[0, "City"] + " to " + df.loc[ i, "City"] else: info += "Starting city >> " + df.loc[0, "City"] image_label = Label( self, image=self.image, bd=0) # <--- will not work if 'image = ImageTk.PhotoImage(im)' image_label.grid(row=1, column=0, columnspan=2, rowspan=len(df.index) + 2, padx=1, sticky=E + W + N) self.showText(info) self.showAnalysis(i) def showAnalysis(self, i): df = pd.read_csv('cities.csv') cities = [] for index, row in df.iterrows(): if index is not 0: cities.append(row['City']) destination = cities[i - 1] traversedCity = [] fname = destination + "_final.csv" df2 = pd.read_csv(fname) if df2.iloc[0, 5] is None: for col in range[1:4]: cityName = df2.iloc[0, col] traversedCity.append(cityName) else: for col in range(1, 3): cityName = df2.iloc[0, col] traversedCity.append(cityName) traversedCity.append(None) def showText(self, info='Flight System'): ttk.Style().configure("TLabel", foreground='black', background='pink', padding=(2, 6, 2, 6), font='serif 10', borderwidth=5) entry = ttk.Label(self, text=info, style="TLabel") entry.configure(anchor="center") entry.grid(row=0, column=0, columnspan=4, rowspan=1, pady=3, sticky=E + W + S + N) def showBtn(self): # creating buttons fot cities Style().configure("TButton", padding=(2, 8, 2, 8), font='serif 10') # create column self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=3) df = pd.read_csv('cities.csv') # create row for i in range(len(df.index) + 3): self.rowconfigure(i, pad=3) self.showImg(im) print("---") ttk.Style().configure("TButton", foreground='black', background='yellow') fileToShow = '' for index, row in df.iterrows(): if index is 0: abtn = ttk.Button( self, text=row['City'], style="TButton" ) #, command=lambda i=index: self.updateImg(im, i)) else: abtn = ttk.Button( self, text=row['City'], style="TButton", command=lambda i=index: self.updateImg(im, i)) fileToShow = 'newsSingapore.txt' abtn.grid(row=index + 1, column=3, sticky=W + E) btn = ttk.Button( self, text="Analysis", style="TButton") #, command=lambda: self.showAnalysis(fileToShow)) btn.grid(row=len(df.index) + 1, column=3, sticky=W + E) def client_exit(self): exit()
''' integer entry allowing additional characters ''' from tkinter import Tk from tkinter.ttk import Entry, Style root = Tk() s = Style() s.theme_use('default') def isOkay(act, inp, text): # print(inp) #if act == '1': ''' if text in '0123456789.-+': try: float(inp) #if 1<float(inp)<63: #return True #else: #return False except ValueError: return False else: return False ''' if inp == "" or inp == "-" or inp == "." or inp == "-.": # and len(inp) == 1 return True if isinstance(inp, float): float(inp)
def __init__(self, master, a_copier, a_supp, a_supp_avant_cp, original, sauvegarde, show_size): Toplevel.__init__(self, master) self.geometry("%ix%i" % (self.winfo_screenwidth(), self.winfo_screenheight())) self.rowconfigure(1, weight=1) self.columnconfigure(0, weight=1) self.columnconfigure(1, weight=1) self.title(_("Confirmation")) self.a_copier = a_copier self.a_supp = a_supp self.a_supp_avant_cp = a_supp_avant_cp h = max(len(a_supp), len(a_copier)) style = Style(self) style.configure("text.TFrame", background="white", relief="sunken") Label(self, text=_("Synchronization from %(original)s to %(backup)s") % { "original": original, "backup": sauvegarde }).grid(row=0, columnspan=2, padx=10, pady=10) paned = PanedWindow(self, orient='horizontal') paned.grid(row=1, columnspan=2, sticky="eswn", padx=(10, 4), pady=4) paned.columnconfigure(0, weight=1) paned.columnconfigure(1, weight=1) paned.rowconfigure(1, weight=1) # --- copy frame_copie = Frame(paned) frame_copie.columnconfigure(0, weight=1) frame_copie.rowconfigure(1, weight=1) paned.add(frame_copie, weight=1) Label(frame_copie, text=_("To copy:")).grid(row=0, columnspan=2, padx=(10, 4), pady=4) f_copie = Frame(frame_copie, style="text.TFrame", borderwidth=1) f_copie.columnconfigure(0, weight=1) f_copie.rowconfigure(0, weight=1) f_copie.grid(row=1, column=0, sticky="ewsn") txt_copie = Text(f_copie, height=h, wrap="none", highlightthickness=0, relief="flat") txt_copie.grid(row=0, column=0, sticky="eswn") scrollx_copie = Scrollbar(frame_copie, orient="horizontal", command=txt_copie.xview) scrolly_copie = Scrollbar(frame_copie, orient="vertical", command=txt_copie.yview) scrollx_copie.grid(row=2, column=0, sticky="ew") scrolly_copie.grid(row=1, column=1, sticky="ns") txt_copie.configure(yscrollcommand=scrolly_copie.set, xscrollcommand=scrollx_copie.set) txt_copie.insert("1.0", "\n".join(a_copier)) txt_copie.configure(state="disabled") self._size_copy = Label(frame_copie) self._size_copy.grid(row=3, column=0) # --- deletion frame_supp = Frame(paned) frame_supp.columnconfigure(0, weight=1) frame_supp.rowconfigure(1, weight=1) paned.add(frame_supp, weight=1) Label(frame_supp, text=_("To remove:")).grid(row=0, columnspan=2, padx=(4, 10), pady=4) f_supp = Frame(frame_supp, style="text.TFrame", borderwidth=1) f_supp.columnconfigure(0, weight=1) f_supp.rowconfigure(0, weight=1) f_supp.grid(row=1, column=0, sticky="ewsn") txt_supp = Text(f_supp, height=h, wrap="none", highlightthickness=0, relief="flat") txt_supp.grid(row=0, column=0, sticky="eswn") scrollx_supp = Scrollbar(frame_supp, orient="horizontal", command=txt_supp.xview) scrolly_supp = Scrollbar(frame_supp, orient="vertical", command=txt_supp.yview) scrollx_supp.grid(row=2, column=0, sticky="ew") scrolly_supp.grid(row=1, column=1, sticky="ns") txt_supp.configure(yscrollcommand=scrolly_supp.set, xscrollcommand=scrollx_supp.set) txt_supp.insert("1.0", "\n".join(a_supp)) txt_supp.configure(state="disabled") self._size_supp = Label(frame_supp) self._size_supp.grid(row=3, column=0) Button(self, command=self.ok, text="Ok").grid(row=3, column=0, sticky="e", padx=(10, 4), pady=(4, 10)) Button(self, text=_("Cancel"), command=self.destroy).grid(row=3, column=1, sticky="w", padx=(4, 10), pady=(4, 10)) self.wait_visibility() self.grab_set() self.transient(self.master) if show_size: self.compute_size()
def set_theme(self, theme): self.theme = theme Style().theme_use(theme)
class RegularityRallyGUI(RegularityRally): STATES = {-1: 'Select configuration', 0: 'Ready', 1: 'Fast Lap', 2: 'Untimed Lap', 3: 'Set Lap', 4: 'Confirmation Lap'} def __init__(self): super().__init__() # Data attribute initialization. self.root_dir = pathlib.Path(__file__).parent.parent.absolute() self.config_dir = os.path.join(self.root_dir, 'config') # Overwrite initial state. Config read is mandatory here. self.state = -1 # GUI attribute initialization. self.master = None self.font = None self.w = None self.h = None self.l_state = None self.l_mark = None self.l_cur_lap = None self.l_cur_lap_disp = None self.l_set_lap = None self.l_set_lap_disp = None self.t_laps = None self.bar_progress = None self.style_progress = None # Get start time. self.time_stamps = [] # Window initialization. self.init_window() def init_window(self): # Create main window self.master = Tk() self.master.title('Regularity Rally Timer') # Resize window. self.master.state('zoomed') self.w = self.master.winfo_screenwidth() self.h = self.master.winfo_screenheight() # Init font variable. self.font = tk_font.Font(family="Helvetica", size=36, weight="bold") # Create menu menu_bar = Menu(self.master) file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label='New', command=self.new_cb) file_menu.add_command(label='Exit', command=self.master.quit) menu_bar.add_cascade(label="File", menu=file_menu) extras_menu = Menu(menu_bar, tearoff=0) extras_menu.add_command(label='Set new start time', command=None) extras_menu.add_command(label='Manage Config Files', command=None) extras_menu.add_command(label='Options', command=None) menu_bar.add_cascade(label="Extras", menu=extras_menu) self.master.config(menu=menu_bar) # Init Widgets. # TODO: Resize and anchor Labels. # Information row. row_count = 0 self.l_state = Label(self.master, text='Select Configuration', font=self.font) self.l_state.grid(row=row_count, column=0) self.l_mark = Label(self.master, text='', font=self.font) self.l_mark.grid(row=row_count, column=1) self.t_laps = Text(self.master, width=20, font=("Consolas", 32)) self.t_laps.grid(row=row_count, column=2, rowspan=3) self.master.grid_rowconfigure(row_count, weight=1) # Labels row. row_count += 1 self.l_cur_lap = Label(self.master, text='Current Lap', anchor='w', font=self.font) self.l_cur_lap.grid(row=row_count, column=0) self.l_set_lap = Label(self.master, text='Current Set Lap', anchor='w', font=self.font) self.l_set_lap.grid(row=row_count, column=1) self.master.grid_rowconfigure(row_count, weight=1) # Time display row. row_count += 1 self.l_cur_lap_disp = Label(self.master, text='__:__:__._', anchor='w', font=self.font) self.l_cur_lap_disp.grid(row=row_count, column=0) self.l_set_lap_disp = Label(self.master, text='__:__:__._', anchor='w', font=self.font) self.l_set_lap_disp.grid(row=row_count, column=1) self.master.grid_rowconfigure(row_count, weight=1) # Progressbar and countdown row. row_count += 1 # Create the progressbar style to be labeled. self.style_progress = Style(self.master) self.style_progress.layout("LabeledProgressbar", [('LabeledProgressbar.trough', {'children': [('LabeledProgressbar.pbar', {'side': 'left', 'sticky': 'ns'}), ("LabeledProgressbar.label", # label inside the bar {"sticky": ""})], 'sticky': 'nswe'})]) self.bar_progress = Progressbar(self.master, orient='horizontal', length=1000, mode='determinate', style="LabeledProgressbar") self.bar_progress.grid(row=row_count, column=0, columnspan=3, ipady=25) # Column configuration. self.master.grid_columnconfigure(0, weight=1) self.master.grid_columnconfigure(1, weight=1) # Define Binds. self.master.bind('1', self.one_cb) self.master.bind('2', self.two_cb) # Start master mainloop. self.master.after(10, self.gui_update) self.master.mainloop() def gui_update(self): # Calculate time delta of current lap. if self.state > 0: # Call regularity update. self.reg_update() # Update current lap time display. self.l_cur_lap_disp['text'] = '{:02}:{:02}:{:02}.{}'.format(self.curlap_decoded[0], self.curlap_decoded[1], self.curlap_decoded[2], floor(self.curlap_decoded[3]/100)) # Update countdown display, if confirmation lap. if self.state == 4: # Update progress bar. self.bar_progress['value'] = self.curlap_countdown_seconds self.style_progress.configure("LabeledProgressbar", text='{:.2f}'.format(self.curlap_countdown_seconds)) self.bar_progress.update() # Update mark label. if self.mark_count < len(self.mark_labels): self.l_mark['text'] = self.mark_labels[self.mark_count] else: self.bar_progress['value'] = 0 self.style_progress.configure("LabeledProgressbar", text='') # Schedule next call. self.master.after(10, self.gui_update) # Method called, when new race should be created. def new_cb(self): # Select and open a configuration. conf_file = open(filedialog.askopenfilename(initialdir=self.config_dir, title='Select file', filetypes=(('Configuration', "*.cfg"), ("all files", "*.*")))) # Read configuration. self.read_config(conf_file.name) # Write state. self.state = 0 self.l_state['text'] = 'Ready' # Method for new lap. # Only update displays here. Set data in regularityRally.reg_new_lap() def one_cb(self, _): if self.state == -1: self.new_cb() else: # Store last state. last_state = self.state # Perform new lap method. self.reg_new_lap() # Change label. self.l_state['text'] = self.STATES[self.state] if self.state in [3, 4]: marks = list(self.config['marks'].keys()) self.l_mark['text'] = marks[0] # Update lap times text field. self.t_laps.delete(1.0, 'end') for lt_id, lt in enumerate(self.lap_times_decoded): # Get text char from config. If id out of config, set 'F. if lt_id < len(self.config['states']): state_char = self.STATES[self.config['states'][lt_id]][0] else: state_char = 'F' # Set char for each lap. self.t_laps.insert('end', '{:>2}: {:02}:{:02}:{:02}.{:03} {}\n'.format(lt_id + 1, lt[0], lt[1], lt[2], lt[3], state_char)) # Update GUI items related to set lap. if self.cur_set_time is not None: # Update shown set time. self.l_set_lap_disp['text'] = '{:02}:{:02}:{:02}.{:01}'.format(self.cur_set_time_decoded[0], self.cur_set_time_decoded[1], self.cur_set_time_decoded[2], floor(self.cur_set_time_decoded[3]/100)) # Update progressbar maximum to set lap time to show countdown. self.bar_progress['maximum'] = self.cur_set_time def two_cb(self, _): # Execute superclass method. self.mark_reached() # Write next mark to label. marks = list(self.config['marks'].keys()) if len(marks) > self.mark_count: self.l_mark['text'] = marks[self.mark_count] else: self.l_mark['text'] = 'countdown'
class MainFrame(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def quit(self): self.parent.destroy() def input_askdirectory(self): select_dir = tkinter.filedialog.askdirectory() self.root_directory.set(select_dir) return select_dir def output_askdirectory(self): select_dir = tkinter.filedialog.askdirectory() self.output_directory.set(select_dir) return select_dir def get_type_value(self): return self.radio_type def run_process(self): if self.radio_type == 0: print('wcs_validator_type') else: print('emammal_validator_type') # print 'self.radio_type', self.radio_type, type(self.radio_type) # print 'self.root_directory', self.root_directory, type(self.root_directory) # print 'self.output_directory',self.output_directory,type(self.output_directory) create_manifest = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'create_manifest.py') proc = subprocess.Popen([ "python", create_manifest, self.root_directory.get(), self.output_directory.get(), str(self.radio_type) ]) proc.wait() with open( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'error.log')) as f: content = f.readlines() for i in content: self.results.insert(END, i) def update_type_value(self): if self.radio_type == 0: self.radio_type = 1 self.radio_type = 1 else: self.radio_type = 0 def initUI(self): self.parent.title("Emammal Legacy Data Converter") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=True) self.root_directory = StringVar(self.parent) self.output_directory = StringVar(self.parent) self.results = StringVar() self.radio_type = IntVar() self.radio_type = 0 frame1 = Frame(self) frame1.pack(fill=X) lbl1 = Label(frame1, text="Input Directory", width=15) lbl1.pack(side=LEFT, padx=5, pady=5) select_dir = Button(frame1, text='Choose Directory', command=self.input_askdirectory) select_dir.pack(side=LEFT, padx=5, pady=5) entry1 = Entry(frame1, textvariable=self.root_directory) entry1.pack(fill=X, padx=5, expand=True) frame2 = Frame(self) frame2.pack(fill=X) lbl2 = Label(frame2, text="Output Directory", width=15) lbl2.pack(side=LEFT, padx=5, pady=5) output_dir = Button(frame2, text='Choose Directory', command=self.output_askdirectory) output_dir.pack(side=LEFT, padx=5, pady=5) entry2 = Entry(frame2, textvariable=self.output_directory) entry2.pack(fill=X, padx=5, expand=True) frameRadio = Frame(self) frameRadio.pack(fill=X) lbl2 = Label(frameRadio, text="Manifest Type", width=15) lbl2.pack(side=LEFT, padx=5, pady=5) radio_emammal = Radiobutton(frameRadio, text="eMammal xmlVerifier-1.0.2", variable=self.radio_type, value=1, command=self.update_type_value) radio_emammal.pack(side=LEFT, padx=5, pady=5) radio_classic = Radiobutton(frameRadio, text="WSC eMammal Classic", variable=self.radio_type, value=0, command=self.update_type_value) radio_classic.pack(side=LEFT, padx=5, pady=5) radio_classic.select() frame3 = Frame(self) frame3.pack(fill=BOTH, expand=True) lbl3 = Label(frame3, text="Results", width=15) lbl3.pack(side=LEFT, anchor=N, padx=5, pady=5) self.results = Text(frame3) self.results.pack(fill=BOTH, pady=5, padx=5, expand=True) closeButton = Button(self, text="Close", command=self.quit) closeButton.pack(side=RIGHT, padx=5, pady=5) okButton = Button(self, text="Run", command=self.run_process) okButton.pack(side=RIGHT)
pls = Button(self, text="+") pls.grid(row=5, column=3) self.pack() def main(): root = Tk() _ = Example() root.mainloop() if __name__ == '__main__': main() """The grid manager is used to organize buttons in the frame container. Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10') We configure the Button widget to have a specific font and to have some internal padding. self.columnconfigure(0, pad=3) ... self.rowconfigure(0, pad=3) We use the columnconfigure() and the rowconfigure() methods to define some space in grid columns and rows. This way we achieve that the buttons are separated by some space. entry = Entry(self) entry.grid(row=0, columnspan=4, sticky=W+E) The Entry widget is where the digits are displayed. The widget is placed in the first row and it spans all four columns. Widgets may not occupy all the space allotted by cells in the grid. The sticky parameter expands
def initUI(self): self.parent.title("Emammal Legacy Data Converter") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=True) self.root_directory = StringVar(self.parent) self.output_directory = StringVar(self.parent) self.results = StringVar() self.radio_type = IntVar() self.radio_type = 0 frame1 = Frame(self) frame1.pack(fill=X) lbl1 = Label(frame1, text="Input Directory", width=15) lbl1.pack(side=LEFT, padx=5, pady=5) select_dir = Button(frame1, text='Choose Directory', command=self.input_askdirectory) select_dir.pack(side=LEFT, padx=5, pady=5) entry1 = Entry(frame1, textvariable=self.root_directory) entry1.pack(fill=X, padx=5, expand=True) frame2 = Frame(self) frame2.pack(fill=X) lbl2 = Label(frame2, text="Output Directory", width=15) lbl2.pack(side=LEFT, padx=5, pady=5) output_dir = Button(frame2, text='Choose Directory', command=self.output_askdirectory) output_dir.pack(side=LEFT, padx=5, pady=5) entry2 = Entry(frame2, textvariable=self.output_directory) entry2.pack(fill=X, padx=5, expand=True) frameRadio = Frame(self) frameRadio.pack(fill=X) lbl2 = Label(frameRadio, text="Manifest Type", width=15) lbl2.pack(side=LEFT, padx=5, pady=5) radio_emammal = Radiobutton(frameRadio, text="eMammal xmlVerifier-1.0.2", variable=self.radio_type, value=1, command=self.update_type_value) radio_emammal.pack(side=LEFT, padx=5, pady=5) radio_classic = Radiobutton(frameRadio, text="WSC eMammal Classic", variable=self.radio_type, value=0, command=self.update_type_value) radio_classic.pack(side=LEFT, padx=5, pady=5) radio_classic.select() frame3 = Frame(self) frame3.pack(fill=BOTH, expand=True) lbl3 = Label(frame3, text="Results", width=15) lbl3.pack(side=LEFT, anchor=N, padx=5, pady=5) self.results = Text(frame3) self.results.pack(fill=BOTH, pady=5, padx=5, expand=True) closeButton = Button(self, text="Close", command=self.quit) closeButton.pack(side=RIGHT, padx=5, pady=5) okButton = Button(self, text="Run", command=self.run_process) okButton.pack(side=RIGHT)
class ytDownloader: """ ytDownloader e' un youtube video downloader """ def __init__(self, _root): # start objects self.root = _root self.selected_language = 'ENG' self.lang = Translator(language) self.root.geometry("960x346") self.root.title("Yt Video Downloader") # self.root.title(self.lang.title) self.root.resizable(False, False) self.init_objects() self.v_counter = 0 self.v_down = 0 self.context_menu = Menu(self.root, tearoff=0) self.context_menu.add_command(label="Cut") self.context_menu.add_command(label="Copy") self.context_menu.add_command(label="Paste") self.downloading = False self.global_downloading = False self.ThreadLauncher = None self.root.protocol('WM_DELETE_WINDOW', self.prevent_close) def change_language(self, _language): self.lang.set_language(_language) self.set_values() # changing language menubar self.menubar.set_language() self.root.update_idletasks() def prevent_close(self): ''' Check if Thread is running then delete it :return: None ''' _title = '' _message = '' if self.global_downloading: _title = self.lang.running _message = f"{self.lang.running_msg_1}"\ f"\n {self.lang.close_app}" question = messagebox.askyesno(title=_title, message=_message) if question: # destroy thread runnning self.stop_download() else: return None self.root.destroy() # messagebox.showinfo('Running', 'The downloader app is already running') # root.destroy() def reset_values(self): self.v_counter = 0 self.v_down = 0 def popup(self, event, element): self.context_menu.post(event.x_root, event.y_root) self.context_menu.entryconfigure( "Cut", command=lambda: element.event_generate("<<Cut>>")) self.context_menu.entryconfigure( "Copy", command=lambda: element.event_generate("<<Copy>>")) self.context_menu.entryconfigure( "Paste", command=lambda: element.event_generate("<<Paste>>")) def init_objects(self): def _redo(text_object): var = text_object.edit_redo def _undo(text_object): var = text_object.edit_undo self.s = Style(self.root) self.s.theme_use('default') self.s.layout( "LabeledProgressbar", [( 'LabeledProgressbar.trough', { 'children': [ ('LabeledProgressbar.pbar', { 'side': 'left', 'sticky': 'ns' }), ( "LabeledProgressbar.label", # label inside the bar { "sticky": "" }) ], 'sticky': 'nswe' })]) self.s.configure("LabeledProgressbar", background='#06b025') self.font_title = ('consolas', 14) self.font_specs = ('consolas', 11) # variables used on proccess self.link = StringVar() self.save_path = StringVar() self.save_path.set(os.path.expanduser('~/Downloads')) self.title_var = StringVar() self.lb_title = Label(self.root, textvariable=self.title_var, font="consolas 14 bold") self.lb_title.grid(row=0, column=0, columnspan=3, padx=(10, 20)) self.d_descr_link = StringVar() self.descr_link = Label(self.root, textvariable=self.d_descr_link, font="consolas 11") self.descr_link.grid(row=1, column=0) self.d_lab_one = StringVar() self.lab_one = Label(self.root, textvariable=self.d_lab_one, font="Consolas 10") self.lab_one.grid(row=2, column=0) # frame for text where put the links self.my_frame = Frame(self.root) self.my_scroll = Scrollbar(self.my_frame, orient=VERTICAL) self.my_text = Text(self.my_frame, width=55, height=8, font=self.font_specs, yscrollcommand=self.my_scroll.set, undo=True) self.my_text.bind('<Control-z>', _undo(self.my_text)) self.my_text.bind('<Control-y>', _redo(self.my_text)) self.my_text.bind("<Button-3>", lambda event, text_element=self.my_text: self.popup( event=event, element=text_element)) self.my_scroll.config(command=self.my_text.yview) self.my_scroll.pack(side=RIGHT, fill=Y) self.my_frame.grid(row=3, column=0, padx=10) self.my_text.pack() # adding buttons self.button_frame = Frame(self.root) self.button_frame.grid(row=4, column=0, padx=10, pady=10) # clear button self.d_clear_button = StringVar() self.clear_button = Button(self.button_frame, textvariable=self.d_clear_button, command=self.clear_text) self.clear_button.grid(row=0, column=0, padx=10) self.d_start_down_btn = StringVar() self.start_down_btn = Button(self.button_frame, textvariable=self.d_start_down_btn, command=self.launch_down, fg="blue") self.start_down_btn.grid(row=0, column=1, padx=10) #stop button self.button_frame1 = Frame(self.root) self.button_frame1.grid(row=4, column=1, padx=10, pady=10) self.d_stop_button = StringVar() self.stop_button = Button(self.button_frame1, textvariable=self.d_stop_button, command=self.stop_download, fg="red") self.stop_button.grid(row=0, column=0, padx=10) self.stop_button.grid_remove() self.d_lb_save_in = StringVar() self.lb_save_in = Label(self.root, textvariable=self.d_lb_save_in, font="Consolas 11") self.lb_save_in.grid(row=1, column=1) # frame for path and button self.search_frame = Frame(self.root) self.search_frame.grid(row=2, column=1, sticky='w', padx=10) self.path_saver = Entry(self.search_frame, textvariable=self.save_path, width=65) self.path_saver.grid(row=0, column=0, sticky='w') self.d_brownse_btn = StringVar() self.browse_btn = Button(self.search_frame, textvariable=self.d_brownse_btn, command=self.browse_button) self.browse_btn.grid(row=0, column=1) # format file option # options frame self.option_format = IntVar() self.option_buttons = Frame(self.root) self.option_buttons.grid(row=5, column=0, sticky='w', padx=10) self.R1 = Radiobutton(self.option_buttons, text="Video", variable=self.option_format, value=1) self.R1.grid(row=0, column=1) self.R2 = Radiobutton(self.option_buttons, text="Audio", variable=self.option_format, value=2) self.R2.grid(row=0, column=2) # set value on audio self.option_format.set(2) # adding status frame self.status_frame = Frame(self.root, bd=1, relief=SUNKEN) self.status_frame.grid(row=6, column=0, columnspan=3, sticky=W + E, pady=(20, 0)) Label(self.status_frame, text="EA Yt Downloader", font="consolas 11 bold").grid(row=0, column=0, padx=10) self.status_text = StringVar() self.status_text_label = Label(self.status_frame, textvariable=self.status_text, font="consolas 11").grid(row=0, column=1, sticky='e') # adding status bar self.my_progress = ttk.Progressbar(self.status_frame, orient=HORIZONTAL, length=250, mode='determinate', style="LabeledProgressbar") self.my_progress.grid(row=0, column=2, sticky='e') # hiding progressbar self.my_progress.grid_remove() # debug text self.deb_frame = Frame(self.root) self.scr_deb = Scrollbar(self.deb_frame, orient=VERTICAL) self.my_text1 = Text(self.deb_frame, state='disabled', width=55, height=8, yscrollcommand=self.scr_deb.set, bg="white") self.scr_deb.config(command=self.my_text1.yview) self.scr_deb.pack(side=RIGHT, fill=Y) self.deb_frame.grid(row=3, column=1, columnspan=2, padx=10) self.my_text1.pack(side=LEFT, fill=BOTH, expand=YES) self.menubar = Menubar(self) self.statusbar = Statusbar(self) self.set_values() def set_values(self): ''' setting values of label, messages and buttons :return: None ''' try: self.title_var.set(self.lang.title) self.d_descr_link.set(self.lang.title_entry) self.d_lab_one.set(self.lang.one_line) self.d_clear_button.set(self.lang.clear) self.d_start_down_btn.set(self.lang.start_download) self.d_stop_button.set(self.lang.stop_download) self.d_lb_save_in.set(self.lang.save_title) self.d_brownse_btn.set(self.lang.browse) except AttributeError: # at the moment do nothing pass def clear_text(self): self.my_text.delete(1.0, END) def browse_button(self): # Allow user to select a directory and store it in global var # called folder_path # global save_path self.filename = filedialog.askdirectory() if self.filename != '': self.save_path.set(self.filename) def stop_download(self): ''' stop download thread and reset all necessary values ''' if not self.ThreadLauncher.stopped(): self.ThreadLauncher.terminate() self.ThreadLauncher.join() # reset values self.global_downloading = False # set message download stopped # get message on current lang self.status_text.set(self.lang.down_videos_stopped) # hide stop button self.stop_button.grid_remove() return None def launch_down(self): if self.global_downloading: messagebox.showinfo(self.lang.running, self.lang.running_msg) return None self.ThreadLauncher = DownloaderThread(target=self.download) self.ThreadLauncher.start() # pass def download(self): # using try and except to execute program without errors try: # reset counters self.reset_values() # global v_counter, v_down format_video = '' if self.option_format.get() == 1: # video format_video = 'bestvideo+bestaudio/best' elif self.option_format.get() == 2: # audio format_video = 'bestaudio/best' else: raise RuntimeError( "Opzione formato di download non selezionato") self.where_save = self.save_path.get() self.my_progress.grid_remove() # default for audio format for_audio = { 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }] } download_options = { 'format': f'{format_video}', 'outtmpl': f'{self.where_save}\\%(title)s.%(ext)s', 'getfilename': '--get-filename', '--get-filename': True, 'progress_hooks': [self.my_hook], } if self.option_format.get() == 2: download_options.update(for_audio) list_links = self.my_text.get(1.0, END) list_down = list_links.splitlines() list_down = [line.rstrip('\n') for line in list_down] # check for correct links c_l = 0 for v_l in list_down: c_l += 1 if v_l.count('http') > 1 or v_l.count('HTTP') > 1: # self.status_text.set(f"Url not valid at line: {c_l}") raise RuntimeError(f"{self.lang.url_invalid}: {c_l}") self.v_counter = len(list_down) # check if empty list if (self.v_counter == 0 or (len(list_down) and list_down[0] == '')): self.status_text.set(self.lang.no_videos) return None with youtube_dl.YoutubeDL(download_options) as dl: self.my_progress.grid() self.stop_button.grid() self.global_downloading = True for video_link in list_down: if video_link == '': continue self.v_down += 1 dl.download([video_link]) self.status_text.set( f"{self.lang.all_downloaded} [{self.v_down}/{self.v_counter}]" ) self.global_downloading = False self.stop_button.grid_remove() # link.set("Video downloaded successfully") except RuntimeError as e: self.status_text.set(e) pass except Exception as e: self.status_text.set(e) self.global_downloading = False # hide stop button self.stop_button.grid_remove() print(e) pass def my_hook(self, d): try: # global percentage, curr_progress_bar # tmpfilename # here we should check if stop process is requested or not file_tuple = os.path.split(os.path.abspath(d['filename'])) # tmp_file_tuple = os.path.split(os.path.abspath(d['tmpfilename'])) # print(tmp_file_tuple) if not self.downloading: self.my_text1.configure(state='normal') self.my_text1.insert( 'end', f"{self.v_down}) {self.lang.starts_down_video}:" f"\n{file_tuple[1]}\n") self.my_text1.configure(state='disabled') self.downloading = True if d['status'] == 'finished': now = datetime.now() date_up = time.mktime(now.timetuple()) os.utime(d['filename'], (date_up, date_up)) # message_fin.set(f"Video \n {file_tuple[1]} \ndownloaded successfully") self.my_progress['value'] = 100 self.downloading = False self.my_text1.configure(state='normal') self.my_text1.insert( 'end', f"{self.v_down}) {self.lang.video_downloaded}\n") self.my_text1.configure(state='disabled') # self.percentage.config( # text=f"Downloaded... {self.my_progress['value']}%") self.s.configure("LabeledProgressbar", text=f"{self.my_progress['value']} % ") self.status_text.set( f"{self.lang.downloaded}... [{self.v_down}/{self.v_counter}]" ) self.root.update_idletasks() if d['status'] == 'downloading': p = d['_percent_str'] p = p.replace('%', '') p = d['_percent_str'] p = p.replace('%', '') percentage = float(p) self.my_progress['value'] = percentage self.status_text.set( f"{self.lang.downloading}... [{self.v_down}/{self.v_counter}]" ) self.s.configure("LabeledProgressbar", text=f"{self.my_progress['value']} % ") self.root.update_idletasks() except Exception as e: self.status_text.set(e) print(e) raise Exception(e)
img11 = PhotoImage("arrowup-n", file='../images/piratz/arrowup-n.png') img12 = PhotoImage("arrowup-p", file='../images/piratz/arrowup-p.png') img13 = PhotoImage("arrowdown-a", file='../images/piratz/arrowdown-a.png') img14 = PhotoImage("arrowdown-d", file='../images/piratz/arrowdown-d.png') img15 = PhotoImage("arrowdown-n", file='../images/piratz/arrowdown-n.png') img16 = PhotoImage("arrowdown-p", file='../images/piratz/arrowdown-p.png') img17 = PhotoImage("arrowleft-a", file='../images/piratz/arrowleft-a.png') img18 = PhotoImage("arrowleft-d", file='../images/piratz/arrowleft-d.png') img19 = PhotoImage("arrowleft-n", file='../images/piratz/arrowleft-n.png') img20 = PhotoImage("arrowleft-p", file='../images/piratz/arrowleft-p.png') img21 = PhotoImage("arrowright-a", file='../images/piratz/arrowright-a.png') img22 = PhotoImage("arrowright-d", file='../images/piratz/arrowright-d.png') img23 = PhotoImage("arrowright-n", file='../images/piratz/arrowright-n.png') img24 = PhotoImage("arrowright-p", file='../images/piratz/arrowright-p.png') style = Style() # both theme_create and theme_settings worked style.theme_create( "yummy", parent="clam", settings={ #style.theme_settings('default', { # start of theme extract "Horizontal.TScrollbar": { "layout": [("Horizontal.Scrollbar.trough", { "sticky": "ew", "children": [("Horizontal.Scrollbar.leftarrow", { "side": "left" }), ("Horizontal.Scrollbar.rightarrow", { "side": "right"
def initUI(self): self.home_dir = os.getcwd() self.master.title("Veraxx SOFASTe PDAL Manager") # Menu Bar menu = Menu(self.master) self.master.config(menu=menu) # File Menu file = Menu(menu, tearoff=0) file.add_command(label="Open PDAL", command=self.open_pdal) # add File Menu to Menu Bar menu.add_cascade(label="File", menu=file) # Actions Menu edit = Menu(menu, tearoff=0) edit.add_command(label="Scan for PDFs", command=self.pdfs_exist) edit.add_command(label="Remove .bak files", command=self.remove_bak) edit.add_command(label="Scan all for superseded", command=self.find_superseded) edit.add_command(label="Scan folder for superseded", command=self.find_superseded_in_folder) edit.add_command(label="Scan CAE filenames", command=self.CAE_filenames_valid) edit.add_command(label="Find \"forgot to introduce\"", command=self.find_files_not_introduced) # Add Validate Menu to Menu Bar menu.add_cascade(label="Actions", menu=edit) # Help Menu helpmenu = Menu(menu, tearoff=0) helpmenu.add_command(label="How to", command=self.howto_popup) menu.add_cascade(label="Help",menu=helpmenu) # Style and padding Style().configure("TButton", padding=(3, 5, 3, 5), font='serif 10') self.columnconfigure(0, pad=3) self.rowconfigure(0, pad=3) # Widget variables # Full path to PDAL self.pdal_dir = StringVar() # Name of PDAL TLD self.pdal_name = StringVar() self.pdal_name.set("No PDAL selected") self.load_persistent() # Listbox for drawing filenames self.lstbox_lbl = StringVar() self.lstbox_lbl.set("Files:") self.lstbox_export_fn = "export.txt" # Full path to cable CSV file self.cable_csv_path = StringVar() self.cable_csv_path.set("No CSV file selected") # Cable assy dwg number self.cable_assy_num = StringVar() self.cable_assy_num.set("No cable labels") # Configure the main widget group grp_main = LabelFrame(self.master, text="PDAL") grp_main.grid(row=0, column=0) grp_main.config(padx=50, pady=20) # PDAL directory label_pdal_name = Label(grp_main, textvariable = self.pdal_name, width=40) label_pdal_name.grid(row=0, column=1) # Listbox lstbx_files_lbl = Label(grp_main, textvariable = self.lstbox_lbl) lstbx_files_lbl.grid(row=0, column=2) self.lstbx_files = Listbox(grp_main, selectmode="extended", width=80) self.lstbx_files.grid(row=1, column=2) btn_export_lstbx = Button(grp_main, text="Export Listbox", command=self.export_listbox) btn_export_lstbx.grid(row=2, column=2) # Configure the cable labels widget group grp_cbllbl = LabelFrame(self.master, text="Cable Labels") grp_cbllbl.grid(row=1, column=0) grp_cbllbl.config(padx=50, pady=20) # Cable label file path cable_label_file = Label(grp_cbllbl, textvariable = self.cable_csv_path, width=40) cable_label_file.grid(row=0, column=0) btn_open_cable_csv = Button(grp_cbllbl, text="Open cable label CSV", command=self.open_cable_csv) btn_open_cable_csv.grid(row=1, column=0) # Cable Label Listbox lstbx_cables_lbl = Label(grp_cbllbl, textvariable = self.cable_assy_num) lstbx_cables_lbl.grid(row=0, column=1) self.lstbx_cables = Listbox(grp_cbllbl, selectmode="extended", width=80) self.lstbx_cables.grid(row=1, column=1) btn_print_labels = Button(grp_cbllbl, text="Print labels", command=self.print_labels) btn_print_labels.grid(row=2, column=1) btn_quit = Button(self.master, text="Quit", command=self.master.destroy) btn_quit.grid(row=3, column=0)
def __init__(self, tab_control, expense_controller, user_controller, username): """Initializes the expense tab and creates all elements of the visual interface""" # Input for the expense interface self.expense_controller = expense_controller self.user_controller = user_controller self.username = username self.category_list = self.user_controller.get_categories(self.username) self.chosen_currency = StringVar() self.chosen_category = StringVar() self.description = StringVar() self.price = StringVar() self.price_in_euro = StringVar() self.date = StringVar() self.currency_EUR_dict = { self.currency_code_list[i]: self.convert_to_EUR[i] for i in range(len(self.currency_code_list)) } try: # try to load latest currency conversion codes through an API response = requests.get('https://api.ratesapi.io/api/latest') for c in self.currency_code_list: try: # try to load conversion rate for specific currency self.currency_EUR_dict[c] = 1 / response.json()['rates'][c] except KeyError: # if not available (e.g. LBP) the hard-coded conversion rate is used pass except requests.exceptions.RequestException as e: # if no internet connection is available or the server is down, hard-coded conversion rates are used print(e) self.id_expenseItem = 0 total = self.expense_controller.total_expenses(self.username) self.sum_expenses = StringVar(value=f"Sum of all expenses: {total}€") self.budget_message = StringVar() self.expense_tab = ttk.Frame(tab_control) tab_control.add(self.expense_tab, text='Expenses') Label(self.expense_tab, text="New expense:", font='Helvetica 16 bold').grid(row=0, column=0, padx=15, pady=15, sticky='w') # DESCRIPTION Label(self.expense_tab, text="Description:").grid(row=1, column=0, padx=(15, 0), pady=2, sticky='w') Entry(self.expense_tab, textvariable=self.description).grid(row=1, column=1, pady=2, sticky="ew") # CATEGORY Label(self.expense_tab, text="Category:").grid(row=1, column=2, pady=2) self.category_select = OptionMenu(self.expense_tab, self.chosen_category, self.category_list[0], *self.category_list) self.category_select.grid(row=1, column=3, padx=(0, 15), pady=2, sticky="ew") # PRICE Label(self.expense_tab, text="Price:").grid(row=2, column=0, padx=(15, 0), pady=2, sticky='w') Entry(self.expense_tab, textvariable=self.price).grid(row=2, column=1, pady=2, sticky="ew") # CURRENCY OPTION Label(self.expense_tab, text="Currency:").grid(row=2, column=2, pady=2) OptionMenu(self.expense_tab, self.chosen_currency, self.currency_code_list[5], *self.currency_code_list)\ .grid(row=2, column=3, padx=(0, 15), pady=2, sticky="ew") # DATE Label(self.expense_tab, text="Date:").grid(row=3, column=0, padx=(15, 0), pady=2, sticky='w') DateEntry(self.expense_tab, background='darkblue', foreground='white', borderwidth=2, textvariable=self.date, date_pattern='dd/MM/yyyy').grid(row=3, column=1, pady=2, sticky="ew") # INSERT BUTTON Button(self.expense_tab, text="Insert", command=self.insert_expense_data).grid(row=4, column=1, pady=2, sticky="ew") Label(self.expense_tab, text="Your expenses:", font='Helvetica 16 bold').grid(row=5, column=0, padx=15, pady=15, sticky='w') # TOTAL EXPENSE Label(self.expense_tab, textvariable=self.sum_expenses).grid(row=6, column=0, padx=(15, 0), sticky='w') # BUDGET DIFFERENCE self.budgetLabel = Label(self.expense_tab, textvariable=self.budget_message) self.budgetLabel.grid(row=7, column=0, columnspan=2, padx=(15, 0), sticky='w') # set budget difference value budget_message = self.calculate_budget_level() self.budget_message.set(budget_message) # TREEVIEW WITH SCROLLBAR y_scroll = Scrollbar(self.expense_tab, orient='vertical') y_scroll.grid(row=8, column=5, padx=(0, 15), pady=(40, 15), sticky='nsw') self.treeExpense = ttk.Treeview(self.expense_tab, columns=('Date', 'Category', 'Description', 'Price', 'Currency', 'Price in EUR'), yscrollcommand=y_scroll.set, height=20) y_scroll['command'] = self.treeExpense.yview self.treeExpense.grid(row=8, column=0, columnspan=5, padx=(15, 0), pady=15) # Set the treeview columns self.treeExpense.heading('#0', text='Item Id') self.treeExpense.column("#0", minwidth=0, width=0) self.treeExpense.heading('#1', text='Date') self.treeExpense.column("#1", minwidth=0, width=120) self.treeExpense.heading('#2', text='Category') self.treeExpense.column("#2", minwidth=0, width=280) self.treeExpense.heading('#3', text='Description') self.treeExpense.column("#3", minwidth=0, width=280) self.treeExpense.heading('#4', text='Price') self.treeExpense.column("#4", minwidth=0, width=100) self.treeExpense.heading('#5', text='Currency') self.treeExpense.column("#5", minwidth=0, width=100) self.treeExpense.heading('#6', text='Price in EUR') self.treeExpense.column("#6", minwidth=0, width=100) # Restore display in table from the expense database self.update_treeview_from_existing_database() # DELETE BUTTON # Configure delete button style to be red style = Style() style.configure('W.TButton', foreground='red') Button(self.expense_tab, text="Delete", style='W.TButton', command=self.delete_expense_data).grid(row=9, column=4, padx=15, sticky="e") # SORT THE PRICE: CALL FUNCTION col1 = "Price" col2 = "Price in EUR" col3 = "Date" self.treeExpense.heading( col1, text=col1, command=lambda: self.treeview_sort_price(col1, False)) self.treeExpense.heading( col2, text=col2, command=lambda: self.treeview_sort_price(col2, False)) # SORT THE DATE: CALL FUNCTION self.treeExpense.heading( col3, text=col3, command=lambda s=col3: self.treeview_sort_date(col3, False))
lbl = Label(window, text="Anna Du ROV V1.0 Microplastics Image Recognition System", font=("Arial Bold", 50), bg="cyan") lbl.grid(column=10, row=20) lbls = Label(window, text="Choose An Option Below", font=("Arial Bold", 40), bg="medium orchid") lbls.grid(column=10, row=25, sticky="w") sep = Separator(window, orient="horizontal") sep.grid(column=5, row=23, columnspan=20, sticky="ew") sty = Style(window) sty.configure("TSeparator", background="red") btn = Button(window, command=open2, text="Infrared Comparison Color Mapper", font=("Arial Bold", 25), height=2) btn.grid(column=10, row=30, sticky="w") lblss = Label(window, text="Unnatural Colors", font=("Arial Bold", 40), bg="medium orchid") lblss.grid(column=10, row=35, sticky="w")
class GuiBasic(Frame): """ Базовый класс для окна запрос к api и вывод данных в лог :param options: width: ширина height: высота """ options = { 'width': 500, 'height': 350, 'title': 'Program', 'win_style': 'winnative' } def __init__( self, parent, options=None, ): """ :param parent: базовый объект Tk :param options: параметры вывода """ print('Start init') self.parent = parent self.base_frame = Frame(parent) self.style = Style() self.parent = parent # self.pack(fill=BOTH, expand=1) self.base_frame.pack(fill=BOTH) # todo: refactor params and concate if options: self.options.update(options) self.create_window() # self.init_ui() def create_window(self): """ создание рабочей области задаём размеры и положение окна """ print('Creating window') self.parent.title(self.options['title']) self.style.theme_use(self.options['win_style']) w = self.options['width'] h = self.options['height'] sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry('{0}x{1}+{2:.0f}+{3:.0f}'.format(w, h, x, y)) # gui_frame = Frame(relief=RAISED, borderwidth=3) # добавляем новый фрейм для группирования # gui_frame.pack(fill=BOTH, expand=True) # self.gui_frame = gui_frame return True def init_ui(self): """ здесь создаём сам каркас\grid окна """ pass def add_button(self): pass def btn_quit(self): """ завершение работы с выводом сообщения """ print('Program end') self.quit()
class ScenarioList(Frame): def __init__(self, parent): super().__init__(parent) self.initUI() def initUI(self): self.style = Style() self.style.theme_use('clam') self.acts = [] self.selected = [] self.scDir = 'Scenarios/' listFrame = Frame(self) listFrame.pack(pady=15) self.lb = Listbox(listFrame) self.lb.grid(row=0, column=0, columnspan=2, padx=5) self.lb.bind("<<ListboxSelect>>", self.onSelect) self.updateList() deleteBtn = Button(listFrame, text='Delete') deleteBtn.grid(row=0, column=2, padx=1) deleteBtn.bind('<ButtonRelease-1>', self.onDeleteClick) self.lbl = Label(self, text='Scenario Name: ') self.lbl.pack() self.scName = Entry(self, width=25) self.scName.pack() self.recBtn = Button(self, text='Record', width=10, height=1) self.recBtn.pack(pady=10) self.recBtn.bind('<ButtonRelease-1>', self.onButtonClick) def onButtonClick(self, event): if self.recBtn['text'] == 'Record': if self.scName.get() != "": Recorder.RecorderFileName = self.scName.get() log.writeEvent('Record') Recorder.RecorderState = 'recording' self.recBtn['text'] = 'Save' else: messagebox.showerror( "No Scenario Name", " You Should Specify a Name for your Scenario" + " before starting to record") return else: if self.scName.get() == "": messagebox.showerror( "No Scenario Name", " You Should Specify a Name for your Scenario") return log.writeEvent('Save') self.recBtn['text'] = 'Record' log.saveRecordedScenario(self.scName.get()) self.updateList() scenarioEvents = log.getScenarioEvents(self.scName.get()) scc = ScenarioCenter(self, scenarioEvents, self.scName.get()) scc.mainloop() def updateList(self): self.lb.delete(0, END) self.acts = [] for file in os.listdir(self.scDir): self.acts.append(file.split('.')[0]) for i in self.acts: self.lb.insert(END, i) def onSelect(self, val): self.selected = self.lb.curselection() def onDeleteClick(self, event): log.deleteScenarioFile(self.acts[self.selected[0]]) self.updateList()
root.resizable(width=False, height=False) root['bg']='lightgray' root.title("Waveguide") w = 1000 h = 630 sw = root.winfo_screenwidth() sh = root.winfo_screenheight() x = (sw - w)/2 y = (sh - h)/2 root.geometry('%dx%d+%d+%d' % (w, h, x, y)) label_n = Label(root, text="Выберите тип волны:", font=LARGE_FONT, bg="lightgray") label_n.grid(row=0, column=0, columnspan=2, padx=30, sticky=SW) style = Style() style.configure("BW.TLabel", foreground='black', background='lightgray', selectbackground='lightgray', selectforeground='black') combobox = Combobox(values = ["TE","TM"], height=2, width=4, state="readonly", style="BW.TLabel", font=LARGE_FONT) combobox.set("TE") combobox.grid(row=0, column=2, columnspan=2, sticky=SW) root.option_add("*TCombobox*Listbox*Background", 'gainsboro') root.option_add("*TCombobox*Listbox*Foreground", 'black') moda_label = Label(root, text="Выберите моду:", font=LARGE_FONT, bg="lightgray") moda_label.grid(row=1, column=0, columnspan=4, padx=30, sticky=SW) moda_n=0 label_n = Label(root, text="n: ", font=LARGE_FONT, bg="lightgray") label_n.grid(row=3, column=0, padx=10, sticky=E) moda_n_label = Label(root, text=moda_n, font=LARGE_FONT, bg="lightgray")