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
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 __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 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)
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()
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 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()
class SecondaryWindow(TkApplication): 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() def setup(self): self.set_title("Piscis") self.pygubu_builder.get_object('main_frame', self.master) self.canvas.append(self._create_canvas('canvas_one')) self.canvas.append(self._create_canvas('canvas_two')) self.canvas.append(self._create_canvas('canvas_three')) self.canvas.append(self._create_canvas('canvas_four')) self.change_background_color(BACKGROUND_COLOR) def _create_canvas(self, identifier): return self.pygubu_builder.get_object(identifier, self.master) def set_fullscreen(self): self.master.overrideredirect(True) self.master.geometry("%dx%d+0+0" % (self.master.winfo_screenwidth(), self.master.winfo_screenheight())) def change_background_color(self, color): self.style.configure('TFrame', background=color) self.current_background_color = color def change_canvas_background(self, color, id_number): self.canvas[id_number].configure(background=color)
def __init__(self, file=None): Tk.__init__(self, className="Sudoku-Tk") self.title("Sudoku-Tk") self.resizable(0, 0) self.protocol("WM_DELETE_WINDOW", self.quitter) cst.set_icon(self) self.columnconfigure(3, weight=1) # --- style bg = '#dddddd' activebg = '#efefef' pressedbg = '#c1c1c1' lightcolor = '#ededed' darkcolor = '#cfcdc8' bordercolor = '#888888' focusbordercolor = '#5E5E5E' disabledfg = '#999999' disabledbg = bg button_style_config = {'bordercolor': bordercolor, 'background': bg, 'lightcolor': lightcolor, 'darkcolor': darkcolor} button_style_map = {'background': [('active', activebg), ('disabled', disabledbg), ('pressed', pressedbg)], 'lightcolor': [('pressed', darkcolor)], 'darkcolor': [('pressed', lightcolor)], 'bordercolor': [('focus', focusbordercolor)], 'foreground': [('disabled', disabledfg)]} style = Style(self) style.theme_use(cst.STYLE) style.configure('TFrame', background=bg) style.configure('TLabel', background=bg) style.configure('TScrollbar', gripcount=0, troughcolor=pressedbg, **button_style_config) style.map('TScrollbar', **button_style_map) style.configure('TButton', **button_style_config) style.map('TButton', **button_style_map) style.configure('TCheckutton', **button_style_config) style.map('TCheckutton', **button_style_map) self.option_add('*Toplevel.background', bg) self.option_add('*Menu.background', bg) self.option_add('*Menu.activeBackground', activebg) self.option_add('*Menu.activeForeground', "black") self.configure(bg=bg) style.configure("bg.TFrame", background="grey") style.configure("case.TFrame", background="white") style.configure("case.TLabel", background="white", foreground="black") style.configure("case_init.TFrame", background="lightgrey") style.configure("case_init.TLabel", background="lightgrey", foreground="black") style.configure("erreur.TFrame", background="white") style.configure("erreur.TLabel", background="white", foreground="red") style.configure("solution.TFrame", background="white") style.configure("solution.TLabel", background="white", foreground="blue") style.configure("pause.TLabel", foreground="grey", background='white') # --- images self.im_erreur = open_image(cst.ERREUR) self.im_pause = open_image(cst.PAUSE) self.im_restart = open_image(cst.RESTART) self.im_play = open_image(cst.PLAY) self.im_info = open_image(cst.INFO) self.im_undo = open_image(cst.UNDO) self.im_redo = open_image(cst.REDO) self.im_question = open_image(cst.QUESTION) # --- timer self.chrono = [0, 0] self.tps = Label(self, text=" %02i:%02i" % tuple(self.chrono), font="Arial 16") self.debut = False # la partie a-t-elle commencée ? self.chrono_on = False # le chrono est-il en marche ? # --- buttons self.b_pause = Button(self, state="disabled", image=self.im_pause, command=self.play_pause) self.b_restart = Button(self, state="disabled", image=self.im_restart, command=self.recommence) self.b_undo = Button(self, image=self.im_undo, command=self.undo) self.b_redo = Button(self, image=self.im_redo, command=self.redo) # --- tooltips self.tooltip_wrapper = TooltipWrapper(self) self.tooltip_wrapper.add_tooltip(self.b_pause, _("Pause game")) self.tooltip_wrapper.add_tooltip(self.b_restart, _("Restart game")) self.tooltip_wrapper.add_tooltip(self.b_undo, _("Undo")) self.tooltip_wrapper.add_tooltip(self.b_redo, _("Redo")) # --- numbers frame_nb = Frame(self, style='bg.TFrame', width=36) self.progression = [] for i in range(1, 10): self.progression.append(Progression(frame_nb, i)) self.progression[-1].pack(padx=1, pady=1) # --- level indication frame = Frame(self) frame.grid(row=0, columnspan=5, padx=(30, 10), pady=10) Label(frame, text=_("Level") + ' - ', font="Arial 16").pack(side='left') self.label_level = Label(frame, font="Arial 16", text=_("Unknown")) self.label_level.pack(side='left') self.level = "unknown" # puzzle level # --- frame contenant la grille de sudoku self.frame_puzzle = Frame(self, style="bg.TFrame") self.frame_pause = Frame(self, style="case.TFrame") self.frame_pause.grid_propagate(False) self.frame_pause.columnconfigure(0, weight=1) self.frame_pause.rowconfigure(0, weight=1) Label(self.frame_pause, text='PAUSE', style='pause.TLabel', font='Arial 30 bold').grid() # --- placement frame_nb.grid(row=1, column=6, sticky='en', pady=0, padx=(0, 30)) self.frame_puzzle.grid(row=1, columnspan=5, padx=(30, 15)) self.tps.grid(row=2, column=0, sticky="e", padx=(30, 10), pady=30) self.b_pause.grid(row=2, column=1, sticky="w", padx=2, pady=30) self.b_restart.grid(row=2, column=2, sticky="w", padx=2, pady=30) self.b_undo.grid(row=2, column=3, sticky="e", pady=30, padx=2) self.b_redo.grid(row=2, column=4, sticky="w", pady=30, padx=(2, 10)) # --- menu menu = Menu(self, tearoff=0) menu_nouveau = Menu(menu, tearoff=0) menu_levels = Menu(menu_nouveau, tearoff=0) menu_levels.add_command(label=_("Easy"), command=self.new_easy) menu_levels.add_command(label=_("Medium"), command=self.new_medium) menu_levels.add_command(label=_("Difficult"), command=self.new_difficult) menu_nouveau.add_cascade(label=_("Level"), menu=menu_levels) menu_nouveau.add_command(label=_("Generate a puzzle"), command=self.genere_grille, accelerator="Ctrl+G") menu_nouveau.add_command(label=_("Empty grid"), command=self.grille_vide, accelerator="Ctrl+N") menu_ouvrir = Menu(menu, tearoff=0) menu_ouvrir.add_command(label=_("Game"), command=self.import_partie, accelerator="Ctrl+O") menu_ouvrir.add_command(label=_("Puzzle"), command=self.import_grille, accelerator="Ctrl+Shift+O") menu_game = Menu(menu, tearoff=0) menu_game.add_command(label=_("Restart"), command=self.recommence) menu_game.add_command(label=_("Solve"), command=self.resolution) menu_game.add_command(label=_("Save"), command=self.sauvegarde, accelerator="Ctrl+S") menu_game.add_command(label=_("Export"), command=self.export_impression, accelerator="Ctrl+E") menu_game.add_command(label=_("Evaluate level"), command=self.evaluate_level) menu_language = Menu(menu, tearoff=0) self.langue = StringVar(self) self.langue.set(cst.LANGUE[:2]) menu_language.add_radiobutton(label="Français", variable=self.langue, value="fr", command=self.translate) menu_language.add_radiobutton(label="English", variable=self.langue, value="en", command=self.translate) menu_help = Menu(menu, tearoff=0) menu_help.add_command(label=_("Help"), command=self.aide, accelerator='F1') menu_help.add_command(label=_("About"), command=self.about) menu.add_cascade(label=_("New"), menu=menu_nouveau) menu.add_cascade(label=_("Open"), menu=menu_ouvrir) menu.add_cascade(label=_("Game"), menu=menu_game) menu.add_cascade(label=_("Language"), menu=menu_language) menu.add_command(label=_("Statistics"), command=self.show_stat) menu.add_cascade(label=_("Help"), menu=menu_help) self.configure(menu=menu) # --- clavier popup self.clavier = None # --- cases self.nb_cases_remplies = 0 self.blocs = np.zeros((9, 9), dtype=object) for i in range(9): for j in range(9): self.blocs[i, j] = Case(self.frame_puzzle, i, j, self.update_nbs, width=50, height=50) px, py = 1, 1 if i % 3 == 2 and i != 8: py = (1, 3) if j % 3 == 2 and j != 8: px = (1, 3) self.blocs[i, j].grid(row=i, column=j, padx=px, pady=py) self.blocs[i, j].grid_propagate(0) # --- undo/redo stacks self._undo_stack = [] self._redo_stack = [] # --- raccourcis clavier et actions de la souris self.bind("<Button>", self.edit_case) self.bind("<Control-z>", lambda e: self.undo()) self.bind("<Control-y>", lambda e: self.redo()) self.bind("<Control-s>", lambda e: self.sauvegarde()) self.bind("<Control-e>", lambda e: self.export_impression()) self.bind("<Control-o>", lambda e: self.import_partie()) self.bind("<Control-Shift-O>", lambda e: self.import_grille()) self.bind("<Control-n>", lambda e: self.grille_vide()) self.bind("<Control-g>", lambda e: self.genere_grille()) self.bind("<FocusOut>", self.focus_out) self.bind("<F1>", self.aide) # --- open game if file: try: self.load_sudoku(file) except FileNotFoundError: one_button_box(self, _("Error"), _("The file %(file)r does not exist.") % file, image=self.im_erreur) except (KeyError, EOFError, UnpicklingError): try: self.load_grille(file) except Exception: one_button_box(self, _("Error"), _("This file is not a valid sudoku file."), image=self.im_erreur) elif exists(cst.PATH_SAVE): self.load_sudoku(cst.PATH_SAVE) remove(cst.PATH_SAVE)
class Clavier(Toplevel): """ Pavé numérique pour choisir un chiffre """ 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 focus_out(self, event): """ quitte si la fenêtre n'est plus au premier plan """ try: if not self.focus_get(): self.quitter() except KeyError: # erreur déclenchée par la présence d'une tkMessagebox self.quitter() def entre_nb(self, val): """ commande de la touche val du clavier """ i, j = self.case.get_i(), self.case.get_j() # données pour le log val_prec = self.case.get_val() pos_prec = self.case.get_possibilites().copy() modifs = [] # modification de la case if self.type == "val": self.master.modifie_nb_cases_remplies(self.case.edit_chiffre(val)) if not self.master.test_case(i, j, val_prec): modifs = self.master.update_grille(i, j, val_prec) self.quitter() else: self.master.modifie_nb_cases_remplies(self.case.edit_possibilite(val)) self.master.test_possibilite(i, j, val) # données pour le log pos = self.case.get_possibilites().copy() val = self.case.get_val() self.master.stacks_modif((i, j, val_prec, pos_prec, modifs, val, pos)) self.master.test_remplie() def quitter(self): """ ferme la fenêtre """ if self.master: self.master.focus_set() self.master.set_clavier(None) self.destroy() def set_case(self, case): self.case = case def display(self, geometry): self.geometry(geometry) self.update_idletasks() self.deiconify() self.focus_set() self.lift() self.bind("<FocusOut>", self.focus_out)
rather than pack or grid layout managers. The classic theme displays a quirky arrow change when the borderwidth is changed. ''' from tkinter import Tk, font from tkinter.ttk import Style, Scrollbar root = Tk() style = Style() style.theme_use('classic') test_size = font.Font(family="Times", size=12, weight="bold").measure('Test') mult = int(test_size / 30) style.configure("1st.Horizontal.TScrollbar", background="Green", troughcolor="lightblue", bordercolor="blue", arrowsize=20 * mult, borderwidth=5) style.configure("2nd.Horizontal.TScrollbar", background="Green", troughcolor="lightblue", bordercolor="blue", arrowsize=20 * mult) hs = Scrollbar(root, orient="horizontal", style="1st.Horizontal.TScrollbar") hs.place(x=5 * mult, y=5 * mult, width=150 * mult) hs.set(0.2, 0.3) hs2 = Scrollbar(root, orient="horizontal", style="2nd.Horizontal.TScrollbar") hs2.place(x=5 * mult, y=50 * mult, width=150 * mult)
def initUI(self): self.title("Loan Calculator") self.geometry("300x300") self.style = Style() self.style.theme_use("default") # default #self.pack(fill=BOTH, expand=1) xpos = 40 ypos = 30 xpos2 = xpos + 100 l1 = Label(self, text="Amount", foreground="#ff0000", background="light blue", font="Arial 9") # Arial 12 bold italic l1.place(x=xpos, y=ypos) self.txtAmount = Entry(self) self.txtAmount.place(x=xpos2, y=ypos, width=70) ypos += 30 l2 = Label(self, text="Rate(%)", foreground="#ff0000", background="light blue", font="Arial 9") # Arial 12 bold italic l2.place(x=xpos, y=ypos) self.txtRate = Entry(self) self.txtRate.place(x=xpos2, y=ypos) ypos += 30 l3 = Label(self, text="Duration(months)", foreground="#ff0000", background="light blue", font="Arial 9") # Arial 12 bold italic l3.place(x=xpos, y=ypos) self.txtDuration = Entry(self) self.txtDuration.place(x=xpos2, y=ypos) ypos += 30 l4 = Label(self, text="Monthly Payment", foreground="#ff0000", background="yellow", font="Arial 9") # Arial 12 bold italic l4.place(x=xpos, y=ypos) self.txtMonthlyPayment = Entry(self) self.txtMonthlyPayment.configure(state="readonly") self.txtMonthlyPayment.place(x=xpos2, y=ypos) ypos += 30 l5 = Label(self, text="Total Payments", foreground="#ff0000", background="yellow", font="Arial 9") # Arial 12 bold italic l5.place(x=xpos, y=ypos) self.txtTotalPayment = Entry(self) self.txtTotalPayment.configure(state="readonly") self.txtTotalPayment.place(x=xpos2, y=ypos) ypos += 30 style = Style() style.configure("Exit.TButton", foreground="red", background="white") #T.Checkbutton for checboxes style.configure("MainButton.TButton", foreground="yellow", background="red") exitButton = Button(self, text="Exit", command=self.exitButtonClick) exitButton.configure(style="Exit.TButton") exitButton.place(x=xpos, y=ypos) calcButton = Button(self, text="Calculate", command=self.calcButtonClick) calcButton.configure(style="MainButton.TButton") calcButton.place(x=xpos2, y=ypos)
def initUI(self): self.master.title("Review") self.pack(fill=BOTH, expand=True) self.frame1 = Frame(self) self.frame1.pack(fill=X) btn1 = Button(self.frame1, text="Load", width=6,command=self.browse_Module) btn1.pack(side=LEFT, padx=20, pady=10) # btn2 = Button(self.frame1, text="Save", width=6) #btn2.pack(side=LEFT, padx=50, pady=10,expand=True) L = ['Processing','full ahe', 'intensiv normalization', 'deconvolution'] self.vS = StringVar(self.frame1) self.vS.set(L[0]) self.oS = OptionMenu(self.frame1, self.vS, *L) self.oS.pack(side=RIGHT, padx=80, pady=10) self.frame2 = Frame(self) self.frame2.pack(fill=X) lbl2 = Label(self.frame2, text="X =", width=2) lbl2.pack(side=LEFT,anchor=N, padx=2, pady=5) entry1 = Entry(self.frame2,width=8) entry1.pack(side=LEFT,pady=5) self.frame3 = Frame(self) self.frame3.pack(fill=X) lbl3 = Label(self.frame3, text="Y =", width=2) lbl3.pack(side=LEFT, anchor=N, padx=2, pady=5) entry2 = Entry(self.frame3,width=8) entry2.pack(side=LEFT, pady=5) self.frame4 = Frame(self) self.frame4.pack(fill=X) lbl4 = Label(self.frame4, text="Z =", width=2) lbl4.pack(side=LEFT, anchor=N, padx=2, pady=5) entry3 = Entry(self.frame4,width=8) entry3.pack(side=LEFT, pady=5) self.frame5 = Frame(self, relief=RAISED, borderwidth=1) self.frame5.pack(fill=BOTH,expand=True) self.frame6 = Frame(self) self.frame6.pack(fill=X) s = Style() s.configure("TProgressbar", thickness=100) mpb = Progressbar(self.frame6, orient="horizontal", length=200, mode="determinate",style="TProgressbar") mpb.pack(fill=X,expand=True,pady=10,padx=100) mpb["maximum"] = 100 mpb["value"] = 50 startButton = Button(self,text="Start", state=DISABLED) startButton.pack(side=RIGHT, padx=10, pady=10) saveButton = Button(self, text="Save") saveButton.pack(side=LEFT,padx=10,pady=10)
s2 = PhotoImage("search2", data=data, format="gif -index 1") style = Style() style.theme_use('default') style.element_create("Search.field", "image", "search1", ("focus", "search2"), border=[22, 7, 14], sticky="ew") style.layout("Search.entry", [ ("Search.field", {"sticky": "nswe", "border": 1, "children": [("Entry.padding", {"sticky": "nswe", "children": [("Entry.textarea", {"sticky": "nswe"})] })] })] ) style.configure("Search.entry", background="#b2b2b2", font=font.nametofont("TkDefaultFont")) root.configure(background="#b2b2b2") e1 = Entry(style="Search.entry", width=20) e1.grid(padx=10, pady=10) e2 = Entry(style="Search.entry", width=20) e2.grid(padx=10, pady=10) root.mainloop()
class App(object): screen_background = "#EAEAAE" screen_resizable = (False,False) screen_title = "File Transfer GUI" __address = None __path = None __mode = FileTransfer.CLIENT def __init__(self): # Obtém a largura da tela do dispositivo do usuário self.__window = Tk() width = self.__window.winfo_screenwidth() default_width = 600 self.__window.destroy() # Define o tamanho da janela do programa if width >= default_width: self.screen_geometry = [default_width,int(0.16666666666666666666666666666667*default_width)] else: self.screen_geometry = [width,int(0.16666666666666666666666666666667*width)] # Ajusta o tamanho de fonte, largura e outros com base na resolução da janela do programa self.button_font = ("Arial",int(15/default_width*self.screen_geometry[0])) self.button_width = int(10/default_width*self.screen_geometry[0]) self.entry_font = ("Arial",int(20/default_width*self.screen_geometry[0])) self.filename_size = int(20/default_width*self.screen_geometry[0]) self.label_font = ("Arial",int(15/default_width*self.screen_geometry[0])) self.__sep = int(5/default_width*self.screen_geometry[0]) # Cria um objeto para realizar a transferência self.fileTransfer = FileTransfer() # Cria a janela self.buildWindow() # Cria parte para inserir o endereço e tipo da transferência self.buildInterfaceToCreateConnection() self.__window.mainloop() def buildWindow(self,title=screen_title): """ Método para criar a janela do programa. """ # Cria janela e realiza algumas configurações self.__window = Tk() self.__window.title(title) self.__window.resizable(*self.screen_resizable) self.__window.geometry("{}x{}".format(*self.screen_geometry)) self.__window.protocol("WM_DELETE_WINDOW",self.close) self.__window["bg"] = self.screen_background # Cria estilos dos botões do programa self.__style = Style() self.__style.configure("SELECTED.TButton",background=self.screen_background,foreground="red",font=self.button_font,width=self.button_width) self.__style.configure("TButton",background=self.screen_background,foreground="black",font=self.button_font,width=self.button_width) def buildInterfaceToCreateConnection(self): """ Método para criar uma interface para o usuário inserir o endereço e tipo de transferência. """ def clearEntry(entry): """ Função para limpar o título das Entrys. """ if entry.hasTitle and entry.get() == entry.title: entry.delete(0,"end") entry.hasTitle = False # Cria um frame para colocar as Entrys de IP e PORT NUMBER entrysFrame = Frame(self.__window,bg=self.screen_background) entrysFrame.pack(side="left",padx=self.__sep) # Cria uma entry para inserir o IP self.__ip_entry = Entry(entrysFrame,font=self.entry_font) self.__ip_entry.title = "IP: " self.__ip_entry.insert(0,self.__ip_entry.title) self.__ip_entry.hasTitle = True self.__ip_entry.bind("<Button-1>",lambda event: clearEntry(self.__ip_entry)) self.__ip_entry.pack(padx=self.__sep) # Cria uma entry para inserir o PORT NUMBER self.__port_entry = Entry(entrysFrame,font=self.entry_font) self.__port_entry.title = "PORT: " self.__port_entry.insert(0,self.__port_entry.title) self.__port_entry.hasTitle = True self.__port_entry.bind("<Button-1>",lambda event: clearEntry(self.__port_entry)) self.__port_entry.pack(padx=self.__sep,pady=self.__sep) # Cria um frame para os botões buttonsFrame = Frame(self.__window,bg=self.screen_background) buttonsFrame.pack(side="left",padx=self.__sep) #Cria um frame somente para botões de seleção de modo de transferência modeButtonsFrame = Frame(buttonsFrame,bg=self.screen_background) modeButtonsFrame.pack(side="top",pady=self.__sep*2) # Cria um botão para selecionar o modo Client (Download). Por padrão, ele já é selecionado. self.clientButton = Button(modeButtonsFrame,text="Client",style="SELECTED.TButton") self.clientButton.config(command=lambda: self.setMode("client",True)) self.clientButton.pack(side="left",padx=self.__sep) # Cria um botão para selecionar o modo Host (Upload) self.hostButton = Button(modeButtonsFrame,text="Host",style="TButton") self.hostButton.config(command=lambda: self.setMode("host",True)) self.hostButton.pack(side="left",padx=self.__sep) # Cria um botão para prosseguir self.continueButton = Button(buttonsFrame,text="Continue",width=(self.button_width*2)-3+self.__sep,style="TButton") self.continueButton.config(command=self.buildInterfaceToSelectPathOrFilename) self.continueButton.pack(side="top",pady=self.__sep) def buildInterfaceToSelectPathOrFilename(self): """ Método para criar uma interface onde o usuário possa escolher o arquivo que será enviado ou o diretório onde o arquivo baixado será salvo. """ def clearEntry(entry): """ Função para limpar o título das Entrys. """ if entry.hasTitle and entry.get() == entry.title: entry.delete(0,"end") entry.hasTitle = False elif self.__path: entry.delete(0,"end") self.__path_entry.insert(0,self.__path) def setPath(): """ Função para definir o caminho do arquivo ou da pasta. """ path = functionToGetDirectory() if not path or path == self.__path_entry.title: return self.__path_entry.delete(0,"end") self.__path_entry.insert(0,path) self.__path = path # Recebe o IP e o PORT NUMBER dentro das entrys ip = self.__ip_entry.get() port = self.__port_entry.get() # Se o PORT NUMBER não for numérico ou o usuário não # tiver inserido um IP ou PORT NUMBER, não será possível prosseguir. if port.isnumeric(): port = int(port) else: return if (not ip or ip == self.__ip_entry.title) or (not port or port == self.__port_entry.title): return self.__address = (ip,port) # Destrói a janela antiga para criar uma nova self.__window.destroy() self.buildWindow(self.screen_title+" [ {} : {} ]".format(*self.__address)) # Cria uma entry para guardar o caminho do arquivo ou pasta selecionada self.__path_entry = Entry(self.__window,font=self.entry_font) # Define o título da entry e a função para selecionar # o caminho do arquivo ou pasta, com base no modo de transferência # selecionado anteriormente. if self.__mode == FileTransfer.CLIENT: self.__path_entry.title = "Directory to save file: " self.__path_entry.insert(0,self.__path_entry.title) functionToGetDirectory = askdirectory else: self.__path_entry.title = "File to upload: " self.__path_entry.insert(0,self.__path_entry.title) functionToGetDirectory = askopenfilename # Configura a entry self.__path_entry.hasTitle = True self.__path_entry.bind("<Button-1>",lambda event: clearEntry(self.__path_entry)) self.__path_entry.pack(side="left",padx=self.__sep*2) # Cria botão para selecionar um arquivo ou pasta findButton = Button(self.__window,text="Search",command=setPath,style="TButton") findButton.pack(side="left",padx=self.__sep) # Cria um botão para iniciar a transferência connectButton = Button(self.__window,text="Connect",style="TButton") connectButton.config(command=self.buildInterfaceToConnect) connectButton.pack(side="left",padx=self.__sep) self.__window.mainloop() def buildInterfaceToConnect(self): """ Método para criar uma interface onde o usuário possa ver tudo relacionado à conexão do client e servidor e transferência do arquivo. """ # Caso o usuário não tenha selecionado um arquivo ou pasta, # não será possível prosseguir. if not self.__path: return if self.__path != self.__path_entry.get(): self.__path_entry.delete(0,"end") self.__path_entry.insert(0,self.__path) return # Destrói a janela antiga para criar uma nova self.__window.destroy() self.buildWindow(self.screen_title+" [ {} : {} ]".format(*self.__address)) # Cria um label para mostrar todas as informações da transferência e conexão self.__infoLabel = Label(self.__window,bg=self.screen_background,font=self.label_font) self.__infoLabel.pack(pady=self.__sep*3) # Essa variável irá guardar a resposta da conexão. self.__resp = None def connect(): """ Função para iniciar a conexão """ try: # Obtêm uma resposta da conexão self.__resp = self.fileTransfer.connect(self.__address) self.buildInterfaceToTransfer() except: self.__infoLabel.config(text="Failed to attempt to connect.") Button(self.__window,text="Close",command=self.close,style="TButton").pack() # Define o modo da transferência self.fileTransfer.changeMode(self.__mode) # Informa o usuário que a conexão está sendo estabelecida if self.__mode == FileTransfer.CLIENT: self.__infoLabel.config(text="Connecting ...") self.fileTransfer.changePath(self.__path) else: self.fileTransfer.changeFileName(self.__path) self.__infoLabel.config(text="Awaiting connection ...") # Cria um processo para tentar conectar-se sem causar danos à interface gráfica Thread(target=connect).start() self.__window.mainloop() def buildInterfaceToTransfer(self): """ Método para criar uma interface para o usuário acompanhar o progresso da transferência. """ def transfer(): """ Função para iniciar a transferência """ def threadFunction(): """ Função que será executada dentro de uma Thread para realizar a transferência sem causar danos à interface gráfica. """ try: self.fileTransfer.transfer(progressFunction) self.__progressBar.forget() self.__infoLabel.config(text="Transfer completed successfully.") Button(self.__window,text="Close",command=self.close,style="TButton").pack() except: self.__progressBar.forget() if self.__mode == FileTransfer.CLIENT: self.__infoLabel.config(text="A failure occurred during the transfer.") else: self.__infoLabel.config(text="Connection terminated.") Button(self.__window,text="Close",command=self.close,style="TButton").pack() # Destrói o botão para permitir o download downloadButton.destroy() # Cria um objeto de DoubleVar para o preenchimento da barra de progresso self.__variable = DoubleVar() self.__variable.set(0) # Cria uma barra de progresso para o usuário ter uma noção maior do andamento da transferência self.__progressBar = Progressbar( self.__window, variable=self.__variable, maximum=100, length=100*(int(self.screen_geometry[0]/100))-(self.__sep*2) ) self.__progressBar.pack() # Executa toda a transferência dentro de uma thread Thread(target=threadFunction).start() def progressFunction(percent): """ Função para atualizar o progresso da transferência. """ if self.__mode == FileTransfer.CLIENT: filename = self.__resp[0] # Verifica se o tamanho do nome do arquivo é maior que o tamanho limite. Se sim, ele será reduzido if len(filename.split(".")[0]) > self.filename_size: filename = filename.split(".")[0][0:self.filename_size]+"."+filename.split(".")[-1] self.__infoLabel.config(text='Downloading "{}" ... {}%'.format(filename,int(percent))) else: filename = self.__path[-1] # Verifica se o tamanho do nome do arquivo é maior que o tamanho limite. Se sim, ele será reduzido if len(filename.split(".")[0]) > self.filename_size: filename = filename.split(".")[0][0:self.filename_size]+"."+filename.split(".")[-1] self.__infoLabel.config(text='Sending "{}" ... {}%'.format(filename,int(percent))) self.__variable.set(percent) # Transforma a resposta da conexão em uma lista resp = list(self.__resp) # Divide o diretório self.__path = os.path.split(self.__path) # Cria um botão para que o usuário autorize ou não o download downloadButton = Button(self.__window,text="Download",width=self.button_width,command=transfer,style="TButton") # Se o usuário estiver realizando o download do arquivo, # será mostrado o nome do arquivo, sua extensão e o tamanho # do arquivo formatado em (Bytes,KB,MB,GB,TB). # O botão para permitir o download será mostrado apenas nesse modo. # Caso o usuário esteja realizando o envio do arquivo, o programa será # mandado direto para a função de transferência onde o usuário, # terá que aguardar o Client autorizar o envio. if self.__mode == FileTransfer.CLIENT: # Formata o tamanho do arquivo resp[1] = int(float(resp[1])) size = FileTransfer.getFormattedSize(resp[1]) # Verifica se o tamanho do nome do arquivo é maior que o tamanho limite. Se sim, ele será reduzido if len(resp[0].split(".")[0]) > self.filename_size: resp[0] = resp[0].split(".")[0][0:self.filename_size]+"."+resp[0].split(".")[-1] self.__infoLabel.config(text="%s [%.2f %s]"%(resp[0],size[0],size[1])) downloadButton.pack() else: self.__infoLabel.config(text="Awaiting confirmation of {} ...".format(resp[0])) transfer() def close(self): """ Método para fechar o programa """ self.fileTransfer.close() self.__window.destroy() quit() def getWindow(self): return self.__window def setAddress(self,ip,port): self.__address = (ip,port) def setMode(self,mode,button=None): # Altera o modo de transferência if mode.lower() == "client": mode = FileTransfer.CLIENT elif mode.lower() == "host": mode = FileTransfer.HOST else: raise TypeError self.__mode = mode # Essa parte está relacionada à interface para inserir o endereço # e o modo de transferência. O estilo de botão será alterado adequamente. if button: if mode == FileTransfer.CLIENT: self.clientButton.config(style="SELECTED.TButton") self.hostButton.config(style="TButton") else: self.clientButton.config(style="TButton") self.hostButton.config(style="SELECTED.TButton")
def __init__(self): self.mainList = [] self.sublist = [ "Serial Number", "Item Name", "Price", "Quantity", "Total Price" ] self.serial = 1 self.row = 0 self.window = Toplevel() self.window.geometry("1200x800") #for background color self.window.config(bg="lightcyan", highlightthickness=8, highlightbackground="navy", highlightcolor="navy") self.window.title("ADD TO CART") self.date = datetime.now() self.datetime = str(self.date).split(" ") self.date = self.datetime[0] self.time = (self.datetime[1]).split(".") self.time = self.time[0] print("DATE:" + self.date) print("TIME:", self.time) print("DATETIME AFTER SPLIT:", self.datetime) self.dateLabel = Label(self.window, text=self.date) self.timeLabel = Label(self.window, text=self.time) self.dateLabel.grid(row=0, column=2) self.timeLabel.grid(row=0, column=3) self.addMenuItem() self.quantity() #label color self.slctname = Label(self.window, text="SELECT NAME", bg="lightcyan", fg="red", font=("Harlow Solid Italic", 40, "italic", "bold")) self.combobox1 = Combobox(self.window, value=self.combobox1, state="readonly") self.slctquantity = Label(self.window, text="SELECT QUANTITY") self.combobox2 = Combobox(self.window, value=self.menuQuantity, state="readonly") self.addbttn = Button(self.window, text="ADD TO CART", command=self.addCart) self.slctname.grid(row=1, column=0, padx=10, pady=10) self.combobox1.grid(row=1, column=1, padx=10, pady=10) self.slctquantity.grid(row=1, column=2, padx=10, pady=10) self.combobox2.grid(row=1, column=3, padx=10, pady=10) self.addbttn.grid(row=1, column=4, padx=10, pady=10) self.treeview = Treeview(self.window, column=("SerialNum", "MenuName", "Price", "Qantity", "TotalPrice")) self.treeview.heading("SerialNum", text="SERIAL NUMBER") self.treeview.heading("MenuName", text="MENU NAME") self.treeview.heading("Price", text="PRICE") self.treeview.heading("Qantity", text="QUANTITY") self.treeview.heading("TotalPrice", text="TOTAL PRICE") self.treeview["show"] = "headings" # scroll = Scrollbar(self.window, orient="vertical", command=self.treeview.yview) # # scroll.pack(pady=20, side=RIGHT, fill=Y) # self.treeview.configure(yscrollcommand=scroll.set) #for table color style = Style() style.configure("Treeview.Heading", font=("Script MT Bold", 16)) style.configure("Treeview", font=("calibri", 13)) self.treeview.grid(row=3, column=0, columnspan=7) self.totalAmnt = Label(self.window, text="TOTAL AMOUNT:", bg="lightcyan", fg="red", font=("Harlow Solid Italic", 40, "italic", "bold")) self.gst = Label(self.window, text="GST:", bg="lightcyan", fg="red", font=("Harlow Solid Italic", 40, "italic", "bold")) self.netAmnt = Label(self.window, text="NET AMOUNT:", bg="lightcyan", fg="red", font=("Harlow Solid Italic", 40, "italic", "bold")) self.totalAmtVar = "" self.gstAmtVar = "" self.netAmtVar = "" self.totalAmnt.grid(row=7, column=0) self.gst.grid(row=8, column=0) self.netAmnt.grid(row=9, column=0) self.typeofordr = Label(self.window, text="TYPE OF ORDER", bg="lightcyan", fg="red", font=("Harlow Solid Italic", 40, "italic", "bold")) self.adress = Label(self.window, text="ADDRESS", bg="lightcyan", fg="red", font=("Harlow Solid Italic", 40, "italic", "bold")) self.paymntmode = Label(self.window, text="MODE OF PAYMENT", bg="lightcyan", fg="red", font=("Harlow Solid Italic", 40, "italic", "bold")) self.cashcllectd = Label(self.window, text="CASH COLLECTED", bg="lightcyan", fg="red", font=("Harlow Solid Italic", 40, "italic", "bold")) self.retrnd = Label(self.window, text="CASH RETURNED", bg="lightcyan", fg="red", font=("Harlow Solid Italic", 40, "italic", "bold")) self.mobile = Label(self.window, text="MOBILE NUMBER", bg="lightcyan", fg="red", font=("Harlow Solid Italic", 40, "italic", "bold")) self.combobox3 = Combobox( self.window, value=["TAKE AWAY", "DINE IN", "HOME DELIVERY"], state="readonly") self.addrssbox = Entry(self.window) self.combobox4 = Combobox(self.window, value=["CASH", "CREDIT CARD", "PAYTM"], state="readonly") self.cashcollctedbox = Entry(self.window) self.retrndbox = Entry(self.window) self.mobilebox = Entry(self.window) self.typeofordr.grid(row=7, column=2) self.adress.grid(row=8, column=2) self.paymntmode.grid(row=9, column=2) self.cashcllectd.grid(row=10, column=2) self.retrnd.grid(row=11, column=2) self.mobile.grid(row=12, column=2) self.combobox3.grid(row=7, column=3) self.addrssbox.grid(row=8, column=3) self.combobox4.grid(row=9, column=3) self.cashcollctedbox.grid(row=10, column=3) self.retrndbox.grid(row=11, column=3) self.mobilebox.grid(row=12, column=3) self.genratbttn = Button(self.window, text="GENERATE EXCEL", command=self.generateexcel) self.genratbill = Button(self.window, text="GENERATE BILL", command=self.generateBill) self.genratbttn.grid(row=13, column=0) self.genratbill.grid(row=13, column=1) self.window.mainloop() # obj =addtocart()
class ServiceGroup(Frame): log = logController NameGroup = StringVar DelayTime = 1 lbServiceGroupName = Label progressBarProcessing = Progressbar progressBarStyle = Style progressNumber = DoubleVar btStarGroup = Button imagebtStarGroup = PhotoImage btStopGroup = Button imagebtStopGroup = PhotoImage linhaDeSeparacao = PanedWindow OrganizerButtons = PanedWindow StyleServiceGroup = StylesInterface def __init__(self, *args, **kw): Frame.__init__(self, *args, **kw) self.NameGroup = StringVar() self.log = logController() def SetInformationGroup(self, name="", delay=0): self.NameGroup.set(name) self.DelayTime = delay def resource_path(self, relative_path): try: base_path = sys._MEIPASS except Exception: base_path = os.path.abspath("./icons") return os.path.join(base_path, relative_path) def AtuServices(self): serviceTool = win32.lib.win32serviceutil for service in self.winfo_children(): if ('service' in service._name): StringMen = 'Atualizando Status do Serviço... ' + service.ServiceName self.log.consoleLogAdd(StringMen) Status = self.StringStatus( serviceTool.QueryServiceStatus(service.ServiceName)[1]) service.atuStatus(service.ServiceNameDisplay + "\n" + Status, Status) #Retorna a string de cada status do serviço def StringStatus(self, nService=0): if (nService == 1): return "STOPPED" elif (nService == 2): return "START PENDING" elif (nService == 3): return "STOP PENDING" elif (nService == 4): return "RUNNING" elif (nService == 5): return "CONTINUE PENDING" elif (nService == 6): return "PAUSE PENDING" elif (nService == 7): return "PAUSED" def ConfigComponents(self, NumberOfServices=0): self.lbServiceGroupName = Label(self) self.lbServiceGroupName["bg"] = "#616161" self.lbServiceGroupName["textvariable"] = self.NameGroup self.lbServiceGroupName["font"] = "Roboto 20" self.lbServiceGroupName["fg"] = "white" self.lbServiceGroupName.pack(pady=5) self.progressNumber = DoubleVar() self.progressBarStyle = Style() self.progressBarStyle.theme_use('clam') self.progressBarStyle.configure("Horizontal.TProgressbar", troughcolor='#616161', background="#34A853", lightcolor='#34A853', darkcolor="#34A853") self.progressBarProcessing = Progressbar( self, style="Horizontal.TProgressbar", variable=self.progressNumber, maximum=NumberOfServices) self.progressBarProcessing.pack(fill=X, padx=10, pady=10) self.OrganizerButtons = PanedWindow(self) self.OrganizerButtons["height"] = 80 self.OrganizerButtons["bg"] = "#616161" self.OrganizerButtons.pack(fill=X, padx=10) self.btStarGroup = Button(self.OrganizerButtons, command=self.StartGroup) self.btStarGroup["bg"] = "#616161" self.btStarGroup["bd"] = 0 self.btStarGroup["command"] = self.StartGroup self.imagebtStarGroup = PhotoImage( file=self.resource_path("btStartGroupIcon.png")) self.btStarGroup.config(image=self.imagebtStarGroup) self.btStarGroup.pack(fill=X, side=LEFT, padx=10) self.btStopGroup = Button(self.OrganizerButtons, command=self.StopGroup) self.btStopGroup["bg"] = "#616161" self.btStopGroup["bd"] = 0 self.btStopGroup["command"] = self.StopGroup self.imagebtStopGroup = PhotoImage( file=self.resource_path("btStopGroupIcon.png")) self.btStopGroup.config(image=self.imagebtStopGroup) self.btStopGroup.pack(fill=X, side=LEFT, padx=5) self.linhaDeSeparacao = PanedWindow(self) self.linhaDeSeparacao["height"] = 2 self.linhaDeSeparacao["bg"] = "#9E9E9E" self.linhaDeSeparacao.pack(fill=X, padx=20, pady=5) def StartGroup(self): taskStartServices = Thread(target=self.OptionRunGroup, args=[1]) taskStartServices.start() def StopGroup(self): taskStopServices = Thread(target=self.OptionRunGroup, args=[2]) taskStopServices.start() def OptionRunGroup(self, Tipo=0): self.progressNumber.set(0) for service in self.winfo_children(): if ('service' in service._name): if (Tipo == 1): service.StartService() updProgress = Thread(target=self.updateProgress, args=[]) updProgress.start() sleep(self.DelayTime) if (Tipo == 2): service.StopService() updProgress = Thread(target=self.updateProgress, args=[]) updProgress.start() sleep(self.DelayTime) self.progressNumber.set(0) def updateProgress(self): self.progressNumber.set(self.progressNumber.get() + 1)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent # self.quote = "I was supposed to be a cool quote . But then internet abandoned me !" # self.author = "Alisha" self.getQuote() self.initUI() def initUI(self): self.parent.title("Wola!!! I automate") self.style = Style() self.style.theme_use("alt") # Styling self.style.configure('.', font=('Helvetica', 12), background="#300A24") self.style.configure( "PW.TLabel", foreground="#fff", background="#300A24", padding=20, justify=CENTER, wraplength="350") self.style.configure( "Medium.TButton", foreground="#300A24", background="#fff", borderwidth=0, padding=8, font=('Helvetica', 9)) # Styling Ends quoteLabel = Label(self, text=self.quote, style="PW.TLabel") quoteLabel.pack() authorLabel = Label(self, text=self.author, style="PW.TLabel") authorLabel.pack() self.pack(fill=BOTH, expand=True) closeButton = Button(self, text="Close This", style="Medium.TButton", command=self.parent.quit) closeButton.pack(side=RIGHT) okButton = Button( self, text="GitHub", style="Medium.TButton", command=self.btnOneFn) okButton.pack(side=RIGHT) okButton = Button(self, text="JStack", style="Medium.TButton", command=self.btnTwoFn) okButton.pack(side=RIGHT) okButton = Button(self, text="Python", style="Medium.TButton", command=self.btnThreeFn) okButton.pack(side=RIGHT) def hello(self): print("Print Hello") def getQuote(self): j = json.loads(requests.get( "http://quotes.stormconsultancy.co.uk/random.json").text) self.quote = j["quote"] self.author = j["author"] def btnOneFn(self): subprocess.Popen( ['firefox', "https://www.github.com"]) subprocess.Popen( ['gnome-terminal'], cwd=r'/mnt/864A162B4A16190F/git/portfolio') def btnTwoFn(self): subprocess.Popen( ['nautilus', "/mnt/864A162B4A16190F/git/JStack"]) subprocess.Popen( ['gnome-terminal'], cwd=r'/mnt/864A162B4A16190F/git/JStack') def btnThreeFn(self): subprocess.Popen( ['nautilus', "/mnt/864A162B4A16190F/git/Python"]) subprocess.Popen( ['gnome-terminal'], cwd=r'/mnt/864A162B4A16190F/git/Python')
def __init__(self, master,title=None,args=None): self.master = master self.args = args self.name = title master.title("Startup interface for %s" % title) self.arguments = dict() style = Style() style.configure(".",background="lightgrey") labelStyle = Style() labelStyle.configure("TLabel", background="lightgrey") buttonStyle = Style() buttonStyle.configure("TButton", background = "lightgrey") chkbuttonStyle = Style() chkbuttonStyle.configure("TCheckbutton", background = "lightgrey") rbuttonStyle = Style() rbuttonStyle.configure("TRadiobutton", background = "lightgrey") row = 0 self.blastLabel = Label(master, text = "Blast/Diamond output file") self.blastLabel.grid(row=row,column=0, sticky=W, padx=3) self.blastFile = StringVar() if self.args.b: self.blastFile.set(self.args.b) self.blastEntry = Entry(master, width = WIDTH, textvariable = self.blastFile) self.blastEntry.grid(row=row,column=1, padx=3) self.blastSelect = Button(master, text = "Select", command = lambda: self.openFile(var=self.blastFile)) self.blastSelect.grid(row=row,column=2, sticky=W, padx=3) self.optionLabel2 = Label(master, text = "required") self.optionLabel2.grid(row=row,column=3,sticky=W, padx=3) CreateToolTip(self.blastEntry,"Sequence similarity file produced by BLAST or DIAMOND.\nUses specific format (see README).") row += 1 self.networkLabel = Label(master, text = "Genome to gene file") self.networkLabel.grid(row=row,column=0, sticky=W, padx=3) self.networkFile = StringVar() if self.args.g: self.networkFile.set(self.args.g) self.networkEntry = Entry(master, width = WIDTH, textvariable = self.networkFile) self.networkEntry.grid(row=row,column=1, padx=3) self.networkSelect = Button(master, text = "Select", command = lambda: self.openFile(var=self.networkFile)) self.networkSelect.grid(row=row,column=2, sticky=W, padx=3) self.optionLabel2 = Label(master, text = "required") self.optionLabel2.grid(row=row,column=3,sticky=W, padx=3) CreateToolTip(self.networkEntry,"Input bipartite graph edge file (Tab-separated).\nCheck for the ordering of the items on each line:\nGenome first, then sequence ID.") row += 1 self.annotLabel = Label(master, text = "Annotation file") self.annotLabel.grid(row=row,column=0, sticky=W, padx=3) self.a = StringVar() if self.args.a: self.a.set(self.args.a) self.annotEntry = Entry(master, width = WIDTH, textvariable = self.a) self.annotEntry.grid(row=row,column=1, padx=3) self.annotSelect = Button(master, text = "Select", command = lambda: self.openAnnotFile(var=self.a)) self.annotSelect.grid(row=row,column=2, sticky=W, padx=3) self.optionLabel2 = Label(master, text = "recommended") self.optionLabel2.grid(row=row,column=3,sticky=W, padx=3) CreateToolTip(self.annotEntry,"Common annotation file for genomes and genes.\nTab-delimited, compulsory header with attribute names.\nSpecify empty annotations with '-'.") row += 1 self.k = StringVar() if self.a.get(): with open(self.a.get(),'r') as ANNOT: keyList = ANNOT.readline().strip().split("\t")[1:] #print(keyList) keyList.sort() keyString = ",".join(keyList) self.optionLabel = Label(master, text = "Annotation keys") self.optionLabel.grid(row=row,column=0, sticky=W, padx=3) self.k = StringVar() self.k.set(keyString) self.optionEntry = Entry(master, width = WIDTH, textvariable = self.k) self.optionEntry.grid(row=row,column=1, padx=3) self.optionLabel2 = Label(master, text = "comma-separated") self.optionLabel2.grid(row=row,column=3,sticky=W, padx=3) CreateToolTip(self.optionEntry,"List of available attributes in file %s.\nIf you wish to remove some, click on line and edit." % self.args.a) row += 1 self.optionLabel = Label(master, text = "Identity threshold(s)") self.optionLabel.grid(row=row,column=0, sticky=W, padx=3) self.n = StringVar() if self.args.n: self.n.set(self.args.n) self.optionEntry = Entry(master, width = WIDTH, textvariable = self.n) self.optionEntry.grid(row=row,column=1, padx=3) self.optionLabel2 = Label(master, text = "comma-separated") self.optionLabel2.grid(row=row,column=3,sticky=W, padx=3) CreateToolTip(self.optionEntry,"List of thresholds considered.\nOne subdirectory will be created for each value.") row += 1 self.optionLabel = Label(master, text = "Mutual cover") self.optionLabel.grid(row=row,column=0, sticky=W, padx=3) self.c = StringVar() if self.args.c: self.c.set(self.args.c) self.optionEntry = Entry(master, width = WIDTH, textvariable = self.c) self.optionEntry.grid(row=row,column=1, sticky=W, padx=3) CreateToolTip(self.optionEntry,"Set new value for minimum mutual cover for sequence similarity.") row += 1 self.optionLabel = Label(master, text = "Clustering method") self.optionLabel.grid(row=row,column=0, sticky=W, padx=3) option_list = ["cc","families"] self.C = StringVar() self.C.set(option_list[0]) self.optionEntry = Combobox(master, width = 10, textvariable = self.C) self.optionEntry['values'] = option_list self.optionEntry.grid(row=row,column=1,sticky=W, padx=3) CreateToolTip(self.optionEntry,"""Select method for the definition of gene families.\ncc = connected components of sequence similarity network.\nfamilies = communities produced by the "Louvain" multilevel algorithm.""") row += 1 self.optionLabel = Label(master, text = "Input network") self.optionLabel.grid(row=row,column=0, sticky=W, padx=3) self.I = StringVar() if self.args.I: self.I.set(self.args.I) self.optionEntry = Entry(master, width = WIDTH, textvariable = self.I) self.optionEntry.grid(row=row,column=1, padx=3) self.optionSelect = Button(master, text = "Select", command = lambda: self.openFile(var=self.I)) self.optionSelect.grid(row=row,column=2, sticky=W, padx=3) self.optionLabel2 = Label(master, text = "optional") self.optionLabel2.grid(row=row,column=3,sticky=W, padx=3) CreateToolTip(self.optionEntry,"Supply directly sequence similarity network.\nSkips use of cleanblast on the blast file output.") row += 1 self.optionLabel = Label(master, text = "Fasta file") self.optionLabel.grid(row=row,column=0, sticky=W, padx=3) self.f = StringVar() if self.args.f: self.f.set(self.args.f) self.optionEntry = Entry(master, width = WIDTH, textvariable = self.f) self.optionEntry.grid(row=row,column=1, padx=3) self.optionSelect = Button(master, text = "Select", command = lambda: self.openFile(var=self.f)) self.optionSelect.grid(row=row,column=2, sticky=W, padx=3) self.optionLabel2 = Label(master, text = "optional") self.optionLabel2.grid(row=row,column=3,sticky=W, padx=3) CreateToolTip(self.optionEntry,"Supply fasta file for the protein sequences.\nAdds sequence similarity detection step.\nWARNING: this could take a long time.") row += 1 self.optionLabel = Label(master, text = "Similarity search software") self.optionLabel.grid(row=row,column=0, sticky=W, padx=3) option_list = ["Blast","Diamond"] self.A = StringVar() self.A.set(option_list[0]) self.optionEntry = Combobox(master, width =10, textvariable = self.A) self.optionEntry['values'] = option_list self.optionEntry.grid(row=row,column=1,sticky=W, padx=3) self.optionLabel2 = Label(master, text = "optional (requires fasta file)") self.optionLabel2.grid(row=row,column=3,sticky=W, padx=3) CreateToolTip(self.optionEntry,"Selects sequence similarity detection software.\nSilently ignored if no fasta file is given.") row += 1 self.optionLabel = Label(master, text = "Unique node identifier") self.optionLabel.grid(row=row,column=0, sticky=W, padx=3) self.i = StringVar() if self.args.i: self.i.set(self.args.i) self.optionEntry = Entry(master, width = WIDTH, textvariable = self.i) self.optionEntry.grid(row=row,column=1, padx=3) CreateToolTip(self.optionEntry,"""Name of first column in %s file.\nCheck that the items in this column match the node IDs in the ROOT graph.""" % self.args.a) row += 1 self.optionLabel = Label(master, text = "Graphic interface for Description") self.optionLabel.grid(row=row,column=0, sticky=W, padx=3) self.K = BooleanVar() self.K.set(self.args.K) self.chk = Checkbutton(master, text="Display?", var = self.K) self.chk.grid (row=row,column=1,padx=3,sticky=W) CreateToolTip(self.chk,"Displays graphic customization interface for the last description.py step.\nIf not selected, displays all attributes for all key types and all trail levels.") row += 1 column = 0 self.outDirLabel = Label(master, text = "Output directory") self.outDirLabel.grid(row=row,column=column, sticky=W, padx=3) self.outDir = StringVar() if self.args.D: self.outDir.set(self.args.D) else: self.outDir.set('') self.outDirEntry = Entry(master, width = WIDTH, textvariable = self.outDir) column += 1 self.outDirEntry.grid(row=row,column=column, padx=3) self.optionLabel2 = Label(master, text = "optional") column += 2 self.optionLabel2.grid(row=row,column=column,sticky=W, padx=3) # tip helpText8 = "Storage directory for output files." self.outDirTip = CreateToolTip(self.outDirEntry, helpText8) # row += 1 self.optionLabel = Label(master, text = "Log file") self.optionLabel.grid(row=row,column=0, sticky=W, padx=3) self.l = StringVar() try: log = self.args.l.name.strip("(<,>") except: log = log self.l.set(log) self.optionEntry = Entry(master, width = WIDTH, textvariable = self.l) self.optionEntry.grid(row=row,column=1, padx=3) row += 2 cbFrame = Frame(master) # create subframe for command buttons self.run_button = Button(cbFrame, text="Run", command=self.run) self.run_button.grid(row=row,column=0,padx=12) self.close_button = Button(cbFrame, text="Close", command=self.Quit) self.close_button.grid(row=row,column=1,padx=12) cbFrame.grid(row=row,column=1,columnspan=2,sticky=E+W) helpText = bitwin.processArgs().format_help() self.helpbutton = Button(master, text="Help", command = lambda: HelpWindow(text=helpText,name=self.name)) self.helpbutton.grid(row=row,column=2,sticky=W,padx=3)
class NotebookDemo: def __init__(self, fr): self.fr = fr self.st0 = Style() self.style = ts.ThemedStyle() # Style() self._create_demo_panel() # run this before allBtns self.allBtns = self.ttkbut + self.cbs[1:] + self.rb def _create_demo_panel(self): demoPanel = Frame(self.fr, name="demo") demoPanel.pack(side='top', fill='both', expand='y') # create the notebook self.nb = nb = Notebook(demoPanel, name="nb") # extend bindings to top level window allowing # CTRL+TAB - cycles thru tabs # SHIFT+CTRL+TAB - previous tab # ALT+K - select tab using mnemonic (K = underlined letter) nb.enable_traversal() nb.bind("<<NotebookTabChanged>>", self._on_tab_changed) nb.pack(fill='both', expand='y', padx=2, pady=3) self._create_descrip_tab(nb) self._create_treeview_tab(nb) self._create_text_tab(nb) def _create_descrip_tab(self, nb): # frame to hold contents frame = Frame(nb, name='descrip') # widgets to be displayed on 'Description' tab # position and set resize behaviour frame.rowconfigure(1, weight=1) frame.columnconfigure((0, 1), weight=1, uniform=1) lf = LabelFrame(frame, text='Animals') lf.pack(pady=2, side='left', fill='y') themes = [ 'cat', 'dog', 'horse', 'elephant', 'crocodile', 'bat', 'grouse\nextra line made longer' ] self.ttkbut = [] for t in themes: b = Button(lf, text=t) b.pack(pady=2) self.ttkbut.append(b) lF2 = LabelFrame(frame, text="Theme Combobox") lF2.pack(anchor='nw') themes = list(sorted(self.style.get_themes())) themes.insert(0, "Pick a theme") self.cb = cb = Combobox(lF2, values=themes, state="readonly", height=10) cb.set(themes[0]) cb.bind('<<ComboboxSelected>>', self.change_style) cb.grid(row=0, column=0, sticky='nw', pady=5) lF3 = LabelFrame(frame, text="Entry") lF3.pack(anchor='ne') self.en = Entry(lF3) self.en.grid(row=0, column=0, sticky='ew', pady=5, padx=5) lf1 = LabelFrame(frame, text='Checkbuttons') lf1.pack(pady=2, side='left', fill='y') # control variables self.enabled = IntVar() self.cheese = IntVar() self.tomato = IntVar() self.basil = IntVar() self.oregano = IntVar() # checkbuttons self.cbOpt = Checkbutton(lf1, text='Enabled', variable=self.enabled, command=self._toggle_opt) cbCheese = Checkbutton(text='Cheese', variable=self.cheese, command=self._show_vars) cbTomato = Checkbutton(text='Tomato', variable=self.tomato, command=self._show_vars) sep1 = Separator(orient='h') cbBasil = Checkbutton(text='Basil', variable=self.basil, command=self._show_vars) cbOregano = Checkbutton(text='Oregano', variable=self.oregano, command=self._show_vars) sep2 = Separator(orient='h') self.cbs = [ self.cbOpt, sep1, cbCheese, cbTomato, sep2, cbBasil, cbOregano ] for opt in self.cbs: if opt.winfo_class() == 'TCheckbutton': opt.configure(onvalue=1, offvalue=0) opt.setvar(opt.cget('variable'), 0) opt.pack(in_=lf1, side='top', fill='x', pady=2, padx=5, anchor='nw') lf2 = LabelFrame(frame, text='Radiobuttons', labelanchor='n') lf2.pack(pady=2, side='left', fill='y') self.rb = [] self.happiness = StringVar() for s in ['Great', 'Good', 'OK', 'Poor', 'Awful']: b = Radiobutton(lf2, text=s, value=s, variable=self.happiness, command=lambda s=s: self._show_vars()) b.pack(anchor='nw', side='top', fill='x', pady=2) self.rb.append(b) right = LabelFrame(frame, text='Control Variables') right.pack(pady=2, side='left', fill='y') self.vb0 = Label(right, font=('Courier', 10)) self.vb1 = Label(right, font=('Courier', 10)) self.vb2 = Label(right, font=('Courier', 10)) self.vb3 = Label(right, font=('Courier', 10)) self.vb4 = Label(right, font=('Courier', 10)) self.vb5 = Label(right, font=('Courier', 10)) self.vb0.pack(anchor='nw', pady=3) self.vb1.pack(anchor='nw', pady=3) self.vb2.pack(anchor='nw', pady=3) self.vb3.pack(anchor='nw', pady=3) self.vb4.pack(anchor='nw', pady=3) self.vb5.pack(anchor='nw', pady=3) self._show_vars() # add to notebook (underline = index for short-cut character) nb.add(frame, text='Description', underline=0, padding=2) # ========================================================================= def _create_treeview_tab(self, nb): # Populate the second pane. Note that the content doesn't really matter # tree = None self.backg = ["white", '#f0f0ff'] tree_columns = ("country", "capital", "currency") tree_data = [("Argentina", "Buenos Aires", "ARS"), ("Australia", "Canberra", "AUD"), ("Brazil", "Brazilia", "BRL"), ("Canada", "Ottawa", "CAD"), ("China", "Beijing", "CNY"), ("France", "Paris", "EUR"), ("Germany", "Berlin", "EUR"), ("India", "New Delhi", "INR"), ("Italy", "Rome", "EUR"), ("Japan", "Tokyo", "JPY"), ("Mexico", "Mexico City", "MXN"), ("Russia", "Moscow", "RUB"), ("South Africa", "Pretoria", "ZAR"), ("United Kingdom", "London", "GBP"), ("United States", "Washington, D.C.", "USD")] #test_length = font.Font(family="Times", size=12, weight="bold").measure('Test') #fact = int(test_length / 30 * 20.45) # 30 is the length of Test in Idle fact = font.Font(font="TkDefaultFont").metrics('linespace') self.st0.configure('fact.Treeview', rowheight=fact, font=font.nametofont("TkDefaultFont")) container = Frame(nb) container.grid(sticky='nsew') #(fill='both', expand=True) self.tree = Treeview(container, columns=tree_columns, show="headings", style='fact.Treeview') vsb = Scrollbar(container, orient="vertical", command=self.tree.yview) hsb = Scrollbar(container, orient="horizontal", command=self.tree.xview) self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set) self.tree.grid(column=0, row=0, sticky='nsew', in_=container) vsb.grid(column=1, row=0, sticky='ns', in_=container) hsb.grid(column=0, row=1, sticky='ew', in_=container) container.grid_columnconfigure(0, weight=1) container.grid_rowconfigure(0, weight=1) for col in tree_columns: self.tree.heading( col, text=col.title(), command=lambda c=col: self.sortby(self.tree, c, 0)) # XXX tkFont.Font().measure expected args are incorrect according # to the Tk docs self.tree.column(col, width=Font().measure(col.title()), stretch=False) for ix, item in enumerate(tree_data): itemID = self.tree.insert('', 'end', values=item) self.tree.item(itemID, tags=itemID) self.tree.tag_configure(itemID, background=self.backg[ix % 2]) # adjust columns lengths if necessary for indx, val in enumerate(item): ilen = Font().measure(val) if self.tree.column(tree_columns[indx], width=None) < ilen: self.tree.column(tree_columns[indx], width=ilen) sg = Sizegrip(container) sg.grid(sticky='e') nb.add(container, text='Treeview', underline=0, padding=2) # ========================================================================= def _create_text_tab(self, nb): # populate the third frame with other widgets self.pw = PanedWindow(nb, name='pw') self.pw.pack(fill='both', expand=True) lF = LabelFrame(self.pw, text="Slider") fr1 = Frame(lF) fr1.grid(row=0, column=0) from_ = -5 to = 105 value = 19 step = 11 fontSize = 9 scvar = IntVar() #scRange=self.any_number_range(from_,to,step) #scLen = len(scRange[1]) * (fontSize + 10) self.sc = TtkScale(fr1, from_=from_, to=to, variable=scvar, orient='vertical', length=200, showvalue=True, command=lambda s: scvar.set('%d' % float(s)), tickinterval=5, resolution=5) #self.sc = Scale(fr1, from_=from_, to=to, variable=scvar, #orient='vertical',length=scLen, #command=lambda s: scvar.set('%d' % float(s) )) self.sc.set(value) #l1 = Label(fr1,textvariable=scvar,width=5) l1 = Spinbox(fr1, from_=from_, to=to, textvariable=scvar, width=4) l1.grid(row=0, column=0, pady=2) self.sc.grid(row=0, column=1, pady=5, padx=40) fr = Frame(fr1) fr.grid(row=0, column=2) #for ix,sR in enumerate(scRange[1]): #lb = Label(fr, text=sR, font=('Courier New', str(fontSize))) #lb.grid(row=ix, column=1) schvar = IntVar() a = -5 b = 105 #schRange = self.any_number_range(a,b,s=11) #schLen = Font().measure(schRange[0]) self.sch = TtkScale(lF, from_=a, to=b, length=200, variable=schvar, orient='horizontal', showvalue=True, command=lambda s: schvar.set('%d' % float(s)), tickinterval=5, resolution=5) #self.sch = Scale(lF, from_=a, to=b, length=schLen, variable=schvar, #orient='horizontal', #command=lambda s: schvar.set('%d' % float(s) )) self.sch.set(23) #l2 = Label(lF,textvariable=schvar) l2 = Spinbox(lF, from_=a, to=b, textvariable=schvar, width=4) l2.grid(row=1, column=1, pady=2) self.sch.grid(row=2, column=1, pady=40, padx=5, sticky='nw') #l3 = Label(lF,text=schRange[0], font=('Courier New', str(fontSize))) #l3.grid(row=3,column=1,pady=2) self.sch.bind("<ButtonRelease-1>", self.show_x) self.pw.add(lF) lF1 = LabelFrame(self.pw, text="Progress", name='lf') pb1var = IntVar() pb2var = IntVar() self.pbar = Progressbar(lF1, variable=pb1var, length=150, mode="indeterminate", name='pb1', orient='horizontal') self.pb2 = Progressbar(lF1, variable=pb2var, mode='indeterminate', name='pb2', orient='vertical') self.pbar["value"] = 25 self.pbar.grid(row=1, column=0, padx=5, pady=5, sticky='nw') self.pb2.grid(row=1, column=1, padx=5, pady=5, sticky='nw') l3 = Label(lF1, textvariable=pb1var) l3.grid(row=0, column=0, pady=2, sticky='nw') l4 = Label(lF1, textvariable=pb2var) l4.grid(row=0, column=1, pady=2, sticky='nw') start = Button(lF1, text='Start Progress', command=lambda: self._do_bars('start')) stop = Button(lF1, text='Stop Progress', command=lambda: self._do_bars('stop')) start.grid(row=2, column=0, padx=5, pady=5, sticky='nw') stop.grid(row=3, column=0, padx=5, pady=5, sticky='nw') self.pw.add(lF1) # add to notebook (underline = index for short-cut character) nb.add(self.pw, text='Sliders & Others', underline=0) #========================================================================= def _toggle_opt(self): # state of the option buttons controlled # by the state of the Option frame label widget if self.enabled.get() == 1: self.sc.state(['!disabled']) self.sch.state(['!disabled']) self.cb.state(['!disabled']) self.en.state(['!disabled']) self.pbar.state(['!disabled']) self.pb2.state(['!disabled']) else: self.sc.state(['disabled']) self.sch.state(['disabled']) self.cb.state(['disabled']) self.en.state(['disabled']) self.pbar.state(['disabled']) self.pb2.state(['disabled']) for opt in self.allBtns: if opt.winfo_class() != 'TSeparator': if self.cbOpt.instate(('selected', )): opt['state'] = '!disabled' # enable option self.nb.tab(1, state='normal') else: opt['state'] = 'disabled' self.nb.tab(1, state='disabled') self._show_vars() def _show_vars(self): # set text for labels in var_panel to include the control # variable name and current variable value self.vb0['text'] = '{:<11} {:<8}'.format('enabled:', self.enabled.get()) self.vb1['text'] = '{:<11} {:<8}'.format('cheese:', self.cheese.get()) self.vb2['text'] = '{:<11} {:<8}'.format('tomato:', self.tomato.get()) self.vb3['text'] = '{:<11} {:<8}'.format('basil:', self.basil.get()) self.vb4['text'] = '{:<11} {:<8}'.format('oregano:', self.oregano.get()) self.vb5['text'] = '{:<11} {:<8}'.format('happiness:', self.happiness.get()) def sortby(self, tree, col, descending): """Sort tree contents when a column is clicked on.""" # grab values to sort data = [(tree.set(child, col), child) for child in tree.get_children('')] # reorder data data.sort(reverse=descending) for indx, item in enumerate(data): tree.move(item[1], '', indx) # switch the heading so that it will sort in the opposite direction tree.heading(col, command=lambda col=col: self.sortby( tree, col, int(not descending))) # reconfigure tags after ordering list_of_items = tree.get_children('') for i in range(len(list_of_items)): tree.tag_configure(list_of_items[i], background=self.backg[i % 2]) def any_number_range(self, a, b, s=1): """ Generate consecutive values list between two numbers with optional step (default=1).""" if (a == b): return a else: mx = max(a, b) mn = min(a, b) result = [] output = '' # inclusive upper limit. If not needed, delete '+1' in the line #below while (mn < mx + 1): # if step is positive we go from min to max if s > 0: result.append(mn) mn += s # if step is negative we go from max to min if s < 0: result.append(mx) mx += s # val maxLen = 0 output = "" for ix, res in enumerate(result[:-1]): # last value ignored if len(str(res)) > maxLen: maxLen = len(str(res)) if maxLen == 1: # converts list to string output = ' '.join(str(i) for i in result) else: for ix, res in enumerate(result): if maxLen == 2: if len(str(res)) == 1: output = output + str(res) + " " * maxLen elif len(str(res)) == 2: output = output + str(res) + " " else: output = output + str(res) return output, result def _do_bars(self, op): pbar = self.pbar.nametowidget('.fr.demo.nb.pw.lf.pb1') pb2 = self.pb2.nametowidget('.fr.demo.nb.pw.lf.pb2') if op == 'start': pbar.start() pb2.start() else: pbar.stop() pb2.stop() def change_style(self, event=None): """set the Style to the content of the Combobox""" content = self.cb.get() try: self.style.theme_use(content) fact = font.Font(font="TkDefaultFont").metrics('linespace') self.st0.configure('font.Treeview', rowheight=fact, font=font.nametofont("TkDefaultFont")) except TclError as err: messagebox.showerror('Error', err) else: root.title(content) def change_theme(self, theme): window = ttktheme.ThemedTk() window.set_theme(theme) root.title(theme) def _on_tab_changed(self, event): event.widget.update_idletasks() tab = event.widget.nametowidget(event.widget.select()) event.widget.configure(height=tab.winfo_reqheight(), width=tab.winfo_reqwidth())
to_val = 255 tick_val = 10 dig_val = 2 res_val = 5 or_val = 'vertical' if or_val == 'horizontal': style_val = 'my.Horizontal.TScale' root.geometry(str(len_val + 200) + "x200+500+500") else: style_val = 'my.Vertical.TScale' root.geometry("200x" + str(len_val + 200) + "+500+300") style = Style() style.theme_use('default') style.configure(style_val) fr = Frame(root) fr.pack(fill='y') ttks = TtkScale(fr, from_=from_val, to=to_val, orient=or_val, tickinterval=tick_val, digits=dig_val, style=style_val, resolution=res_val) if or_val == 'horizontal': ttks.pack(fill='x', pady=40, padx=5) else:
def __init__(self, parent, XML=None): # initialize frame Frame.__init__(self, parent) style = Style() style.configure(".", background="lightgrey") labelStyle = Style() labelStyle.configure("TLabel", background="lightgrey") buttonStyle = Style() buttonStyle.configure("TButton", background="lightgrey") chkbuttonStyle = Style() chkbuttonStyle.configure("TCheckbutton", background="lightgrey") rbuttonStyle = Style() rbuttonStyle.configure("TRadiobutton", background="lightgrey") self.XML = XML self.returnValue = None # set root as parent self.parent = parent # read and parse XML document self.DOMTree = ET.parse(self.XML) # create attribute for XML document self.xmlDocument = self.DOMTree.getroot() # create attribute for root directory self.RootDir = getElementValue(self.xmlDocument, "root") # create attribute for "mod" elements self.xmlModList = getElement(self.xmlDocument, "mod") # create attribute for "trail" elements self.xmlTrailList = getElement(self.xmlDocument, "trail") # create attribute for "attr" elements self.xmlAttrList = getElement(self.xmlDocument, "attr") # identify node types self.nodeTypes = [] attr = self.xmlAttrList[0] for KEY in getElement(attr, "node"): nT = int(KEY.attrib['type']) self.nodeTypes.append(nT) # Module setting self.xmlMod = self.xmlModList[0] self.mod = xmlModule(self.xmlMod) self.mod.KEYS = dict() for KEY in getElement(self.xmlMod, "key"): nT = int(KEY.attrib['type']) self.mod.KEYS[nT] = KEY # Trails setting self.trails = dict() for trail in self.xmlTrailList: rank = int(getElementValue(trail, "rank")) self.trails[rank] = xmlTrail(trail) self.trails[rank].KEYS = dict() for KEY in getElement(trail, "key"): nT = int(KEY.attrib['type']) self.trails[rank].KEYS[nT] = KEY #Attributes setting self.attrs = dict() for attr in self.xmlAttrList: name = getElementValue(attr, "name") self.attrs[name] = Attr(attr) self.attrs[name].KEYS = dict() for KEY in getElement(attr, "node"): nT = int(KEY.attrib['type']) self.attrs[name].KEYS[nT] = KEY self.M = len(self.xmlModList) self.T = len(self.xmlTrailList) self.A = len(self.xmlAttrList) self.K = len(self.nodeTypes) print( """%s displays %d module(s), %d trail file(s) and %d node attribute(s). The graph is %d-partite.""" % (self.XML, self.M, self.T, self.A, self.K)) # initialize UI self.initUI()
class link_dl: def __init__(self, root): self.root = root self.styles = Style() self.main_layer() self.creating_titleAndbrand() self.creating_urlHolder() self.buttons_AudioVideo() def main_layer(self): self.root.title('Link DL') self.root.geometry('450x250') self.root.resizable(0, 0) def creating_titleAndbrand(self): self.label_title = ttk.Label(root, text='Link DL - Youtube Downloader', font=30) self.label_title.place(relx=0.31, rely=0.12) self.label_brand = ttk.Label(root, text='Coded under Nadomso') self.label_brand.place(relx=0.4, rely=0.9) def creating_urlHolder(self): self.label_url = ttk.Label(root, text='URL ') self.label_url.place(relx=0.1, rely=0.3) self.url_link = StringVar() self.entry_url = ttk.Entry(root, width=50, textvariable=self.url_link) self.entry_url.focus() self.entry_url.place(relx=0.2, rely=0.3) def buttons_AudioVideo(self): def audio_download(): if self.url_link.get() == '': messagebox.showinfo(message='URL can not be empty') else: dl_audio = YouTube(self.url_link.get()).streams get_audio = dl_audio.filter(type='audio') get_audio.first().download( output_path=tk.filedialog.askdirectory()) messagebox.showinfo(message='Download Complete') def video_download(): if self.url_link.get() == '': messagebox.showinfo(message='URL can not be empty') else: dl_video = YouTube(self.url_link.get()).streams.first() dl_video.download(output_path=tk.filedialog.askdirectory()) messagebox.showinfo(message='Download Complete') self.audio_button = ttk.Button(root, text='Audio', command=audio_download) self.video_button = ttk.Button(root, text='Video', command=video_download) self.audio_button.place(relx=0.25, rely=0.65) self.video_button.place(relx=0.55, rely=0.65) self.styles.configure('TButton', relief='flat', background='#fff', font=10, padding=2)
# colouring the ttk buttons from tkinter.ttk import Style from tkinter import Tk from tkinter import Button as origbutton from tkinter.ttk import Button as tilebutton root=Tk() s = Style() s.theme_use('default') s.configure('green.TButton', foreground='green') s.configure('red.green.TButton', background='red') origbutton(root,text='original').pack() tilebutton(root,text='ttk themed',style='green.TButton').pack() tilebutton(root,text='2nd ttk',style='red.green.TButton').pack() root.mainloop()
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()
class DefaultThemingEngine(AOSLibrary): def __init__(self, manager): super().__init__(manager) self.manager.registerConfig('theme') self.style = Style() self.style.configure("Tk", background="#000000", foreground="white") self.delayEnable = True def enable(self): self.manager.addTool('Edit Theme', self.themeList) self.loadTheme() def disable(self): self.manager.removeTool('Edit Theme') def themeList(self): self.themelistwin = Toplevel() Label(self.themelistwin, text="Log Window background:").grid(row=0, column=0) self.textbox_bg = Entry(self.themelistwin) self.textbox_bg.grid(row=0, column=1) self.textbox_bg.insert(0, self.manager.process.log.textbox['background']) Label(self.themelistwin, text="Log Window Font Colour:").grid(row=0, column=2) self.textbox_fg = Entry(self.themelistwin) self.textbox_fg.grid(row=0, column=3) self.textbox_fg.insert(0, self.manager.process.log.textbox['foreground']) Label(self.themelistwin, text="Buttons background:").grid(row=1, column=0) self.button_bg = Entry(self.themelistwin) self.button_bg.grid(row=1, column=1) self.button_bg.insert(0, self.style.lookup("TButton", "background")) Label(self.themelistwin, text="Buttons padding:").grid(row=2, column=0) self.button_fbg = Entry(self.themelistwin) self.button_fbg.grid(row=2, column=1) self.button_fbg.insert(0, self.style.lookup("TButton", "padding")) Label(self.themelistwin, text="Buttons foreground:").grid(row=3, column=0) self.button_fg = Entry(self.themelistwin) self.button_fg.grid(row=3, column=1) self.button_fg.insert(0, self.style.lookup("TButton", "foreground")) Label(self.themelistwin, text="Buttons relief:").grid(row=4, column=0) self.button_rf = Entry(self.themelistwin) self.button_rf.grid(row=4, column=1) self.button_rf.insert(0, self.style.lookup("TButton", "relief")) Button(self.themelistwin, text="Save", command=self.saveTheme).grid(row=10, column=0) self.themelistwin.bind('<Return>', lambda evt: self.saveTheme()) def saveTheme(self): self.manager.getConfig('theme')._set('theme_outputwin', self.textbox_bg.get()) self.manager.getConfig('theme')._set('theme_outputwin_font', self.textbox_fg.get()) self.manager.process.log.textbox.configure(bg=self.textbox_bg.get()) self.manager.process.log.textbox.configure(fg=self.textbox_fg.get()) self.style.configure("TButton", padding=self.button_fbg.get(), relief=self.button_rf.get(), background=self.button_bg.get(), foreground=self.button_fg.get()) data = { 'button': { 'padding': self.button_fbg.get(), 'relief': self.button_rf.get(), 'background': self.button_bg.get(), 'foreground': self.button_fg.get() } } self.manager.getConfig('theme')._set('theme', data) def loadTheme(self): tbb = self.manager.getConfig('theme').get( 'theme_outputwin', self.manager.process.log.textbox['background']) tbf = self.manager.getConfig('theme').get( 'theme_outputwin_font', self.manager.process.log.textbox['foreground']) self.manager.process.log.textbox.configure(bg=tbb) self.manager.process.log.textbox.configure(fg=tbf) data = self.manager.getConfig('theme').get('theme', {}) if data: theme_b = data.get('button', None) #print(theme_b) if theme_b: #print(theme_b.get('background')) self.style.configure( "TButton", padding=theme_b.get( 'padding', self.style.lookup("TButton", "padding")), relief=theme_b.get('relief', self.style.lookup("TButton", "relief")), background=theme_b.get( 'background', self.style.lookup("TButton", "background")), foreground=theme_b.get( 'foreground', self.style.lookup("TButton", "foreground")))
def __init__(self, master): Toplevel.__init__(self, master) self.protocol("WM_DELETE_WINDOW", self.quitter) self.columnconfigure(0, weight=1) self.columnconfigure(2, weight=1) self.rowconfigure(0, weight=1) self.title("Exclusions") self.transient(master) self.grab_set() self.last_path = "" # last opened path self.img_open = PhotoImage(file=IM_OPEN) self.img_doc = PhotoImage(file=IM_DOC) self.img_supp = PhotoImage(file=IM_SUPP) style = Style(self) style.configure("list.TFrame", background="white", relief="sunken") frame = Frame(self) frame.columnconfigure(0, weight=1) frame.rowconfigure(0, weight=1) frame.grid(row=0, columnspan=3, sticky="eswn", padx=10, pady=(10, 4)) listbox_frame = Frame(frame, borderwidth=1, style="list.TFrame") listbox_frame.columnconfigure(0, weight=1) listbox_frame.rowconfigure(0, weight=1) listbox_frame.grid(row=0, column=0, sticky="nswe") self.listvar = StringVar(self, value=CONFIG.get("Defaults", "exclude_supp")) self.exclude_list = split(r'(?<!\\) ', CONFIG.get("Defaults", "exclude_supp")) self.listbox = Listbox(listbox_frame, highlightthickness=0, listvariable=self.listvar) self.listbox.grid(sticky="eswn") scroll_x = Scrollbar(frame, orient="horizontal", command=self.listbox.xview) scroll_x.grid(row=1, column=0, sticky="ew") scroll_y = Scrollbar(frame, orient="vertical", command=self.listbox.yview) scroll_y.grid(row=0, column=1, sticky="ns") self.listbox.configure(xscrollcommand=scroll_x.set, yscrollcommand=scroll_y.set) Button(self, image=self.img_doc, command=self.add_doc).grid(row=1, column=0, sticky="e", padx=(10, 4), pady=(4, 10)) Button(self, image=self.img_open, command=self.add_dir).grid(row=1, column=1, padx=4, pady=(4, 10)) Button(self, image=self.img_supp, command=self.rem).grid(row=1, column=2, sticky="w", padx=(4, 10), pady=(4, 10)) self.geometry("500x400")
#coding:utf-8 from tkinter.ttk import Frame, Label, Button, Style style = Style() style.configure("RW.TLabel", foreground="red", background="white") class Application(Frame): def __init__(self, master=None): super().__init__(master) #窗口大小位置 self.master.geometry("600x400+100+400") #长x宽+x+y self.pack() self.createWidgets() def createWidgets(self): self.helloLabel = Label(self, text='Hello, world!') self.helloLabel.pack() self.quitButton = Button(self, text='Quit', style="RW.TLabel", command=self.quit) self.quitButton.pack() if __name__ == "__main__": app = Application() # 设置窗口标题: app.master.title('Hello World')
def Tree(fr0,csv_file,out_var,csv_delimiter=','): st1 = Style() st1.theme_use('default') st1.map('Treeview', foreground=fixed_map(st1,'foreground'), background=fixed_map(st1,'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 st1.configure('font.Treeview.Heading', font=(font_family,font_size,'bold')) # function to enable selection def select_item(evt): curItem = tree.focus() lvar.set(tree.item(curItem)['values']) out_var.set(tree.item(curItem)['values']) def sort_by(tree, col, descending): # When a column is clicked on sort tree contents . # grab values to sort data = [(tree.set(child, col), child) for child in tree.get_children('')] # reorder data data.sort(reverse=descending) for indx, item in enumerate(data): tree.move(item[1], '', indx) # switch the heading so that it will sort in the opposite direction tree.heading(col, command=lambda col=col: sort_by(tree, col, int(not descending))) # reconfigure tags after ordering list_of_items = tree.get_children('') for i in range(len(list_of_items)): tree.tag_configure(list_of_items[i], background=backg[i%2]) tree_data = [] backg = ["white",'#f0f0ff'] with open(csv_file, newline='', encoding='utf-8-sig') as csvfile: treeCsv = csv.reader(csvfile, delimiter=csv_delimiter) for ix, row in enumerate(treeCsv): if ix == 0: tree_columns = row else: tree_data.append(row) # create Treeview widget tree = Treeview(fr0, column=tree_columns, show='headings',style='font.Treeview') tree.grid(column=0, row=0, sticky='nsew') tree.bind("<<TreeviewSelect>>", select_item) vsb = Scrollbar(fr0,orient="vertical", command=tree.yview) vsb.grid(column=1, row=0, sticky='ns') hsb = Scrollbar(fr0,orient="horizontal", command=tree.xview) hsb.grid(column=0, row=1, sticky='ew') tree.configure(xscrollcommand=hsb.set,yscrollcommand=vsb.set) fr0.grid_columnconfigure(0, weight=1) fr0.grid_rowconfigure(0, weight=1) # insert header, data and tag configuration for ix,col in enumerate(tree_columns): tree.heading(col, text=col.title(), command=lambda c=col: sort_by(tree, c, 0)) #tree.column(col,stretch=True) #tree.column(col,width=font.nametofont('TkHeadingFont').measure(col.title()), #stretch=False) tree.column(col,width=font.Font(family=font_family,size=font_size, weight="bold").measure(col.title()) + 10, stretch=False) #print(tree.column(col)) # insert data row by row, then measure each items' width for ix, item in enumerate(tree_data): item_ID = tree.insert('', 'end', values=item) tree.item(item_ID, tags=item_ID) tree.tag_configure(item_ID, background=backg[ix%2]) for indx, val in enumerate(item): #ilen = font.Font(family="Segoe UI", size=10, weight="normal").measure(val) ilen = font.nametofont('TkDefaultFont').measure(val) if tree.column(tree_columns[indx], width=None) < ilen +10: tree.column(tree_columns[indx], width=ilen + 10) # you should see the widths adjust #print('col',tree.column(tree_columns[indx]),ilen) # display selection lvar = StringVar() lbl = Label(fr0, textvariable=lvar, text="Ready") lbl.grid(column=0, row=2, sticky='nsew')
def search(self, url): # queue to share between gui and threads q = queue.Queue() self.helper.hidefilters() if SearchFrame.content is None: searchprogress = Progressbar(self, orient="horizontal", style='mongo.Horizontal.TProgressbar', length=700, mode="indeterminate") searchprogress.place(relx=.5, rely=.8, anchor=CENTER) searchprogress.start() proglabel = Label(self, text="Fetching Results...", font="Times 14", bg="#282828", fg="#FFFFFF") proglabel.place(relx=.5, rely=.765, anchor=CENTER) # get additional info from filters if they exist url = self.helper.addurlfilters(url) # start thread to get data from url thread = GetDataThread(url, q) thread.start() # wait until thread is done, then get data from queue self.updateuntildata(q, searchprogress) self.data = q.get(0) # get rid of progress bar searchprogress.destroy() proglabel.destroy() else: self.data = SearchFrame.content # make sure search didn't time out if self.data != "ReadTimeout": self.master.master.updateque.queue.clear() # start thread to analyze data and repeat process self.analysisthread = ResultsAnalysisThread(self.data, self.master.master.analyzer, q, self.resultTopics) self.analysisthread.start() self.resultTopics.config(text="Processing Data...(0%)") self.processingloop('percent') self.processingloop('dots') self.helper.hidesearch() style = Style(self) style.configure("Treeview", rowheight=30, fieldbackground='#bdbdbd') style.configure("Treeview.Heading", background="#707070", rowheight=60, font="Ariel 14 bold") self.tree = Treeview(self, columns=('date','title'), selectmode='browse') self.tree['show'] = 'headings' self.tree.column('date', width=100, anchor=CENTER) self.tree.heading('date', text="Date", command = lambda: self.treeview_sort_column(self.tree,'date',False)) self.tree.column('title', width=900) self.tree.heading('title', text="Article Title", anchor=W, command = lambda: self.treeview_sort_column(self.tree,'title',False)) #self.tree.place(relx=.3, relheight=1, width=1200) self.tree.place(x=330, relheight=1, width=760) self.treeyscb = Scrollbar(self, orient="vertical", command=self.tree.yview) self.treeyscb.place(relx=1, rely=.5, relheight=1, anchor=E) self.tree.configure(yscrollcommand=self.treeyscb.set) self.treexscb = Scrollbar(self, orient="horizontal", command=self.tree.xview) self.treexscb.place(relx=.3, rely=.999, width=755, anchor=SW) self.tree.configure(xscrollcommand=self.treexscb.set) self.sf.place(relx=0, rely=.055, relwidth=.30, relheight=.4) self.topicsHead.place(relx=.01, rely=.024, relwidth=.28, relheight=.03) self.topics.place(relx=.01, rely=.065, relwidth=.28) # frame for results analysis self.sf2.place(relx=0, rely=.51, relwidth=.30, relheight=.4) self.resultTopicHead.place(relx=.01, rely=.475, relwidth=.28, relheight=.03) self.resultTopics.place(relx=.01, rely=.52, relwidth=.28) # New Search Edit Search Save Search self.new_search = Button(self, text='New Search', background='#383838', foreground='#5DE0DC', font="Veranda 14", command=self.NewSearch) self.edit_search = Button(self, text='Edit Search', background='#383838', foreground='#5DE0DC', font="Veranda 14", command=self.EditSearch) self.save_search = Button(self, text='Save Search', background='#383838', foreground='#5DE0DC', font="Veranda 14", command=self.saveMenu) if self.data: for count,item in enumerate(self.data): # remove BOM images first from body >uffff item['body'] = ''.join(c for c in unicodedata.normalize('NFC', item['body']) if c <= '\uFFFF') tagname = 'even' if count % 2 == 0 else 'odd' self.tree.insert('', 'end', values=(parser.parse(item['date']).strftime('%m/%d/%y'), item['title'], item['uri'], item['author'], item['body']), tag=tagname) self.tree.tag_configure('even', font='Verdana 14', background="#9fedea") self.tree.tag_configure('odd', font='Verdana 14', background="#dedede") self.tree.bind('<Double-1>', self.on_click) self.tree.bind('<<TreeviewSelect>>', self.on_single_click) self.treeview_sort_column(self.tree,'date',True) else: self.topics.config(text='No Articles Matching Search') self.resultTopics.config(text='') self.new_search.place(relx=0, rely=.95, relwidth=.1, relheight=.05, anchor=NW) if SearchFrame.content is None: self.edit_search.place(relx=.1, rely=.95, relwidth=.1, relheight=.05, anchor=NW) if len(self.data) > 0: self.save_search.place(relx=.2, rely=.95, relwidth=.1, relheight=.05, anchor=NW) else: messagebox.showerror("Too Broad", "Search is too broad. Try refining with filters.") self.helper.ent_keyword.focus_set() SearchFrame.content = None pass
class About(Toplevel): ''' The About dialog Shows information about this application ''' WINDOW_WIDTH = 350 WINDOW_HEIGHT = 120 WINDOW_WIDTH_MIN = 350 WINDOW_HEIGHT_MIN = 100 WINDOW_WIDTH_OFFSET = 40 WINDOW_HEIGHT_OFFSET = 20 WINDOW_TITLE = "Brainfsck - About" def __init__(self, master, **kw): Toplevel.__init__(self, master, **kw) self.style = Style() self.withdraw() x = self.master.winfo_rootx() + self.WINDOW_WIDTH_OFFSET y = self.master.winfo_rooty() + self.WINDOW_HEIGHT_OFFSET loadIcon(self.tk, self, IIVLXICO) self.title(self.WINDOW_TITLE) self.geometry('{0:d}x{1:d}+{2:d}+{3:d}'.format( self.WINDOW_WIDTH, self.WINDOW_HEIGHT, x,y)) self.resizable(False, False) self.minsize(self.WINDOW_WIDTH_MIN, self.WINDOW_HEIGHT_MIN) #grid configure self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=1) self.grid_rowconfigure(0, weight=1) self.grid_rowconfigure(1, weight=0) self.grid_rowconfigure(2, weight=0) self.grid_rowconfigure(3, weight=0) self.grid_rowconfigure(4, weight=1) # grab the current window #self.wait_visibility() self.transient(self.master) self.focus_set() self.grab_set() self.deiconify() # draw this window self.configureStyles() self.draw() # wait for the window to close and return to master self.wait_window() def configureStyles(self): self.style.configure('About.TButton', font='Segoe 8', anchor='center', height=0, width=10, padding=2) self.style.configure('About.TLabel', font='Segoe 10') self.style.configure('AboutBold.TLabel', font='Segoe 14 bold', anchor='center') self.style.configure('AboutBoldMed.TLabel', font='Segoe 11 bold', anchor='center') def draw(self): ''' Draw the About window ''' self.title_label = Label(self, text = "Brainfsck", justify=CENTER, style= 'AboutBold.TLabel') self.title_label.grid(row=0, column=0, columnspan=2, sticky='news') self.title_label_sub = Label(self, text = "Brainfsck Interpreter", style = "AboutBoldMed.TLabel") self.title_label_sub.grid(row=1, column=0, columnspan=2, sticky='news') self.about_label = Label(self, text = "Created by iivlx - [email protected]", style = "About.TLabel") self.about_label.grid(row=2, column=0, columnspan=2, padx=10, sticky='news') self.version_label = Label(self, text = "Version: {0:s}".format('.'.join(str(v) for v in __version__)), style = "About.TLabel") self.version_label.grid(row=3, column=0, columnspan=2, padx=10, sticky='news') self.close_button = Button(self, text = "Close", style = "About.TButton", command = lambda: self.close()) self.close_button.grid(row=4, column=1, padx=4, pady=4, sticky='nes') self.close_button.focus_set() def close(self): ''' Close this dialog and return to parent window ''' self.master.focus_set() self.destroy()
class StartFrame(Frame): def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller # set the controller self.title = "CySpyder" #ttile of the window path = os.getcwd() + '\\resources\spiderweb2.jpg' self.img = ImageTk.PhotoImage(Image.open(path)) self.panel = Label(self, image=self.img) self.panel.pack() #Progress Bar self.s = Style() self.s.theme_use('clam') self.s.configure("mongo.Horizontal.TProgressbar", foreground='#38494C', background='#5AE9FF') self.progress = Progressbar(self, orient="horizontal", style='mongo.Horizontal.TProgressbar', length=700, mode="determinate") self.controller.attributes('-transparentcolor', '#38494C') #Menu Frame window self.style = Style() self.style.configure('My.TFrame', background='#434343') self.sf = Frame(self, width=179, height=76, style='My.TFrame') self.sf['relief']='sunken' #todo to be populated with old searches to be able to reopen. self.menutree = Treeview(self) self.menutree.column('#0', stretch=True) #Menu Labels self.wl= Label(self, text='Welcome', width=24, font='ariel 18') self.wl.configure(background='#434343', foreground='#06c8e6', relief='groove') self.ns = Label(self, text='-New Session-', width=24, height=1, relief='raised', font="ariel 12 bold") self.ns.configure(height=2, background='#828282', foreground='#06c8e6') self.ns.bind('<1>', self.start) self.ns.bind('<Enter>', self.enter) self.ns.bind('<Leave>', self.leave) self.rs = Label(self, text='Recent Searches', width=28,height=2, bd=3, relief='ridge', font="Ariel 12 bold underline") self.rs.configure(background='#434343', foreground='#06c8e6') #window placements self.sf.place(relx=.625, rely=.5, relwidth=.26, relheight=.22, anchor=CENTER) self.wl.place(relx=.624, rely=.449, relwidth=.25, relheight=.1, anchor=CENTER) self.ns.place(relx=.626, rely=.555, relwidth=.25, relheight=.10, anchor=CENTER) self.rs.place(x=0, relwidth=.25, relheight=.1) self.menutree.place(x=0,rely=.045, relwidth=.25, relheight=.92) self.progress.place(y=435) self.bytes = 0 self.maxbytes = 0 self.openMenu() def openMenu(self): # set initial directory to savedScans folder path = os.path.join(os.getcwd(), "Sessions") filenames = os.listdir(path) for file in filenames: filetoprint = file.replace('2017-', '') self.menutree.insert('', 'end', text=filetoprint, tags='date') self.menutree.tag_configure('date', background='grey', foreground='yellow', font='bold, 11') path= os.path.join(os.getcwd(), 'Sessions'+'\\'+file) psr = os.listdir(path) for f in psr: filetoprint = f.replace('.txt', '') filetosend = f#.replace(' ', '') self.menutree.insert('', 'end', text=' -'+filetoprint, values=(file,filetosend), tags='article') self.menutree.tag_configure('article', background='#434343', foreground='#06c8e6', font='bold, 12') self.menutree.bind('<<TreeviewSelect>>', self.onmenuclick) #fill tree with greay past files for i in range(1,20): self.menutree.insert('', 'end', text='', tags='clean') self.menutree.tag_configure('clean', background='#434343') def onmenuclick(self, event): item = self.menutree.item(self.menutree.selection()[0], 'values') path = 'Sessions'+'\\'+item[0]+'\\'+item[1] with open(path, "r") as fin: SearchFrame.content = json.load(fin) self.start(event='open file') def start(self, event): self.progress["value"] = 0 self.maxbytes = 50000 self.progress["maximum"] = 50000 self.after(400, self.master.master.analyzer.loadSpacy) self.read_bytes(event) def read_bytes(self, event): # simulate reading 500 bytes; update progress bar self.bytes += 1500 self.progress["value"] = self.bytes if self.bytes < self.maxbytes: # read more bytes after 100 ms self.after(25, lambda e = event: self.read_bytes(e)) else: self.welcomewindowing() if event == "open file": self.master.master.frames['SearchFrame'].helper.hidesearch() self.master.master.frames['SearchFrame'].search('') def welcomewindowing(self): xoffset = int(self.winfo_screenwidth() / 2 - 1280 / 2) yoffset = int(self.winfo_screenheight() / 2 - 800 / 2) self.controller.geometry("%dx%d+%d+%d" % (1100, 700, xoffset, yoffset)) # set geometry of window self.controller.show_frame('SearchFrame') def enter(self, event): self.ns.config(bg="#d3d3d3") def leave(self, event): self.ns.config(bg="#828282")
class Application_ui(Frame): # 这个类仅实现界面生成功能,具体事件处理代码在子类Application中。 def __init__(self, master=None): Frame.__init__(self, master) self.master.title('Excel转化Rpy工具') self.master.geometry('600x343') self.createWidgets() def createWidgets(self): self.top = self.winfo_toplevel() self.style = Style() self.bkg_gif = PhotoImage(data=base64.b64decode(back_ground_gif_data)) self.background_label = Label(self.top, image=self.bkg_gif) self.background_label.place(x=0, y=0, relwidth=1, relheight=1) self.Text = Text(self.top, font=('宋体', 9)) self.Text.place(relx=0.066, rely=0.07, relwidth=0.869, relheight=0.563) self.saveAddr = Entry(self.top, font=('宋体', 9)) self.saveAddr.place(relx=0.355, rely=0.84, relwidth=0.409, relheight=0.052) self.ComboList = ['源文件目录', '自定义目录'] self.Combo = Combobox(self.top, values=self.ComboList, font=('宋体', 9), state='readonly') self.Combo.place(relx=0.184, rely=0.84, relwidth=0.146, relheight=0.058) self.Combo.set(self.ComboList[0]) self.Combo.bind('<<ComboboxSelected>>', self.comboEvent) self.style.configure('InputButton.TButton', font=('宋体', 9)) self.InputButton = Button(self.top, text='浏览', command=self.InputButton_Cmd, style='InputButton.TButton') self.InputButton.place(relx=0.184, rely=0.7, relwidth=0.133, relheight=0.073) self.Haruhi_gif = PhotoImage(data=base64.b64decode(haruhi_gif_data)) self.style.configure('ConvertButton.TButton', font=('宋体', 9)) self.ConvertButton = Button(self.top, image=self.Haruhi_gif, command=self.ConvertButton_Cmd, style='ConvertButton.TButton') self.ConvertButton.place(relx=0.788, rely=0.7, relwidth=0.146, relheight=0.236) self.style.configure('OutputLabel.TLabel', anchor='w', font=('宋体', 9)) self.OutputLabel = Label(self.top, text='保存目录:', style='OutputLabel.TLabel') self.OutputLabel.place(relx=0.066, rely=0.84, relwidth=0.107, relheight=0.05) self.style.configure('InputLabel.TLabel', anchor='w', font=('宋体', 9)) self.InputLabel = Label(self.top, text='输入设置:', style='InputLabel.TLabel') self.InputLabel.place(relx=0.066, rely=0.723, relwidth=0.107, relheight=0.05) menubar = Menu(self.top) filemenu = Menu(menubar, tearoff=0) # tearoff意为下拉 menubar.add_cascade(label='帮助', menu=filemenu) filemenu.add_command(label='视频教程', command=self.open_help_url) filemenu.add_command(label='检查更新', command=self.check_for_update) self.top.config(menu=menubar)
class MainFrame(Frame): def __init__(self, parent): super().__init__(parent) self.parent = parent self.parent.title("InstaDjango") self.pack(fill=BOTH, expand=1) self.size_and_center_window() self.style = Style() self.style.theme_use("clam") self.style.configure("TFrame", background="#808080", foreground="white") self.style.configure("TButton", background="#808080", foreground="white") self.style.configure("high.TButton", background="#8FBC8B", foreground="white") self.style.configure("TLabel", background="#808080", foreground="white") self.style.map("TButton", background=[("pressed", "#404040"), ("active", "#A0A0A0")]) frame = Frame(self, relief=FLAT, borderwidth=1) frame.pack(fill=BOTH, expand=1) subframe_0 = Frame(frame, relief=FLAT, borderwidth=0) subframe_0.pack(fill=X) lbl_0 = Label(subframe_0, text="App's machine-readable name (used for naming folders locally and remotely):", style="TLabel") lbl_0.pack(fill=BOTH, padx=10, pady=10) entry_0 = Entry(subframe_0) entry_0.pack(fill=X, padx=10, ipady=5) self.set_entry_text(entry_0, "") subframe_1 = Frame(frame, relief=FLAT, borderwidth=0) subframe_1.pack(fill=X) lbl_1 = Label( subframe_1, text="Where to create the app's folder locally:", style="TLabel") lbl_1.pack(fill=BOTH, padx=10, pady=10) entry_1 = Entry(subframe_1) def action_1(): cdir = filedialog.askdirectory(title="Please select a directory") if cdir: self.set_entry_text(entry_1, cdir) button_1 = Button(subframe_1, text="Choose", command=action_1, style="TButton") button_1.pack(side=RIGHT, padx=10, pady=0) entry_1.pack(fill=X, padx=10, ipady=5) self.set_entry_text(entry_1, "") subframe_2 = Frame(frame, relief=FLAT, borderwidth=0) subframe_2.pack(fill=X) lbl_2 = Label(subframe_2, text="Remote host:", style="TLabel") lbl_2.pack(fill=BOTH, padx=10, pady=10) entry_2 = Entry(subframe_2) entry_2.pack(fill=X, padx=10, ipady=5) self.set_entry_text(entry_2, "") subframe_3 = Frame(frame, relief=FLAT, borderwidth=0) subframe_3.pack(fill=X) lbl_3 = Label( subframe_3, text="Remote SSH port (empty will mean the default port):", style="TLabel") lbl_3.pack(fill=BOTH, padx=10, pady=10) entry_3 = Entry(subframe_3) entry_3.pack(fill=X, padx=10, ipady=5) self.set_entry_text(entry_3, "") subframe_4 = Frame(frame, relief=FLAT, borderwidth=0) subframe_4.pack(fill=X) lbl_4 = Label(subframe_4, text="Remote user:"******"TLabel") lbl_4.pack(fill=BOTH, padx=10, pady=10) entry_4 = Entry(subframe_4) entry_4.pack(fill=X, padx=10, ipady=5) self.set_entry_text(entry_4, "") subframe_5 = Frame(frame, relief=FLAT, borderwidth=0) subframe_5.pack(fill=X) lbl_5 = Label( subframe_5, text="Local path to the SSH private key:", style="TLabel") lbl_5.pack(fill=BOTH, padx=10, pady=10) entry_5 = Entry(subframe_5) def action_5(): cdir = filedialog.askopenfilename(title="Please select a private key") if cdir: self.set_entry_text(entry_5, cdir) button_5 = Button(subframe_5, text="Choose", command=action_5, style="TButton") button_5.pack(side=RIGHT, padx=10, pady=0) entry_5.pack(fill=X, padx=10, ipady=5) self.set_entry_text(entry_5, "") subframe_6 = Frame(frame, relief=FLAT, borderwidth=0) subframe_6.pack(fill=X) lbl_6 = Label( subframe_6, text="Where to create the app's folder remotely (should not be owned by root):", style="TLabel") lbl_6.pack(fill=BOTH, padx=10, pady=10) entry_6 = Entry(subframe_6) entry_6.pack(fill=X, padx=10, ipady=5) self.set_entry_text(entry_6, "/var/www") subframe_7 = Frame(frame, relief=FLAT, borderwidth=0) subframe_7.pack(fill=X) lbl_7 = Label(subframe_7, text="Sudo password:"******"TLabel") lbl_7.pack(fill=BOTH, padx=10, pady=10) entry_7 = Entry(subframe_7, show="*") entry_7.pack(fill=X, padx=10, ipady=5) self.set_entry_text(entry_7, "") subframe_8 = Frame(frame, relief=FLAT, borderwidth=0) subframe_8.pack(fill=X) lbl_8 = Label(subframe_8, text="Database password:"******"TLabel") lbl_8.pack(fill=BOTH, padx=10, pady=10) entry_8 = Entry(subframe_8, show="*") entry_8.pack(fill=X, padx=10, ipady=5) self.set_entry_text(entry_8, "") subframe_9 = Frame(frame, relief=FLAT, borderwidth=0) subframe_9.pack(fill=X) lbl_9 = Label(subframe_9, text="Domain:", style="TLabel") lbl_9.pack(fill=BOTH, padx=10, pady=10) entry_9 = Entry(subframe_9) entry_9.pack(fill=X, padx=10, ipady=5) self.set_entry_text(entry_9, "dev.example.com") subframe_10 = Frame(frame, relief=FLAT, borderwidth=0) subframe_10.pack(fill=X) lbl_10 = Label(subframe_10, text="Django installation type (local, production, staging):", style="TLabel") lbl_10.pack(fill=BOTH, padx=10, pady=10) entry_10 = Entry(subframe_10) entry_10.pack(fill=X, padx=10, ipady=5) self.set_entry_text(entry_10, "local") def go(): setup_django_project( proj=entry_0.get(), proj_local_parent_dir=entry_1.get(), host=entry_2.get(), port=entry_3.get(), user=entry_4.get(), ssh_key=entry_5.get(), proj_remote_parent_dir=entry_6.get(), sudo_pass=entry_7.get(), db_pass=entry_8.get(), domain=entry_9.get(), insta_type=entry_10.get()) self.quit() inst_button = Button(self, text="Go", command=go, style="high.TButton") inst_button.pack(side=RIGHT, padx=10, pady=10) quit_button = Button(self, text="Quit", command=self.quit, style="TButton") quit_button.pack(side=RIGHT, pady=10) def size_and_center_window(self): w = 640 h = 850 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)) @staticmethod def set_entry_text(e, text): e.delete(0, END) e.insert(0, text)
def setup(tk_instance): """Sets up all the custom styles. Args: Toplevel Tk instance. """ style = Style(tk_instance) style.theme_use('default') style.configure(GRID_FRAME, background='#888') style.configure(BOX_FRAME, background='white') style.configure(GIVEN_FRAME, background='#ddd') style.configure(NUMBER_LABEL, background='white', font='Helvetica 24') style.configure(GIVEN_LABEL, background='#ddd', font='Helvetica 24 bold') style.configure(PENCIL_LABEL, background='white', font='Helvetica 8') style.configure(GREEN, background='green') style.configure(RED, background='red') style.configure(YELLOW, background='yellow')
def __init__(self, master, font_dict={}, text="Abcd", title="Font Chooser", **kwargs): """ Create a new FontChooser instance. font: dictionnary, like the one returned by the .actual method of a Font object {'family': 'DejaVu Sans', 'overstrike':False, 'size': 12, 'slant': 'italic' or 'roman', 'underline': False, 'weight': 'bold' or 'normal'} text: text to be displayed in the preview label title: window title **kwargs: additional keyword arguments to be passed to Toplevel.__init__ """ Toplevel.__init__(self, master, **kwargs) self.title(title) self.resizable(False, False) self.protocol("WM_DELETE_WINDOW", self.quit) self._validate_family = self.register(self.validate_font_family) self._validate_size = self.register(self.validate_font_size) # variable storing the chosen font self.res = "" style = Style(self) style.configure("prev.TLabel", background="white") bg = style.lookup("TLabel", "background") self.configure(bg=bg) # family list self.fonts = list(set(families())) self.fonts.append("TkDefaultFont") self.fonts.sort() for i in range(len(self.fonts)): self.fonts[i] = self.fonts[i].replace(" ", "\ ") max_length = int(2.5 * max([len(font) for font in self.fonts])) // 3 self.sizes = [ "%i" % i for i in (list(range(6, 17)) + list(range(18, 32, 2))) ] # font default font_dict["weight"] = font_dict.get("weight", "normal") font_dict["slant"] = font_dict.get("slant", "roman") font_dict["family"] = font_dict.get("family", self.fonts[0].replace('\ ', ' ')) font_dict["size"] = font_dict.get("size", 10) # Widgets creation options_frame = Frame(self, relief='groove', borderwidth=2) self.font_family = StringVar(self, " ".join(self.fonts)) self.font_size = StringVar(self, " ".join(self.sizes)) self.var_bold = BooleanVar(self, font_dict["weight"] == "bold") b_bold = Checkbutton(options_frame, text=TR["Bold"], command=self.toggle_bold, variable=self.var_bold) b_bold.grid(row=0, sticky="w", padx=4, pady=(4, 2)) self.var_italic = BooleanVar(self, font_dict["slant"] == "italic") b_italic = Checkbutton(options_frame, text=TR["Italic"], command=self.toggle_italic, variable=self.var_italic) b_italic.grid(row=1, sticky="w", padx=4, pady=2) self.var_size = StringVar(self) self.entry_family = Entry(self, width=max_length, validate="key", validatecommand=(self._validate_family, "%d", "%S", "%i", "%s", "%V")) entry_size = Entry(self, width=4, validate="key", textvariable=self.var_size, validatecommand=(self._validate_size, "%d", "%P", "%V")) self.list_family = Listbox(self, selectmode="browse", listvariable=self.font_family, highlightthickness=0, exportselection=False, width=max_length) self.list_size = Listbox(self, selectmode="browse", listvariable=self.font_size, highlightthickness=0, exportselection=False, width=4) scroll_family = Scrollbar(self, orient='vertical', command=self.list_family.yview) scroll_size = Scrollbar(self, orient='vertical', command=self.list_size.yview) self.preview_font = Font(self, **font_dict) if len(text) > 30: text = text[:30] self.preview = Label(self, relief="groove", style="prev.TLabel", text=text, font=self.preview_font, anchor="center") # Widget configuration self.list_family.configure(yscrollcommand=scroll_family.set) self.list_size.configure(yscrollcommand=scroll_size.set) self.entry_family.insert(0, font_dict["family"]) self.entry_family.selection_clear() self.entry_family.icursor("end") entry_size.insert(0, font_dict["size"]) i = self.fonts.index(self.entry_family.get().replace(" ", "\ ")) self.list_family.selection_clear(0, "end") self.list_family.selection_set(i) self.list_family.see(i) i = self.sizes.index(entry_size.get()) self.list_size.selection_clear(0, "end") self.list_size.selection_set(i) self.list_size.see(i) self.entry_family.grid(row=0, column=0, sticky="ew", pady=(10, 1), padx=(10, 0)) entry_size.grid(row=0, column=2, sticky="ew", pady=(10, 1), padx=(10, 0)) self.list_family.grid(row=1, column=0, sticky="nsew", pady=(1, 10), padx=(10, 0)) self.list_size.grid(row=1, column=2, sticky="nsew", pady=(1, 10), padx=(10, 0)) scroll_family.grid(row=1, column=1, sticky='ns', pady=(1, 10)) scroll_size.grid(row=1, column=3, sticky='ns', pady=(1, 10)) options_frame.grid(row=0, column=4, rowspan=2, padx=10, pady=10, ipadx=10) self.preview.grid(row=2, column=0, columnspan=5, sticky="eswn", padx=10, pady=(0, 10), ipadx=4, ipady=4) button_frame = Frame(self) button_frame.grid(row=3, column=0, columnspan=5, pady=(0, 10), padx=10) Button(button_frame, text="Ok", command=self.ok).grid(row=0, column=0, padx=4, sticky='ew') Button(button_frame, text=TR["Cancel"], command=self.quit).grid(row=0, column=1, padx=4, sticky='ew') self.list_family.bind('<<ListboxSelect>>', self.update_entry_family) self.list_size.bind('<<ListboxSelect>>', self.update_entry_size, add=True) self.list_family.bind("<KeyPress>", self.keypress) self.entry_family.bind("<Return>", self.change_font_family) self.entry_family.bind("<Tab>", self.tab) entry_size.bind("<Return>", self.change_font_size) self.entry_family.bind("<Down>", self.down_family) entry_size.bind("<Down>", self.down_size) self.entry_family.bind("<Up>", self.up_family) entry_size.bind("<Up>", self.up_size) # bind Ctrl+A to select all instead of go to beginning self.bind_class("TEntry", "<Control-a>", self.select_all) self.update_idletasks() self.grab_set() self.entry_family.focus_set() self.lift()
# progressbar with text inside it s = Style(root) # add the label to the progressbar style s.layout("LabeledProgressbar", [('LabeledProgressbar.trough', {'children': [('LabeledProgressbar.pbar', {'side': 'left', 'sticky': 'ns'}), ("LabeledProgressbar.label", # label inside the bar {"sticky": ""})], 'sticky': 'nswe'})]) progress = Progressbar(commandframe, orient="horizontal", length=300, style="LabeledProgressbar") progress.pack(side=TOP, padx=10, pady=10) # change the text of the progressbar, # the trailing spaces are here to properly center the text s.configure("LabeledProgressbar", text="Loading Model on GPU please wait:0 % ") # uncomment this if you want to make an image button instead of 'Detect' text button #btnphoto = ImageTk.PhotoImage(Image.open('C:/Users/Talha/Desktop/chkpt/paprika_model/run.png')) # make detect button btn = Button(commandframe, text='Detect', command =play_btn)#image = btnphoto, btn.pack(side=LEFT, padx=10, pady=10) # 2nd progress bar with detect button progress_det = Progressbar(commandframe, length=200, cursor='watch',mode="determinate", orient=HORIZONTAL) #progress_det = Progressbar(commandframe, orient = HORIZONTAL, length = 100, mode = 'indeterminate') # for shuttling block progress bar progress_det.pack(side=LEFT, padx=10, pady=10) ################################################## # Start threadin b/c loading model on GPU will take time # threading will run processes in parallel so that our GUI don't stop responding
def __init__(self, master,title=None,args=None): self.master = master self.args = args self.name = title master.title("Startup interface for %s" % title) self.arguments = dict() style = Style() style.configure(".",background="lightgrey") labelStyle = Style() labelStyle.configure("TLabel", background="lightgrey") buttonStyle = Style() buttonStyle.configure("TButton", background = "lightgrey") chkbuttonStyle = Style() chkbuttonStyle.configure("TCheckbutton", background = "lightgrey") rbuttonStyle = Style() rbuttonStyle.configure("TRadiobutton", background = "lightgrey") row = 0 column = 0 # Input edge file self.inEdgeLabel = Label(master, text = "Input edge file") self.inEdgeLabel.grid(row=row,column=column, sticky=W, padx=3) self.inEdgeFile = StringVar() if self.args.input_edge_file: self.inEdgeFile.set(self.args.input_edge_file) self.inEdgeEntry = Entry(master, width = WIDTH, textvariable = self.inEdgeFile) column += 1 self.inEdgeEntry.grid(row=row,column=column, padx=3) self.inEdgeSelect = Button(master, text = "Select", command = lambda: self.setOutputFiles(IN=self.inEdgeFile,TWIN=self.outTwinFile,TWINCOMP=self.twinCompFile)) column += 1 self.inEdgeSelect.grid(row=row,column=column, sticky=W, padx=3) self.optionLabel2 = Label(master, text = "required") column += 1 self.optionLabel2.grid(row=row,column=column,sticky=W, padx=3) # tip helpText1 = "Edge file for input graph (two columns, tab-delimited)." self.inEdgeTip = CreateToolTip(self.inEdgeEntry, helpText1) ## row += 1 column = 0 # Output twin file self.outTwinLabel = Label(master, text = "Output twin file") self.outTwinLabel.grid(row=row,column=column, sticky=W, padx=3) self.outTwinFile = StringVar() if self.args.o: self.outTwinFile.set(self.args.o) self.outTwinEntry = Entry(master, width = WIDTH, textvariable = self.outTwinFile) column += 1 self.outTwinEntry.grid(row=row,column=column, padx=3) self.outTwinSelect = Button(master, text = "Select", command = lambda: self.openFile(var=self.outTwinFile)) column += 1 self.outTwinSelect.grid(row=row,column=column, sticky=W, padx=3) self.optionLabel2 = Label(master, text = "required") column += 1 self.optionLabel2.grid(row=row,column=column,sticky=W, padx=3) # tip helpText2 = "Links a nodeID to its twin class ID (two columns, tab-delimited)." self.outTwinTip = CreateToolTip(self.outTwinEntry, helpText2) ## row += 1 column = 0 # Twin component file self.twinCompLabel = Label(master, text = "Twin component file ") self.twinCompLabel.grid(row=row,column=column, sticky=W, padx=3) self.twinCompFile = StringVar() if self.args.c: self.twinCompFile.set(self.args.c) self.twinCompEntry = Entry(master, width = WIDTH, textvariable = self.twinCompFile) column += 1 self.twinCompEntry.grid(row=row,column=column, padx=3) self.twinCompSelect = Button(master, text = "Select", command = lambda: self.openFile(var=self.twinCompFile)) column += 1 self.twinCompSelect.grid(row=row,column=column, sticky=W, padx=3) self.optionLabel2 = Label(master, text = "optional") column += 1 self.optionLabel2.grid(row=row,column=column,sticky=W, padx=3) # tip helpText3 = "Links a nodeID and its neighbours to the twin class ID.\nThis is usually an overlapping clustering." self.twinCompTip = CreateToolTip(self.twinCompEntry, helpText3) ## row += 1 column = 0 # Populate outFiles if edge file given if self.args.input_edge_file: inFile = os.path.split(self.args.input_edge_file)[1] inRad = inFile.split(".")[0] twin = inRad+".twins" twinComp = inRad+".twin_comp" self.outTwinFile.set(twin) self.twinCompFile.set(twinComp) # Partiteness options self.inNodeLabel = Label(master, text = "Partitneness") self.inNodeLabel.grid(row=row,column=column, sticky=W, padx=3) column += 1 MODES = [("Unipartite", "1"),("Bipartite", "2"),] self.inNodeType = StringVar() self.v = StringVar() if str(self.args.n) == '1' or str(self.args.n) == '2': self.v.set(self.args.n) # initialize at bipartite elif self.args.n: self.v.set("m") self.inNodeType.set(self.args.n) rbFrame = Frame(master) # create subframe for radiobuttons for text,mode in MODES: b = Radiobutton(rbFrame, text=text, variable=self.v, value=mode, command = lambda: self.inNodeType.set('')) # tip CreateToolTip(b,"Select if graph is %s" % text.lower()) ## b.pack(side="left", fill=None, expand=False, padx=3) b = Radiobutton(rbFrame, text="Multipartite", variable=self.v, value="m", command = lambda: self.openFile(var=self.inNodeType)) CreateToolTip(b,"Select if graph is multipartite.\nThis will open a select box for the node type file.") b.pack(side="left", fill=None, expand=False, padx=3) rbFrame.grid(row=row,column=column, padx=3) row += 1 column = 0 self.inNodeEntry = Entry(master, width = WIDTH, textvariable = self.inNodeType, validate='focusin',validatecommand = lambda: self.v.set("m")) CreateToolTip(self.inNodeEntry,"""Select node type file for multipartite graphs.\nThis will reset the partiteness to "Multipartite".""") column += 1 self.inNodeEntry.grid(row=row,column=column, padx=3) self.inNodeSelect = Button(master, text = "Select", command = lambda: self.openFile2(var=self.inNodeType,var2=self.v,value="m")) # reset value to "multipartite" when type file is chosen. column += 1 self.inNodeSelect.grid(row=row,column=column, sticky=W, padx=3) self.optionLabel2 = Label(master, text = "for multipartite") column += 1 self.optionLabel2.grid(row=row,column=column,sticky=W, padx=3) CreateToolTip(self.inNodeSelect,"""Select node type file for multipartite graphs.\nThis will reset the partiteness to "Multipartite".""") row += 1 column = 0 # unilat self.twinSelectLabel = Label(master, text = "Restrict to node types") self.twinSelectLabel.grid(row=row,column=column, sticky=W, padx=3) column += 1 self.unilat = StringVar() if self.args.u: self.unilat.set(self.args.u) self.twinSelectEntry = Entry(master, width = WIDTH, textvariable = self.unilat) self.twinSelectEntry.grid(row=row,column=column, padx=3) column += 2 self.optionLabel2 = Label(master, text = "optional (comma-separated)") self.optionLabel2.grid(row=row,column=column, padx=3) CreateToolTip(self.twinSelectEntry,"Computes twins for nodes of specified types only.") row += 1 column = 0 # Min support self.minsuppLabel = Label(master, text = "Minimum support") self.minsuppLabel.grid(row=row,column=column, sticky=W, padx=3) column += 1 self.minsupp = StringVar() if self.args.thr: self.minsupp.set(self.args.thr) self.minsuppEntry = Entry(master, width = WIDTH, textvariable = self.minsupp) self.minsuppEntry.grid(row=row,column=column, padx=3) column += 2 self.optionLabel2 = Label(master, text = "optional") self.optionLabel2.grid(row=row,column=column, padx=3,sticky=W) CreateToolTip(self.minsuppEntry,"Returns twins only if their neighbourhood has at least this number of elements.") row += 1 column = 0 # min size self.minsizeLabel = Label(master, text = "Minimum twin size") self.minsizeLabel.grid(row=row,column=column, sticky=W, padx=3) column += 1 self.minsize = StringVar() if self.args.M: self.minsize.set(self.args.M) self.minsizeEntry = Entry(master, width = WIDTH, textvariable = self.minsize) self.minsizeEntry.grid(row=row,column=column, padx=3) column += 2 self.optionLabel2 = Label(master, text = "optional") self.optionLabel2.grid(row=row,column=column, padx=3,sticky=W) CreateToolTip(self.minsizeEntry,"Returns twins only if they have at least this number of elements.") row += 1 column = 0 # Log self.optionLabel = Label(master, text = "Log file") self.optionLabel.grid(row=row,column=0, sticky=W, padx=3) self.l = StringVar() try: log = self.args.l.name.strip("(<,>") except: log = log self.l.set(log) self.optionEntry = Entry(master, width = WIDTH, textvariable = self.l) self.optionEntry.grid(row=row,column=1, padx=3) row += 2 cbFrame = Frame(master) # create subframe for command buttons self.run_button = Button(cbFrame, text="Run", command=self.run) self.run_button.grid(row=row,column=0,padx=12) self.close_button = Button(cbFrame, text="Close", command=self.Quit) self.close_button.grid(row=row,column=1,padx=12) cbFrame.grid(row=row,column=1,columnspan=2,sticky=E+W) helpText = detect_twins.processArgs().format_help() self.helpbutton = Button(master, text="Help", command = lambda: HelpWindow(text=helpText,name=self.name)) self.helpbutton.grid(row=row,column=2,sticky=W,padx=3)
choose_label = Label(window, text="Choose Path : ") choose_label.place(x=32, y=200) entry_2 = Entry(window, width=45, textvariable=path) entry_2.place(x=140, y=200) Button(window, text="Browse", command=select).place(x=418, y=196) video_label = Label(window, font="arial 8") video_label.place(x=13, y=280) progress_label = Label(window, font="arial 12 bold") progress_label.place(x=242, y=340) S = Style() S.configure("TProgressbar", foreground="green", background="white", thickness=40) progress = Progressbar(window, length=495, orient=HORIZONTAL, mode="determinate") progress['value'] = 0 progress.place(x=15, y=300) Button(window, text="Download", command=thread_func).place(x=230, y=400) new = 1 url = "https://github.com/AbhishekTiwari-342123/youtube-playlist-downloader" def openweb():
def __init__(self, master, columns, data=None, command=None, sort=True, select_mode=None, heading_anchor = CENTER, cell_anchor=W, style=None, height=None, padding=None, adjust_heading_to_content=False, stripped_rows=None, selection_background=None, selection_foreground=None, field_background=None, heading_font= None, heading_background=None, heading_foreground=None, cell_pady=2, cell_background=None, cell_foreground=None, cell_font=None, headers=True): self._stripped_rows = stripped_rows self._columns = columns self._number_of_rows = 0 self._number_of_columns = len(columns) self.row = self.List_Of_Rows(self) self.column = self.List_Of_Columns(self) s = Style() if style is None: style_name = "Multicolumn_Listbox%s.Treeview"%self._style_index self._style_index += 1 else: style_name = style style_map = {} if selection_background is not None: style_map["background"] = [('selected', selection_background)] if selection_foreground is not None: style_map["foeground"] = [('selected', selection_foreground)] if style_map: s.map(style_name, **style_map) style_config = {} if cell_background is not None: style_config["background"] = cell_background if cell_foreground is not None: style_config["foreground"] = cell_foreground if cell_font is None: font_name = s.lookup(style_name, "font") cell_font = nametofont(font_name) else: if not isinstance(cell_font, Font): if isinstance(cell_font, basestring): cell_font = nametofont(cell_font) else: if len(font) == 1: cell_font = Font(family=cell_font[0]) elif len(font) == 2: cell_font = Font(family=cell_font[0], size=cell_font[1]) elif len(font) == 3: cell_font = Font(family=cell_font[0], size=cell_font[1], weight=cell_font[2]) else: raise ValueError("Not possible more than 3 values for font") style_config["font"] = cell_font self._cell_font = cell_font self._rowheight = cell_font.metrics("linespace")+cell_pady style_config["rowheight"]=self._rowheight if field_background is not None: style_config["fieldbackground"] = field_background s.configure(style_name, **style_config) heading_style_config = {} if heading_font is not None: heading_style_config["font"] = heading_font if heading_background is not None: heading_style_config["background"] = heading_background if heading_foreground is not None: heading_style_config["foreground"] = heading_foreground heading_style_name = style_name + ".Heading" s.configure(heading_style_name, **heading_style_config) treeview_kwargs = {"style": style_name} if height is not None: treeview_kwargs["height"] = height if padding is not None: treeview_kwargs["padding"] = padding if headers: treeview_kwargs["show"] = "headings" else: treeview_kwargs["show"] = "" if select_mode is not None: treeview_kwargs["selectmode"] = select_mode self.interior = Treeview(master, columns=columns, **treeview_kwargs) if command is not None: self._command = command self.interior.bind("<<TreeviewSelect>>", self._on_select) for i in range(0, self._number_of_columns): if sort: self.interior.heading(i, text=columns[i], anchor=heading_anchor, command=lambda col=i: self.sort_by(col, descending=False)) else: self.interior.heading(i, text=columns[i], anchor=heading_anchor) if adjust_heading_to_content: self.interior.column(i, width=Font().measure(columns[i])) self.interior.column(i, anchor=cell_anchor) if data is not None: for row in data: self.insert_row(row)
def configure_ui(info): """ UI config function. @param info: UI config info dict. @return: None. """ # Background color bg_color = 'white smoke' # Create ttk style object STYLE = Style() # Configure TFrame style's background STYLE.configure( 'TFrame', background=bg_color, ) # Configure TLabelframe style's background STYLE.configure( 'TLabelframe', background=bg_color, ) # Configure TLabelframe.Label style's background STYLE.configure( 'TLabelframe.Label', background=bg_color, ) # Configure TLabel style's background STYLE.configure( 'TLabel', background=bg_color, ) # Configure TRadiobutton style's background STYLE.configure( 'TRadiobutton', background=bg_color, ) # Get TK root window tk = info['tk'] # Set window title tk.title('AoikRegistryEditor') # Set window geometry tk.geometry('1280x720') # Configure layout weights for children. # Row 0 is for registry editor. tk.rowconfigure(0, weight=1) # Row 1 is for status bar tk.rowconfigure(1, weight=0) # Use only one column tk.columnconfigure(0, weight=1) # Get menu tree menutree = info['menutree'] # Add `File` menu menutree.add_menu(pid='/', id='File', index=0) # Add `Exit` command menutree.add_command(pid='/File', id='Exit', command=tk.quit) # Get status bar label status_bar_label = info['status_bar_label'] # Set status bar label's main frame's height status_bar_label.widget().config(height=20) # Set status bar label's background status_bar_label.config(background='#F0F0F0') # Lay out the status bar label status_bar_label.grid( in_=tk, row=2, column=0, sticky='NSEW', padx=(5, 0), ) # Create size grip sizegrip = Sizegrip(master=tk) # Lay out the size grip sizegrip.grid( in_=tk, row=2, column=0, sticky='E', ) # Get registry editor editor = info['editor'] # Lay out the registry editor editor.grid( row=0, column=0, sticky='NSEW', ) # Set registry editor's inner padding editor.config(padding=10) # Get path bar label path_bar_label = info['path_bar_label'] # Get static files' directory path static_dir = os.path.dirname( os.path.abspath(aoikregistryeditor.static.__file__) ) # Get path bar label's normal state image file path image_path = os.path.join(static_dir, 'path_bar_label_normal.png') # Load path bar label's normal state image file path_bar_label._normal_image = PhotoImage(file=image_path) # Get path bar label's disabled state image file path image_path = os.path.join(static_dir, 'path_bar_label_disabled.png') # Load path bar label's disabled state image file path_bar_label._disabled_image = PhotoImage(file=image_path) # Set path bar label's images path_bar_label.config( image=( path_bar_label._normal_image, 'disabled', path_bar_label._disabled_image, ) ) # Get path bar textfield path_bar = info['path_bar'] # Set path bar textfield's font path_bar.config(font=('Consolas', 12)) # Set path bar textfield's outer padding path_bar.grid(padx=(3, 0)) # Get child keys labelframe child_keys_labelframe = info['child_keys_labelframe'] # Set child keys labelframe's outer padding child_keys_labelframe.grid(pady=(5, 0)) # Set child keys labelframe's inner padding child_keys_labelframe.config(padding=5) # Get child keys listbox child_keys_listbox = info['child_keys_listbox'] # Set child keys listbox's font child_keys_listbox.config(font=('Consolas', 12)) # Get fields labelframe fields_labelframe = info['fields_labelframe'] # Set fields labelframe's outer padding fields_labelframe.grid(padx=(10, 0), pady=(5, 0)) # Set fields labelframe's inner padding fields_labelframe.config(padding=5) # Get fields listbox fields_listbox = info['fields_listbox'] # Set fields listbox's font fields_listbox.config(font=('Consolas', 12)) # Create event handler to set fields listbox background def _fields_listbox_set_background(): # If fields listbox is not empty if fields_listbox.size() > 0: # Set background color for non-empty listbox fields_listbox.config(background='white') # If fields listbox is empty else: # Set background color for empty listbox fields_listbox.config(background='gainsboro') # Call the event handler to initialize the background color _fields_listbox_set_background() # Add the event handler to fields listbox fields_listbox.handler_add( fields_listbox.ITEMS_CHANGE_DONE, _fields_listbox_set_background ) # Get field editor labelframe field_editor_labelframe = info['field_editor_labelframe'] # Set field editor labelframe's outer padding field_editor_labelframe.grid(padx=(10, 0), pady=(5, 0)) # Set field editor labelframe's inner padding field_editor_labelframe.config(padding=5) # Get field add label field_add_label = info['field_add_label'] # Set field add label's main frame size field_add_label.widget().config(width=40, height=40) # Get field add label's normal state image file path image_path = os.path.join(static_dir, 'field_add_normal.png') # Load field add label's normal state image file field_add_label._normal_image = PhotoImage(file=image_path) # Get field add label's active state image file path image_path = os.path.join(static_dir, 'field_add_active.png') # Load field add label's active state image file field_add_label._active_image = PhotoImage(file=image_path) # Get field add label's hover state image file path image_path = os.path.join(static_dir, 'field_add_hover.png') # Load field add label' hover state image file field_add_label._hover_image = PhotoImage(file=image_path) # Set field add label's images. # Notice `disabled` state is excluded from other states. # Notice `active` state takes precedence over `hover` state. field_add_label.config( image=( field_add_label._normal_image, '!disabled active', field_add_label._active_image, '!disabled hover', field_add_label._hover_image, ) ) # Get field delete label field_del_label = info['field_del_label'] # Set field delete label's main frame size field_del_label.widget().config(width=40, height=40) # Get field delete label's normal state image file path image_path = os.path.join(static_dir, 'field_del_normal.png') # Load field delete label's normal state image file field_del_label._normal_image = PhotoImage(file=image_path) # Get field delete label's active state image file path image_path = os.path.join(static_dir, 'field_del_active.png') # Load field delete label's active state image file field_del_label._active_image = PhotoImage(file=image_path) # Get field delete label's hover state image file path image_path = os.path.join(static_dir, 'field_del_hover.png') # Load field delete label's hover state image file field_del_label._hover_image = PhotoImage(file=image_path) # Set field delete label's images. # Notice `disabled` state is excluded from other states. # Notice `active` state takes precedence over `hover` state. field_del_label.config( image=( field_del_label._normal_image, '!disabled active', field_del_label._active_image, '!disabled hover', field_del_label._hover_image, ) ) # Get field load label field_load_label = info['field_load_label'] # Set field load label's main frame size field_load_label.widget().config(width=40, height=40) # Get field load label's normal state image file path image_path = os.path.join(static_dir, 'field_load_normal.png') # Load field load label's normal state image file field_load_label._normal_image = PhotoImage(file=image_path) # Get field load label's active state image file path image_path = os.path.join(static_dir, 'field_load_active.png') # Load field load label's active state image file field_load_label._active_image = PhotoImage(file=image_path) # Get field load label's hover state image file path image_path = os.path.join(static_dir, 'field_load_hover.png') # Load field load label's hover state image file field_load_label._hover_image = PhotoImage(file=image_path) # Set field load label's images. # Notice `disabled` state is excluded from other states. # Notice `active` state takes precedence over `hover` state. field_load_label.config( image=( field_load_label._normal_image, '!disabled active', field_load_label._active_image, '!disabled hover', field_load_label._hover_image, ) ) # Get field save label field_save_label = info['field_save_label'] # Set field save label's main frame size field_save_label.widget().config(width=40, height=40) # Get field save label's normal state image file path image_path = os.path.join(static_dir, 'field_save_normal.png') # Load field save label's normal state image file field_save_label._normal_image = PhotoImage(file=image_path) # Get field save label's active state image file path image_path = os.path.join(static_dir, 'field_save_active.png') # Load field save label's active state image file field_save_label._active_image = PhotoImage(file=image_path) # Get field save label's hover state image file path image_path = os.path.join(static_dir, 'field_save_hover.png') # Load field save label's hover state image file field_save_label._hover_image = PhotoImage(file=image_path) # Set field save label's images. # Notice `disabled` state is excluded from other states. # Notice `active` state takes precedence over `hover` state. field_save_label.config( image=( field_save_label._normal_image, '!disabled active', field_save_label._active_image, '!disabled hover', field_save_label._hover_image, ) ) # Get field add dialog field_add_dialog = info['field_add_dialog'] # Set field add dialog's geometry field_add_dialog.toplevel().geometry('300x110') # Set field add dialog to not resizable field_add_dialog.toplevel().resizable(width=False, height=False) # Set field add dialog's background field_add_dialog.toplevel().config(background=bg_color) # Set field add dialog's main frame's outer padding field_add_dialog.main_frame().grid(padx=5, pady=5) # Set field add dialog's confirm button's outer padding field_add_dialog.confirm_button().grid(pady=(15, 0)) # Set field add dialog's cancel button's outer padding field_add_dialog.cancel_button().grid(pady=(15, 0)) # Set field add dialog's field add type label's outer padding editor._field_add_type_label.grid( pady=(10, 0), ) # Set field add dialog's field add type radio buttons frame's outer padding editor._field_add_type_rbuttons_frame.grid( padx=(3, 0), pady=(10, 0), )
def __init__(self, master): self.master = master self.master.withdraw() if self.master.winfo_viewable(): self.master.transient() self.master.protocol("WM_DELETE_WINDOW", self._check_exit) self.master.title("Biscuit") try: img = PhotoImage(file=OSCONST.ICON) except TclError: img = PhotoImage(file=OSCONST.ICON_GIF) self.master.tk.call('wm', 'iconphoto', self.master._w, img) self.treeview_text_size = OSCONST.TREEVIEW_TEXT_SIZE Frame.__init__(self, self.master) self.proj_settings_file = op.join(OSCONST.USRDIR, 'proj_settings.pkl') self.settings_file = op.join(OSCONST.USRDIR, 'settings.pkl') # sort out some styling style = Style() style.configure("Treeview", font=("TkTextFont", self.treeview_text_size)) # this will be a dictionary containing any preloaded data from MNE # when we click on a folder to load its information, the object will be # placed in this dictionary so that we can then avoid reloading it # later as each load of data takes ~0.5s self.preloaded_data = dict() self._load_settings() self.save_handler = SaveManager(self) self.context = ClickContext() self.selected_files = None # the current set of selected files # the previous set. Keep as a buffer in case it is needed # (it is for the file association!) self.prev_selected_files = None self.r_click_menu = RightClick(self, self.context) self._create_widgets() self._create_menus() self._drag_mode = None self.progress_popup = None self.file_treeview.generate('', self.settings["DATA_PATH"]) self.file_treeview.index() # This dictionary will consist of keys which are the file paths to the # .con files, and the values will be a list of associated .mrk files. # All other files (.hsp, .elp) are automatically associated by name. self.file_groups = dict() # the different operating modes of the treeview. self.treeview_select_mode = "NORMAL" # This will allow us to put the treeview in different modes # (eg. select a file when prompted etc) # options: "ASSOCIATING", "NORMAL" # set some tag configurations self.file_treeview.tag_configure('ASSOC_FILES', foreground="Blue") self.file_treeview.tag_configure('BAD_FILE', foreground="Red") self.file_treeview.tag_configure('GOOD_FILE', foreground="Green") self.file_treeview.tag_configure('JUNK_FILE', font=("TkTextFont", self.treeview_text_size, 'overstrike')) self.save_handler.load() self.master.deiconify() self.focus_set() self.update_idletasks() screen_width = self.master.winfo_screenwidth() screen_height = self.master.winfo_screenheight() screen_dimensions = "{0}x{1}+20+20".format(screen_width - 200, screen_height - 200) self.master.geometry(screen_dimensions) if OSCONST.os == 'LNX': # For some reason the right click menu isn't un-drawn on linux # like it is on windows and mac... self.master.bind("<Button-1>", self.r_click_menu.undraw, add='+')