def __init__(self, parent, title, imageFile, body): super(DialogAbout, self).__init__(parent) self.parent = parent parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.transient(self.parent) self.title(title) frame = Frame(self) image = PhotoImage(file=imageFile) aboutImage = Label(frame, image=image) aboutBody = Label(frame, text=body, wraplength=500) okButton = Button(frame, text=_("OK"), command=self.ok) okButton.focus_set() aboutImage.grid(row=0, column=0, sticky=NW, pady=20, padx=16) aboutBody.grid(row=0, column=1, columnspan=2, sticky=EW, pady=3, padx=0) okButton.grid(row=1, column=2, sticky=EW, pady=3) frame.grid(row=0, column=0, sticky=(N,S,E,W)) frame.columnconfigure(1, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) self.geometry("+{0}+{1}".format(dialogX+200,dialogY+200)) self.bind("<Alt-u>", lambda *ignore: okButton.focus_set()) self.bind("<Return>", self.ok) self.bind("<Escape>", self.close) self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self)
def __init__(self, parent=None, title="", message="", button="Ok", image=None, **options): """ Create a message box with one button: parent: parent of the toplevel window title: message box title message: message box text button: message displayed on the button image: image displayed at the left of the message **options: other options to pass to the Toplevel.__init__ method """ Toplevel.__init__(self, parent, **options) self.transient(parent) self.resizable(False, False) self.title(title) if image: Label(self, text=message, wraplength=335, font="Sans 11", compound="left", image=image).grid(row=0, padx=10, pady=10) else: Label(self, text=message, wraplength=335, font="Sans 11").grid(row=0, padx=10, pady=10) b = Button(self, text=button, command=self.destroy) b.grid(row=1, padx=10, pady=10) self.grab_set() b.focus_set() self.wait_window(self)
def create_widgets(self): ''' Creates appropriate widgets on this frame. ''' self.columnconfigure(0, weight=1) self.rowconfigure(3, weight=1) frame_for_save_btn = Frame(self) frame_for_save_btn.columnconfigure(1, weight=1) self.status_lbl = Label(frame_for_save_btn, text='') self.status_lbl.grid(row=0, column=1, sticky=N+W) save_solution_btn = Button(frame_for_save_btn, text='Save solution', command=self.on_save_solution) save_solution_btn.grid(row=1, column=0, sticky=W+N, padx=5, pady=5) self.progress_bar = Progressbar(frame_for_save_btn, mode='determinate', maximum=100) self.progress_bar.grid(row=1, column=1, sticky=W+E, padx=10, pady=5) frame_for_save_btn.grid(sticky=W+N+E+S, padx=5, pady=5) frame_for_btns = Frame(self) self._create_file_format_btn('*.xlsx', 1, frame_for_btns, 0) self._create_file_format_btn('*.xls', 2, frame_for_btns, 1) self._create_file_format_btn('*.csv', 3, frame_for_btns, 2) self.solution_format_var.set(1) frame_for_btns.grid(row=1, column=0, sticky=W+N+E+S, padx=5, pady=5) self.data_from_file_lbl = Label(self, text=TEXT_FOR_FILE_LBL, anchor=W, justify=LEFT, wraplength=MAX_FILE_PARAMS_LBL_LENGTH) self.data_from_file_lbl.grid(row=2, column=0, padx=5, pady=5, sticky=W+N) self.solution_tab = SolutionFrameWithText(self) self.solution_tab.grid(row=3, column=0, sticky=W+E+S+N, padx=5, pady=5)
def __init__(self, title="", message="", button="Ok", image=None, checkmessage="", style="clam", **options): """ Create a messagebox with one button and a checkbox below the button: parent: parent of the toplevel window title: message box title message: message box text button: message displayed on the button image: image displayed at the left of the message checkmessage: message displayed next to the checkbox **options: other options to pass to the Toplevel.__init__ method """ Tk.__init__(self, **options) self.resizable(False, False) self.title(title) s = Style(self) s.theme_use(style) if image: Label(self, text=message, wraplength=335, font="Sans 11", compound="left", image=image).grid(row=0, padx=10, pady=(10, 0)) else: Label(self, text=message, wraplength=335, font="Sans 11").grid(row=0, padx=10, pady=(10, 0)) b = Button(self, text=button, command=self.destroy) b.grid(row=2, padx=10, pady=10) self.var = BooleanVar(self) c = Checkbutton(self, text=checkmessage, variable=self.var) c.grid(row=1, padx=10, pady=0, sticky="e") self.grab_set() b.focus_set() self.wait_window(self)
class Window(Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.master.resizable(False, False) self.master.title('The Game of Life') self.pack() self.button_start = Button(self, text='Start', command=self.button_start) self.button_start.grid(row=1, column=1, padx=8, pady=8) Button(self, text='Reset', command=self.button_reset).grid(row=2, column=1) self.world = World(self, 60, on_stop=self.button_start_text_reset) self.world.grid(row=1, column=2, rowspan=50) def button_start_text_reset(self): self.button_start['text'] = 'Start' def button_start(self): if self.world.simulation: self.world.stop() self.button_start_text_reset() else: self.world.start() self.button_start['text'] = 'Stop' def button_reset(self): self.world.stop() self.world.clear() self.button_start_text_reset()
def add_file_info_box(self, mainframe, name, labeldict, btncallback, fvar): """ Create and add a infobox containing the info about a loaded savegame. """ title = {'source':'Copy face from source file:', 'target':'To target file:'} frame = LabelFrame(mainframe, text=title[name]) frame.pack(anchor=N, fill=X, expand=1, side=TOP, padx=0, pady=0) frame.columnconfigure(1, weight=1) btn = Button(frame, text='Browse', command=btncallback) btn.grid(column=0, row=0, padx=2, pady=2) field = Entry(frame, width=50, textvariable=fvar) field.grid(column=1, row=0, columnspan=2, padx=2, pady=2, sticky=W+E) l = ('name','gender','level','race','location','save number','playing time') for n, (i, j) in enumerate([(x.capitalize()+':', x) for x in l]): Label(frame, text=i, state=DISABLED).grid(column=0, row=n+1, padx=4, pady=3, sticky=E) labeldict[j] = StringVar() Label(frame, textvariable=labeldict[j]).grid(column=1, row=n+1, padx=4, pady=3, sticky=W) self.screenshot[name] = Label(frame) self.screenshot[name].grid(column=2, row=1, rowspan=len(l), padx=4, pady=4)
def dialogRssWatchDBextender(dialog, frame, row, options, cntlr, openFileImage, openDatabaseImage): from tkinter import PhotoImage, N, S, E, W from tkinter.simpledialog import askstring from arelle.CntlrWinTooltip import ToolTip from arelle.UiUtil import gridCell, label try: from tkinter.ttk import Button except ImportError: from ttk import Button def enterConnectionString(): from arelle.DialogUserPassword import askDatabase # (user, password, host, port, database) db = askDatabase(cntlr.parent, dialog.cellDBconnection.value.split(',') if dialog.cellDBconnection.value else None) if db: dbConnectionString = ','.join(db) dialog.options["xbrlDBconnection"] = dbConnectionString dialog.cellDBconnection.setValue(dbConnectionString) else: # deleted dialog.options.pop("xbrlDBconnection", "") # remove entry label(frame, 1, row, "DB Connection:") dialog.cellDBconnection = gridCell(frame,2, row, options.get("xbrlDBconnection","")) ToolTip(dialog.cellDBconnection, text=_("Enter an XBRL Database (Postgres) connection string. " "E.g., host,port,user,password,db[,timeout]. "), wraplength=240) enterDBconnectionButton = Button(frame, image=openDatabaseImage, width=12, command=enterConnectionString) enterDBconnectionButton.grid(row=row, column=3, sticky=W)
def __init__(self, parent, process): super(ProcessWindow, self).__init__(parent) self.parent = parent self.process = process terminate_button = Button(self, text="cancel", command=self.cancel) terminate_button.grid(row=0, column=0) self.grab_set() # so you can't push submit multiple times
def sphinxDialogRssWatchFileChoices(dialog, frame, row, options, cntlr, openFileImage, openDatabaseImage, *args, **kwargs): from tkinter import PhotoImage, N, S, E, W try: from tkinter.ttk import Button except ImportError: from ttk import Button from arelle.CntlrWinTooltip import ToolTip from arelle.UiUtil import gridCell, label # add sphinx formulas to RSS dialog def chooseSphinxFiles(): sphinxFilesList = cntlr.uiFileDialog("open", multiple=True, # expect multiple sphinx files title=_("arelle - Select sphinx rules file"), initialdir=cntlr.config.setdefault("rssWatchSphinxRulesFilesDir","."), filetypes=[(_("Sphinx files .xsr"), "*.xsr"), (_("Sphinx archives .xrb"), "*.xrb")], defaultextension=".xsr") if sphinxFilesList: dialog.options["rssWatchSphinxRulesFilesDir"] = os.path.dirname(sphinxFilesList[0]) sphinxFilesPipeSeparated = '|'.join(sphinxFilesList) dialog.options["sphinxRulesFiles"] = sphinxFilesPipeSeparated dialog.cellSphinxFiles.setValue(sphinxFilesPipeSeparated) else: # deleted dialog.options.pop("sphinxRulesFiles", "") # remove entry label(frame, 1, row, "Sphinx rules:") dialog.cellSphinxFiles = gridCell(frame,2, row, options.get("sphinxRulesFiles","")) ToolTip(dialog.cellSphinxFiles, text=_("Select a sphinx rules (file(s) or archive(s)) to to evaluate each filing. " "The results are recorded in the log file. "), wraplength=240) chooseFormulaFileButton = Button(frame, image=openFileImage, width=12, command=chooseSphinxFiles) chooseFormulaFileButton.grid(row=row, column=3, sticky=W)
def create_widgets(self, clear_all_fnc): ''' Creates widgets of this frame. Args: clear_all_fnc (function): function that should be called when "Clear all" button is pressed. ''' rows_spinbox = Spinbox(self, from_=1, to=100, width=3, textvariable=self.row_str_var) rows_spinbox.grid(row=0, column=0, pady=3, padx=3) add_row_btn = Button(self, text='Add row(s)', command=self.add_rows) add_row_btn.grid(row=0, column=1, sticky=N+E+W, pady=3) remove_row_btn = Button(self, text='Remove row(s)', command=self.remove_rows) remove_row_btn.grid(row=1, column=1, sticky=N+E+W, pady=3) columns_spinbox = Spinbox(self, from_=1, to=100, width=3, textvariable=self.col_str_var) columns_spinbox.grid(row=2, column=0, pady=3, padx=3) add_column_btn = Button(self, text='Add column(s)', command=self.add_columns) add_column_btn.grid(row=2, column=1, sticky=N+E+W, pady=3) remove_column_btn = Button(self, text='Remove column(s)', command=self.remove_columns) remove_column_btn.grid(row=3, column=1, sticky=N+E+W, pady=3) clear_all_btn = Button(self, text='Clear all', command=clear_all_fnc) clear_all_btn.grid(row=4, column=1, sticky=N+E+W, pady=3)
class OkFrame(MessageFrame): def __init__(self, master, config): super(OkFrame, self).__init__(master, config) if config.full_screen: self._make_full(master) self.master.grid_rowconfigure(0, weight=1) self.master.grid_rowconfigure(1, weight=1) self.master.grid_columnconfigure(0, weight=1) self._frame_lbl = Label( self.master, text='', anchor='center', font=self._config.item_font ) self._frame_lbl.grid(row=0, column=0, sticky='snew') self._next_btn = Button( self.master, text='OK', command=self._next_cmd ) self._next_btn.grid(row=1, column=0, sticky='snew') def show(master, config, msg): new_window = Toplevel(master) dlg = OkFrame(new_window, config) dlg._frame_lbl['text'] = msg def _next_cmd(self): self._master.destroy()
class MainApplication(Frame): def __init__(self, parent, *args, **kwargs): Frame.__init__(self, parent, *args, **kwargs) self.parent = parent self.button = Button(self, text="start", command=self.callback) self.cancel = Button(self, text="cancel", command=self.cancel) self.button.grid(row=0, column=0) self.cancel.grid(row=0, column=1) self.is_canceled = False def check_status(self): if self.proc.is_alive(): self.after(100, self.check_status) elif self.is_canceled: messagebox.showinfo(message="canceled") else: messagebox.showinfo(message="finished" + int(self.result_queue.get())) def callback(self): self.result_queue = Queue() self.proc = CalculationProcess(self.result_queue) self.proc.start() self.after(10, self.check_status) def cancel(self): self.is_canceled = True self.proc.terminate()
def __init__(self, master, ordinances=False, **kwargs): super(Options, self).__init__(master, **kwargs) self.ancestors = IntVar() self.ancestors.set(4) self.descendants = IntVar() self.spouses = IntVar() self.ordinances = IntVar() self.contributors = IntVar() self.start_indis = StartIndis(self) self.fid = StringVar() btn = Frame(self) entry_fid = EntryWithMenu(btn, textvariable=self.fid, width=16) entry_fid.bind('<Key>', self.enter) label_ancestors = Label(self, text=_('Number of generations to ascend')) entry_ancestors = EntryWithMenu(self, textvariable=self.ancestors, width=5) label_descendants = Label(self, text=_('Number of generations to descend')) entry_descendants = EntryWithMenu(self, textvariable=self.descendants, width=5) btn_add_indi = Button(btn, text=_('Add a FamilySearch ID'), command=self.add_indi) btn_spouses = Checkbutton(self, text='\t' + _('Add spouses and couples information'), variable=self.spouses) btn_ordinances = Checkbutton(self, text='\t' + _('Add Temple information'), variable=self.ordinances) btn_contributors = Checkbutton(self, text='\t' + _('Add list of contributors in notes'), variable=self.contributors) self.start_indis.grid(row=0, column=0, columnspan=3) entry_fid.grid(row=0, column=0, sticky='w') btn_add_indi.grid(row=0, column=1, sticky='w') btn.grid(row=1, column=0, columnspan=2, sticky='w') entry_ancestors.grid(row=2, column=0, sticky='w') label_ancestors.grid(row=2, column=1, sticky='w') entry_descendants.grid(row=3, column=0, sticky='w') label_descendants.grid(row=3, column=1, sticky='w') btn_spouses.grid(row=4, column=0, columnspan=2, sticky='w') if ordinances: btn_ordinances.grid(row=5, column=0, columnspan=3, sticky='w') btn_contributors.grid(row=6, column=0, columnspan=3, sticky='w') entry_ancestors.focus_set()
def initUI(self, server): self.parent.title("TrackWise Service Manager") self.pack(fill=BOTH, expand = True, padx = 300) # self.centerWindow() menubar = Menu(self.parent) self.parent.config(menu = menubar) fileMenu = Menu(menubar) fileMenu.add_command(label = "Exit", command = self.onExit) menubar.add_cascade(label = "File", menu = fileMenu) svcsMenu = Menu(menubar) svcsMenu.add_command(label = "List Service Status", command = self.onStatus) svcsMenu.add_command(label = "Stop Services", command = self.onStop) svcsMenu.add_command(label = "Start Services", command = self.onStart) menubar.add_cascade(label = "Services", menu = svcsMenu) # svcs = ['TrackWise Tomcat', 'Web Services Tomcat', 'QMD Tomcat', 'Keystone Intake', 'ID Intake', 'TWC'] svcs = server.getservices() hostname = server.gethostname().strip() servertype = server.gettype().strip() frame0 = Labelframe(self, text = "Server Details", borderwidth = 1) frame0.grid(column = 0, row = 0, sticky = W) so = StringVar() svroverview = Message(frame0, textvariable = so, anchor = W, width = 300) svroverview.grid(column = 0, row = 0) sstr = "Server: {}\n".format(hostname) sstr += "Server Type: {}".format(servertype) so.set(sstr) frame1 = Labelframe(self, text = "Service Status", borderwidth = 1) frame1.grid(column = 0, row = 1, sticky = W) l = StringVar() label1 = Message(frame1, textvariable = l , anchor = W) svcscount = 0 lstr = "" for i in svcs: svcscount += 1 lstr += '{} - '.format(i) + ('UP\n' if svcscount % 2 else 'DOWN\n') l.set(lstr) label1.pack(side=TOP, padx = 5, pady = 5) frame4 = Frame(self, relief=RAISED, borderwidth = 1) frame4.grid(column = 0, row = 2, sticky = W) closeButton = Button(frame4, text="Close", command = self.quit) closeButton.grid(column = 0, row = 0) okButton = Button(frame4, text = "OK") okButton.grid(column = 1, row = 0)
def __init__(self, mainWin, options): self.mainWin = mainWin parent = mainWin.parent super(DialogNewFactItemOptions, self).__init__(parent) self.parent = parent self.options = options parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.accepted = False self.transient(self.parent) self.title(_("New Fact Item Options")) frame = Frame(self) label(frame, 1, 1, "Entity scheme:") self.cellEntityIdentScheme = gridCell(frame, 2, 1, getattr(options,"entityIdentScheme",""), width=50) ToolTip(self.cellEntityIdentScheme, text=_("Enter the scheme for the context entity identifier"), wraplength=240) label(frame, 1, 2, "Entity identifier:") self.cellEntityIdentValue = gridCell(frame, 2, 2, getattr(options,"entityIdentValue","")) ToolTip(self.cellEntityIdentValue, text=_("Enter the entity identifier value (e.g., stock ticker)"), wraplength=240) label(frame, 1, 3, "Start date:") startDate = getattr(options,"startDate",None) self.cellStartDate = gridCell(frame, 2, 3, XmlUtil.dateunionValue(startDate) if startDate else "") ToolTip(self.cellStartDate, text=_("Enter the start date for the report period (e.g., 2010-01-01)"), wraplength=240) label(frame, 1, 4, "End date:") endDate = getattr(options,"endDate",None) self.cellEndDate = gridCell(frame, 2, 4, XmlUtil.dateunionValue(endDate, subtractOneDay=True) if endDate else "") ToolTip(self.cellEndDate, text=_("Enter the end date for the report period (e.g., 2010-12-31)"), wraplength=240) label(frame, 1, 5, "Monetary unit:") self.cellMonetaryUnit = gridCombobox(frame, 2, 5, getattr(options,"monetaryUnit",""), values=monetaryUnits) ToolTip(self.cellMonetaryUnit, text=_("Select a monetary unit (e.g., EUR)"), wraplength=240) label(frame, 1, 6, "Monetary decimals:") self.cellMonetaryDecimals = gridCell(frame, 2, 6, getattr(options,"monetaryDecimals","2")) ToolTip(self.cellMonetaryDecimals, text=_("Enter decimals for monetary items"), wraplength=240) label(frame, 1, 7, "Non-monetary decimals:") self.cellNonMonetaryDecimals = gridCell(frame, 2, 7, getattr(options,"nonMonetaryDecimals","0")) ToolTip(self.cellNonMonetaryDecimals, text=_("Enter decimals for non-monetary items (e.g., stock shares)"), wraplength=240) cancelButton = Button(frame, text=_("Cancel"), width=8, command=self.close) ToolTip(cancelButton, text=_("Cancel operation, discarding changes and entries")) okButton = Button(frame, text=_("OK"), width=8, command=self.ok) ToolTip(okButton, text=_("Accept the options as entered above")) cancelButton.grid(row=8, column=1, columnspan=3, sticky=E, pady=3, padx=3) okButton.grid(row=8, column=1, columnspan=3, sticky=E, pady=3, padx=86) frame.grid(row=0, column=0, sticky=(N,S,E,W)) frame.columnconfigure(2, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100)) #self.bind("<Return>", self.ok) #self.bind("<Escape>", self.close) self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self)
class ListDialog(object): def __init__ (self, master, items, message, accept_func): self.accept_func = accept_func self.top = Toplevel(master) self.top.transient(master) self.top.rowconfigure(0, weight=1) self.top.rowconfigure(1, weight=3) self.top.rowconfigure(2, weight=0) self.top.columnconfigure(0, weight=1) self.top.columnconfigure(1, weight=1) self.top.resizable(width=True, height=True) self.frame = Frame(self.top) self.frame.rowconfigure(0, weight=1) self.frame.rowconfigure(1, weight=0) self.frame.columnconfigure(0, weight=1) self.frame.columnconfigure(1, weight=0) self.frame.grid(row=0, column=0, sticky=(N, S, W, E), columnspan=2) self.canvas = Canvas(self.frame) self.canvas.create_text(0, 0, text=message, anchor=NW) self.canvas.grid(row=0, column=0, sticky=(N, W, S, E)) self.vscroll = Scrollbar(self.frame, command=self.canvas.yview) self.vscroll.grid(row=0, column=1, sticky=(N, S)) self.canvas['yscrollcommand'] = self.vscroll.set self.hscroll = Scrollbar(self.frame, command=self.canvas.xview, orient=HORIZONTAL) self.hscroll.grid(row=1, column=0, sticky=(W, E), columnspan=2) self.canvas['xscrollcommand'] = self.hscroll.set self.canvas['scrollregion'] = self.canvas.bbox('all') self.canvas.bind('<Button-4>', self.scroll) self.canvas.bind('<Button-5>', self.scroll) self.canvas.bind('<MouseWheel>', self.scroll) self.view = NameView(self.top, sorted(items)) self.view.widget.grid(row=1, column=0, columnspan=2, sticky=(N, W, E, S)) self.delbutton = Button(self.top, text='Ok', command=self.accept ) self.cancelbutton = Button(self.top, text='Cancel', command=self.cancel) self.delbutton.grid(row=2, column=0) self.cancelbutton.grid(row=2, column=1) self.view.widget.focus_set() def accept(self): self.accept_func(self.view.selection()) self.top.destroy() def cancel(self): self.result = None self.top.destroy() def scroll(self, event): if event.num == 4 or event.delta > 0: self.canvas.yview(SCROLL, -1, UNITS) elif event.num == 5 or event.delta < 0: self.canvas.yview(SCROLL, 1, UNITS)
def make_button(self, label, command, isdef=0): "Return command button gridded in command frame." b = Button(self.buttonframe, text=label, command=command, default=isdef and "active" or "normal") cols,rows=self.buttonframe.grid_size() b.grid(pady=1,row=rows,column=0,sticky="ew") self.buttonframe.grid(rowspan=rows+1) return b
class ButtonFrame(Frame): def __init__(self, master): Frame.__init__(self, master, padding="0 0 0 13") Separator(self).grid(row=0, columnspan=2, pady="0 9", sticky=EW) self.button = Button(self, text="Close", command=master.destroy) self.button.grid(row=1, column=0, padx="15", sticky=E) self.grid(sticky=EW) self.columnconfigure(0, weight=1) def add_button(self, name, command): Button(self, text=name, command=command).grid(row=1, column=1, padx="0 15", sticky=E)
class CalculationFrame(LabelFrame): def __init__(self,parent): LabelFrame.__init__(self,parent,text="Calculate",borderwidth=5) self.startCalculationB = Button(self,text="Start calculation",width=20) self.startCalculationB.grid(row=0,column=0,padx=10,pady=5) self.endCalculationB = Button(self,text="Cancel calculation",width=20) self.endCalculationB.grid(row=1,column=0,padx=10,pady=5) self.calculationPB = Progressbar(self, mode="indeterminate",length=128) self.calculationPB.grid(row=2,column=0,padx=10,pady=5)
class ConfirmFrame(MessageFrame): def __init__(self, master, config): super(ConfirmFrame, self).__init__(master, config) if config.full_screen: self._make_full(master) self.master.grid_rowconfigure(0, weight=1) self.master.grid_rowconfigure(1, weight=1) self.master.grid_columnconfigure(0, weight=1) self.master.grid_columnconfigure(1, weight=1) self._result = False self._frame_lbl = Label( self.master, text='', anchor='center', font=self._config.item_font ) self._frame_lbl.grid(row=0, column=0, columnspan=2, sticky='snew') self._prev_btn = Button( self.master, text='Cancel', command=self._prev_cmd ) self._prev_btn.grid(row=1, column=0, sticky='snew') self._next_btn = Button( self.master, text='OK', command=self._next_cmd ) self._next_btn.grid(row=1, column=1, sticky='snew') def show(master, config, msg, ok_text, cancel_text): new_window = Toplevel(master) dlg = ConfirmFrame(new_window, config) dlg._frame_lbl['text'] = msg dlg._prev_btn['text'] = cancel_text dlg._next_btn['text'] = ok_text dlg.wait_window(new_window) return dlg._result def _prev_cmd(self): self._result = False self._master.destroy() def _next_cmd(self): self._result = True self._master.destroy()
def __init__(self, master): Frame.__init__(self, master) self.dir = master.dir self.manager = master.manager self.rows = [] for i, img in enumerate(f for f in listdir(master.dir) if f.endswith(PNG_SUFFIX)): button = Button(self) button.grid(row=i, column=2) row = Row(self, i, img, button) self.rows.append(row) Label(self, text=img).grid(row=i) Label(self, textvariable=row.status).grid(row=i, column=1)
def initUI(self): self.parent.title("Windows") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(6, weight=1) self.rowconfigure(5, pad=7) lbl = Label(self, text="BookManager") lbl.grid(sticky=W, pady=4, padx=5) self.area = Text(self) #WHITE TEXT BOX self.area.grid(row=1, column=0, columnspan=3, rowspan=4, padx=5, sticky=E+W+S+N) abtn = Button(self, text="add", command=self.press_add) abtn.grid(row=1, column=3) srcbtn = Button(self, text="search", command=self.press_search) srcbtn.grid(row=2, column=3, pady=3) rbtn = Button(self, text="remove", command=self.press_remove) rbtn.grid(row=3, column=3, pady=3) sbtn = Button(self, text="show all", command=self.press_show) sbtn.grid(row=4, column=3, pady=3)
def init_ui(self): self.parent.title("Papers") self.style = Style() self.style.theme_use("clam") frame = Frame(self, relief=RAISED, borderwidth=1) frame.grid(row=0, column=0) label = Label(frame, text="Change Wallpaper") label.grid(row=0, column=0) button = Button(frame, text="Change", command=self.change) button.grid(row=1, column=0) label = Label(frame, text="Fetch Wallpapers") label.grid(row=2, column=0) button = Button(frame, text="Fetch", command=self.fetch) button.grid(row=3, column=0)
def initUI(self): self.parent.title("Windows") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(3, weight=1) self.rowconfigure(5, pad=7) lbl = Label(self, text="Windows") lbl.grid(sticky=W, pady=4, padx=5) area = Text(self) area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N) abtn = Button(self, text="Activate") abtn.grid(row=1, column=3) cbtn = Button(self, text="Close") cbtn.grid(row=2, column=3, pady=4) hbtn = Button(self, text="Help") hbtn.grid(row=5, column=0, padx=5) obtn = Button(self, text="OK") obtn.grid(row=5, column=3)
def initUI(self): self.parent.title('OMX GUI') self.parent.bind("<Key>", self.keyEvt) # ---- STYLE ---- Style().theme_use('default') Style().configure("TFrame", background="white") Style().configure("TButton", font="12", padding=(5,1,5,1), background="#4285F4", foreground="white") Style().configure("TEntry", font="12", padding=(5,3,5,2)) Style().configure("TLabel", background="white") Style().map('TButton', foreground=[('pressed', 'white'), ('active', 'white')], background=[('pressed', '!disabled', '#3367d6'), ('active', '#3b78e7')], highlightcolor=[('focus','#4285F4')], relief=[('pressed', '!disabled', 'flat')]) Style().configure('Treeview', foreground='#333', background="white", highlightthickness='0') Style().map('Treeview', foreground=[('focus', '#000')], background=[('focus', '#F5F5F5')]) # ---- MENU ---- self.menubar = menubar = MenuBar(self, self.parent) # ---- TREE ---- self.filesTree = filesTree = FilesTree(self) self.filesTree.loadRecentFile() # ---- BUTTONS ---- bBrowse = Button(self, text=_("browse"), width="6", command=self.openVideo) bPlay = Button(self, text=_("play"), width="6", command=self.playVideo) # ---- GRID ---- self.grid(column=0, row=0, sticky=(N, E, W, S)) filesTree.grid(column=0, row=0, columnspan=2, rowspan=2, sticky=(N,W,E)) bBrowse.grid(column=0, row=2, sticky=(N,W)) bPlay.grid(column=0, row=2, sticky=(N,W), padx=70) self.parent.columnconfigure(0, weight=1) self.parent.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.columnconfigure(1, weight=1) self.rowconfigure(0, weight=1) self.rowconfigure(1, weight=1) self.centerWindow()
def __make_widgets(self): widgets = {} for index, editor_field in enumerate(self.editor_fields): label = Label(self, width=50, padding=5, text=editor_field.title()) combo = Combobox(self, width=100) widgets[editor_field] = {} widgets[editor_field]['label'] = label widgets[editor_field]['widget'] = combo label.grid(row=index, column=0) combo.grid(row=index, column=1) index += 1 label = Label(self, width=50, padding=5, text="Pictures") button = Button(self, text="...", command=self.__load_pictures) label.grid(row=index, column=0) button.grid(row=index, column=1) return widgets
def __init__(self, parent, url=None, buttonSEC=False, buttonRSS=False): super(DialogURL, self).__init__(parent) self.parent = parent parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.accepted = False self.url = None self.transient(self.parent) self.title("Enter URL") self.urlVar = StringVar() self.urlVar.set(url if url is not None else "http://") frame = Frame(self) urlLabel = Label(frame, text=_("URL:"), underline=0) urlEntry = Entry(frame, textvariable=self.urlVar, width=60) urlEntry.focus_set() okButton = Button(frame, text=_("OK"), command=self.ok) cancelButton = Button(frame, text=_("Cancel"), command=self.close) if buttonSEC: usSecButton = Button(frame, text=_("SEC search"), command=self.usSec) usSecButton.grid(row=1, column=1, sticky=W, pady=3) ToolTip(usSecButton, text=_("Opens US SEC Edgar Company Search (in web browser)\n\n" "(1) Find the company in web browser,\n" "(2) Click 'documents' button for desired filing,\n" "(3) Find 'data files' panel, instance document row, 'document' column,\n" "(4) On instance document file name, right-click browser menu: 'copy shortcut',\n" "(5) Come back to this dialog window,\n" "(6) Ctrl-v (paste) shortcut into above URL text box,\n" "(7) Click ok button to load instance document"), wraplength=480) if buttonRSS: rssButton = Button(frame, text=_("SEC RSS"), command=self.rssFeed) rssButton.grid(row=1, column=1, pady=3) ToolTip(rssButton, text=_("Opens current US SEC Edgar RSS feed"), wraplength=480) urlLabel.grid(row=0, column=0, sticky=W, pady=3, padx=3) urlEntry.grid(row=0, column=1, columnspan=3, sticky=EW, pady=3, padx=3) okButton.grid(row=1, column=2, sticky=E, pady=3) ToolTip(okButton, text=_("Opens above URL from web cache, downloading to cache if necessary"), wraplength=240) cancelButton.grid(row=1, column=3, sticky=EW, pady=3, padx=3) ToolTip(cancelButton, text=_("Cancel operation")) frame.grid(row=0, column=0, sticky=(N,S,E,W)) frame.columnconfigure(1, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100)) self.bind("<Alt-u>", lambda *ignore: urlEntry.focus_set()) self.bind("<Return>", self.ok) self.bind("<Escape>", self.close) self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self)
class MainApp(Frame): def __init__(self, parent, *args, **kwargs): super(MainApp, self).__init__(parent, *args, **kwargs) self.parent = parent self.button = Button(self, text="foo", command=self.callback) self.button.grid(row=0, column=0) def callback(self): try: proc = multiprocessing.Process(target=foo) process_window = ProcessWindow(self, proc) process_window.launch() except TerminatedProcess as e: messagebox.showinfo(title="canceled", message=e.error_str) else: messagebox.showinfo(message="sucessful run", title="Finished") finally: pass
def create_widgets(self): super().create_widgets() frame = self.frame pathlabel = Label(frame, anchor='w', justify='left', text='Help File Path: Enter URL or browse for file') self.pathvar = StringVar(self, self.filepath) self.path = Entry(frame, textvariable=self.pathvar, width=40) browse = Button(frame, text='Browse', width=8, command=self.browse_file) self.path_error = Label(frame, text=' ', foreground='red', font=self.error_font) pathlabel.grid(column=0, row=10, columnspan=3, padx=5, pady=[10,0], sticky=W) self.path.grid(column=0, row=11, columnspan=2, padx=5, sticky=W+E, pady=[10,0]) browse.grid(column=2, row=11, padx=5, sticky=W+S) self.path_error.grid(column=0, row=12, columnspan=3, padx=5, sticky=W+E)
class Application(Frame): """The main Tk application, a simple dialog.""" def __init__(self, master=None): super().__init__(master) self.badge = None self.grid() self.columnconfigure(0, minsize=200) self.columnconfigure(1, minsize=200) self.rowconfigure(0, minsize=300) self.rowconfigure(3, minsize=30) self.create_widgets() self.connect() def create_widgets(self): """Sets up dialog elements.""" self.select = tix.FileSelectBox(self, browsecmd=self.on_file_selected, pattern="*.fs", directory="forth") # self.select["textVariable"] = self.forth_file self.select.grid(row=0, columnspan=2, sticky='n' + 'w' + 'e') self.connect_btn = Button(self, text="Connect", command=self.toggle_connect) self.connect_btn.grid(row=1, column=0, columnspan=2) self.exec_btn = Button(self, text="Execute", command=self.send_file) self.exec_btn.state(["disabled"]) self.exec_btn.grid(row=2, column=0, sticky='w' + 'e', padx=5, pady=3) self.quit = Button(self, text="QUIT", command=self.master.destroy) self.quit.grid(row=2, column=1, sticky='w' + 'e', padx=5, pady=3) self.status_panel = Frame(self, relief="groove", borderwidth=3) self.status_panel.grid(row=3, columnspan=2, sticky='nwse') self.connect_status = Label(self.status_panel, text="Not Connected") self.connect_status.grid(row=0, padx=5, pady=5, sticky="w") if self.badge is not None: self.connect_btn.state(["disabled"]) self.connect_status.config(text="Connected: " + self.badge.os_device) def send_file(self, _retry=False): """Send the selected file to the badge.""" if self.badge: try: # oddly, very first set LED seems to not set correct color self.badge.led(0, 0, 128) self.badge.led(0, 0, 128) with open(self.select.cget("value"), 'r') as forthin: self.badge.forth_run(forthin.read()) time.sleep(1) # because forth_run() may be too fast self.badge.led(0, 128, 0) except IOError: if not _retry: self.connect() self.send_file(True) else: raise def toggle_connect(self): "If connected, disconnect, otherwise connect." if self.connect_btn.cget("text") == "Connect": self.connect() else: self.disconnect() def disconnect(self): "Disconnect from current badge." isinstance(self.badge, Badge) self.badge.close() self.badge = None self.connect_btn.config(text="Connect") self.connect_status.config(text="Not connected.") self.exec_btn.state(["disabled"]) def connect(self): """Attempt to connect to a badge; toggle Connect button if successful.""" try: self.badge = Badge() self.connect_status.config(text="Connected: " + self.badge.os_device) self.connect_btn.config(text="Disconnect") # enable "Execute" if file is selected self.on_file_selected(self.select.cget("value")) except BadgeSerialException: self.connect_status.config(text="Not connected") def on_file_selected(self, selected_file): """Respond to user selection of file by enabling the Execute button.""" if Path(selected_file).is_file: self.exec_btn.state(["!disabled"]) else: self.exec_btn.state(["disabled"])
class Example(Frame): # This is the URL to the defualt icon that will appear before any item is selected. defaultIconURL = "https://support.runescape.com/hc/article_attachments/360002434025/App_Icon-Circle.png" def __init__(self): super().__init__() self.initUI() def initUI(self): # Set the window title. self.master.title("OSRS Item Lookup") # Call the methods to center the window on screen & create grid within frame self.centerWindow() self.makeGrid() # Create all of the Label & Entry widgets contained within the frame self.nameLabel = Label(self, text="Name: ") self.name = Entry(self) self.descLabel = Label(self, text="Description: ") self.description = Entry(self) self.priceLabel = Label(self, text="Price: ") self.price = Entry(self) self.idLabel = Label(self, text="Item ID: ") self.itemID = Entry(self) # Setting the default icon image self.iconImg = self.getImage(self.defaultIconURL) self.icon = Label(self, image=self.iconImg) self.icon.image = self.iconImg # Creating the Button to fetch data via API. self.getData = Button(self, text="Get Data", command=lambda: self.getItem(self.itemID.get())) # Creating the frame that will contain MatPlotLib fig self.plotFrame = Frame(self) # Placing all of the widgets within the grid self.nameLabel.grid(row=0, columnspan=1, sticky='nsew') self.name.grid(row=0, column=1, columnspan=14, sticky='nsew') self.descLabel.grid(row=1, columnspan=1, sticky='nsew') self.description.grid(row=1, column=1, columnspan=14, sticky='nsew') self.icon.grid(row=0, column=15, rowspan=3, columnspan=5) self.priceLabel.grid(row=2, columnspan=1, sticky='nsew') self.price.grid(row=2, column=1, columnspan=14, sticky='nsew') self.idLabel.grid(row=19, columnspan=1, sticky='nsew') self.itemID.grid(row=19, column=1, columnspan=9, sticky='nsew') self.getData.grid(row=19, column=10, columnspan=10, sticky='nsew') self.plotFrame.grid(row=3, rowspan=16, columnspan=20, sticky='nsew') # Set the frame to expand and fill as the window is resized. self.pack(fill=BOTH, expand=1) # This method will create a plot based on data fed in as a dictionary. def plot(self, data): # Destory all the children in the plotFrame widget, this allows for the # plot to update whenver a new item is selected. for widget in self.plotFrame.winfo_children(): widget.destroy() # Place X & Y values into their own respective lists x = list(data.keys()) y = list(data.values()) # This is the starting day for the time data recieved from the server. # The time values in the server are represented as milliseconds from Jan. # 1, 1970. The following converts all of those times in milliseconds to a datetime. day = datetime.date(1970, 1, 1) x[:] = [ day + timedelta(days=(int(item) / ((1000 * 60 * 60 * 24)))) for item in x ] # Create and size the figure to the plotframe size. f = Figure(figsize=(self.plotFrame.winfo_width() / 100, self.plotFrame.winfo_height() / 100), dpi=100) # Add 1 subplot on a 1 x 1 grid. a = f.add_subplot(111) # Format x_axis date f.autofmt_xdate() # Plot date and price values a.plot(x, y) # Create canvas for figure to reside on, set parent to plot frame, then # Draw the canvas and pack it in plotFrame. self.canvas = FigureCanvasTkAgg(f, self.plotFrame) self.canvas.draw() self.canvas.get_tk_widget().pack(fill=BOTH, expand=1) # This method interfaces with the OSRS API and retrieves data, updates data # in GUI. def getItem(self, itemIDNum): # Create new instance of Item with provided ID number. newItem = osrs_api.Item(itemIDNum) # Clear out the entry widgets if anything is any them. self.name.delete(0, END) self.description.delete(0, END) self.price.delete(0, END) # Insert the name, description and price of item in entry widgets. self.name.insert(0, newItem.getName()) self.description.insert(0, newItem.getDescription()) self.price.insert(0, newItem.getCurrentPrice()) # Get the items icon url and set the icon to the new items image. self.iconImg2 = self.getImage(newItem.getLargeIconURL()) self.icon.configure(image=self.iconImg2) self.icon.image = self.iconImg2 # Call the plot method with the new items daily price data self.plot(newItem.getGraphData()['daily']) def centerWindow(self): sw = self.master.winfo_screenwidth() sh = self.master.winfo_screenheight() w = sw / 2 h = 0.75 * sh x = (sw - w) / 2 y = (sh - h) / 2 self.master.geometry('%dx%d+%d+%d' % (w, h, x, y)) def makeGrid(self): for x in range(0, 20): self.columnconfigure(x, weight=1) for i in range(0, 20): self.rowconfigure(i, weight=1, minsize=20) def getImage(self, URL): imageRequest = requests.get(URL) return ImageTk.PhotoImage( Image.open(BytesIO(imageRequest.content)).resize((97, 97)))
def __init__(self, parent, openType, filesource, filenames, title, colHeader, showAltViewButton=False): if isinstance(parent, Cntlr): cntlr = parent parent = parent.parent # parent is cntlrWinMain else: # parent is a Toplevel dialog cntlr = parent.cntlr super(DialogOpenArchive, self).__init__(parent) self.parent = parent self.showAltViewButton = showAltViewButton parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.accepted = False self.transient(self.parent) frame = Frame(self) treeFrame = Frame(frame, width=500) vScrollbar = Scrollbar(treeFrame, orient=VERTICAL) hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL) self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set) self.treeView.grid(row=0, column=0, sticky=(N, S, E, W)) hScrollbar["command"] = self.treeView.xview hScrollbar.grid(row=1, column=0, sticky=(E, W)) vScrollbar["command"] = self.treeView.yview vScrollbar.grid(row=0, column=1, sticky=(N, S)) treeFrame.columnconfigure(0, weight=1) treeFrame.rowconfigure(0, weight=1) treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.treeView.focus_set() if openType != PLUGIN: cntlr.showStatus(_("loading archive {0}").format(filesource.url)) self.filesource = filesource self.filenames = filenames self.selection = filesource.selection self.hasToolTip = False selectedNode = None if openType == ENTRY_POINTS: try: metadataFiles = filesource.taxonomyPackageMetadataFiles ''' take first for now if len(metadataFiles) != 1: raise IOError(_("Taxonomy package contained more than one metadata file: {0}.") .format(', '.join(metadataFiles))) ''' metadataFile = metadataFiles[0] metadata = filesource.url + os.sep + metadataFile self.metadataFilePrefix = os.sep.join( os.path.split(metadataFile)[:-1]) if self.metadataFilePrefix: self.metadataFilePrefix += "/" # zip contents have /, never \ file seps self.taxonomyPkgMetaInf = '{}/META-INF/'.format( os.path.splitext(os.path.basename(filesource.url))[0]) self.taxonomyPackage = parsePackage( cntlr, filesource, metadata, os.sep.join(os.path.split(metadata)[:-1]) + os.sep) # may be a catalog file with no entry oint names if not self.taxonomyPackage["nameToUrls"]: openType = ARCHIVE # no entry points to show, just archive self.showAltViewButton = False except Exception as e: self.close() err = _( "Failed to parse metadata; the underlying error was: {0}" ).format(e) messagebox.showerror(_("Malformed taxonomy package"), err) cntlr.addToLog(err) return if openType != PLUGIN: cntlr.showStatus(None) if openType in (DISCLOSURE_SYSTEM, PLUGIN): y = 3 else: y = 1 okButton = Button(frame, text=_("OK"), command=self.ok) cancelButton = Button(frame, text=_("Cancel"), command=self.close) okButton.grid(row=y, column=2, sticky=(S, E, W), pady=3) cancelButton.grid(row=y, column=3, sticky=(S, E, W), pady=3, padx=3) if self.showAltViewButton: self.altViewButton = Button(frame, command=self.showAltView) self.altViewButton.grid(row=y, column=0, sticky=(S, W), pady=3, padx=3) self.loadTreeView(openType, colHeader, title) self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100)) frame.grid(row=0, column=0, sticky=(N, S, E, W)) frame.columnconfigure(0, weight=1) frame.rowconfigure(0, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) window.rowconfigure(0, weight=1) self.bind("<Return>", self.ok) self.bind("<Escape>", self.close) self.toolTipText = StringVar() if self.hasToolTip: self.treeView.bind("<Motion>", self.motion, '+') self.treeView.bind("<Leave>", self.leave, '+') self.toolTipText = StringVar() self.toolTip = ToolTip(self.treeView, textvariable=self.toolTipText, wraplength=640, follow_mouse=True, state="disabled") self.toolTipRowId = None self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self)
def __init__(self, parent=None): super().__init__(parent) parent.bind('<Return>', self.on_accept_button_click) self.pack(side=LEFT, fill=BOTH, expand=True) self.columnconfigure(0, weight=1) self.rowconfigure(1, weight=1) style = AppStyle() style.configure("SELF.TLabel", width=15) style.configure("SELF.TEntry", width=200, padding=5) style.configure("SELF.TMenubutton", width=200, padding=5) # Tab container. notebook = Notebook(self) # Main tab content main = Frame(notebook) main.columnconfigure(1, weight=1) screen_label = Label(main, text="Screen", style="SELF.TLabel") screen_label.grid(row=0, column=0, padx=[10, 0], pady=[10, 0], sticky=W) self.screen_entry = Entry(main, style="SELF.TEntry") self.screen_entry.grid(row=0, column=1, padx=[0, 10], pady=[10, 0], sticky=W + E) width_label = Label(main, text="Width percent", style="SELF.TLabel") width_label.grid(row=1, column=0, padx=[10, 0], pady=[5, 0], sticky=W) self.width_entry = Entry(main, style="SELF.TEntry") self.width_entry.grid(row=1, column=1, padx=[0, 10], pady=[5, 0], sticky=W + E) height_label = Label(main, text="Height percent", style="SELF.TLabel") height_label.grid(row=2, column=0, padx=[10, 0], pady=[5, 0], sticky=W) self.height_entry = Entry(main, style="SELF.TEntry") self.height_entry.grid(row=2, column=1, padx=[0, 10], pady=[5, 0], sticky=W + E) camera_type_label = Label(main, text="Camera type", style="SELF.TLabel") camera_type_label.grid(row=3, column=0, padx=[10, 0], pady=[5, 10], sticky=W) self.camera_type_entry = Entry(main, style="SELF.TEntry") self.camera_type_entry.grid(row=3, column=1, padx=[0, 10], pady=[5, 10], sticky=W + E) # Frames tab content. frames = Frame(notebook) frames.columnconfigure(1, weight=1) frame_interval_label = Label(frames, text="Frame interval", style="SELF.TLabel") frame_interval_label.grid(row=0, column=0, padx=[10, 0], pady=[10, 0], sticky=W) self.frame_interval_entry = Entry(frames, style="SELF.TEntry") self.frame_interval_entry.grid(row=0, column=1, padx=[0, 10], pady=[10, 0], sticky=W + E) frame_rate_label = Label(frames, text="Frame rate", style="SELF.TLabel") frame_rate_label.grid(row=1, column=0, padx=[10, 0], pady=[10, 0], sticky=W) self.frame_rate_entry = Entry(frames, style="SELF.TEntry") self.frame_rate_entry.grid(row=1, column=1, padx=[0, 10], pady=[10, 0], sticky=W + E) frame_count_label = Label(frames, text="Frame count", style="SELF.TLabel") frame_count_label.grid(row=2, column=0, padx=[10, 0], pady=[10, 0], sticky=W) self.frame_count_entry = Entry(frames, style="SELF.TEntry") self.frame_count_entry.grid(row=2, column=1, padx=[0, 10], pady=[10, 0], sticky=W + E) # Cameras tab content. cameras = Frame(notebook) cameras.columnconfigure(1, weight=1) camera_label = Label(cameras, text="Cameras", style="SELF.TLabel") camera_label.grid(row=0, column=0, padx=[10, 0], pady=[10, 0], sticky=W) self.selected_camera_var = StringVar(self) self.selected_camera_var.trace('w', self.on_camera_option_select) self.cameras_options = OptionMenu(cameras, self.selected_camera_var, style="SELF.TMenubutton") self.cameras_options.grid(row=0, column=1, padx=[0, 10], pady=[10, 0], sticky=E) add_cam_button = Button(cameras, text="Add", width=5, command=self.on_add_cam_button_click) add_cam_button.grid(row=0, column=2, padx=[0, 10], pady=[10, 0], sticky=E) delete_cam_button = Button(cameras, text="Delete", width=5, command=self.on_delete_cam_button_click) delete_cam_button.grid(row=0, column=3, padx=[0, 10], pady=[10, 0], sticky=E) self.edit_cam_entry = Entry(cameras, style="SELF.TEntry") self.edit_cam_entry.grid(row=1, column=0, columnspan=3, padx=10, pady=[5, 0], sticky=W + E) edit_cam_button = Button(cameras, text="Edit", width=5, command=self.on_edit_cam_button_click) edit_cam_button.grid(row=1, column=2, columnspan=2, padx=[0, 10], pady=[5, 0], sticky=E) # Add the tabs. notebook.add(main, text="Main") notebook.add(frames, text="Frames") notebook.add(cameras, text="Cameras") notebook.grid(row=0, column=0, columnspan=4, padx=10, pady=10, sticky=W + E) accept_button = Button(self, text="Accept") accept_button.grid(row=1, column=1, padx=[0, 10], sticky=N + E) accept_button.bind("<Button-1>", self.on_accept_button_click) default_button = Button(self, text="Default") default_button.grid(row=1, column=2, padx=[0, 10], sticky=N + E) default_button.bind("<Button-1>", self.on_default_button_click) cancel_button = Button(self, text="Cancel") cancel_button.grid(row=1, column=3, padx=[0, 10], sticky=N + E) cancel_button.bind("<Button-1>", self.on_cancel_button_click) # Load configuration. self.load_config()
class signUpPage(Frame): ''' The user is taken to this Frame if they choose to sign up this class implements the Frame Class in Tkinter and contains the required functions that will allow it to work well in this project ''' def __init__(self, parent, main, **kw): Frame.__init__(self, parent, **kw) self.main = main self.label_head = Label(text='Sign Up Page', font=MED_FONT) self.l_user = Label(text='Username') self.user = Entry(text='must have atleast 5 chars') self.l_pass = Label(text='Password') self.l_pass2 = Label(text='re-enter') self.password = Entry(show='*') self.password2 = Entry(show='*') self.sign_up_b = Button(text='Sign Up', command=lambda: self.sign_up(main)) self.back_b = Button( text='Back', command=lambda: self.main.show_frame(LOGIN_PAGE, SIGN_UP_PAGE)) self.age = BooleanVar() self.age_c = Checkbutton(text='Are you above 16 years of age', variable=self.age, onvalue=True, offvalue=False) self.balance = BooleanVar() self.balance_c = Checkbutton( text='Do you have 10000 rupees in \nyour bank account', variable=self.balance, onvalue=True, offvalue=False) def showItems(self, main): self.label_head.grid(column=0, row=0, columnspan=2) self.l_user.grid(column=0, row=1) self.user.grid(column=1, row=1) self.l_pass.grid(column=0, row=2) self.l_pass2.grid(column=0, row=3) self.password.grid(column=1, row=2) self.password2.grid(column=1, row=3) self.age_c.grid(column=0, columnspan=2, row=4) self.balance_c.grid(column=0, columnspan=2, row=5) self.sign_up_b.grid(column=0, row=6, columnspan=2) self.back_b.grid(column=0, row=7, columnspan=2) def hideItems(self, main): self.label_head.grid_forget() self.l_user.grid_forget() self.user.grid_forget() self.l_pass.grid_forget() self.l_pass2.grid_forget() self.password.grid_forget() self.password2.grid_forget() self.sign_up_b.grid_forget() self.back_b.grid_forget() self.age_c.grid_forget() self.balance_c.grid_forget() def sign_up(self, main): ''' Similar to the login check function it does the necessary checks to make sure that a person actually is above 18 (not really) and has the required amount of money to open an account on this platform also it creates pop ups when ever an exceptional circumstance is reached ''' password1 = self.password.get() password2 = self.password2.get() username = self.user.get() bool1 = username not in main.users_dict.keys() bool2 = (password1 == password2) bool3 = len(password1) >= 5 bool4 = username == 'admin' bool5 = self.age.get() bool6 = self.balance.get() if not bool1: num = str(randint(100, 999)) showinfo(message='Username already exists, try: ' + username + num) self.password.delete(0, END) self.password2.delete(0, END) elif not bool2: showinfo(message='Passwords dont match') self.password.delete(0, END) self.password2.delete(0, END) elif not bool3: showinfo(message='Password must be more than 5 characters') self.password.delete(0, END) self.password2.delete(0, END) elif bool4: showinfo(message='Please don\'t use that username it is reserved') elif not bool5: showinfo(message='You must be 16 years or older to join') elif not bool6: showinfo(message='You need to have 10000 to create an account') else: buff = [] for name in main.shares_dict.keys(): temp = {} temp['name'] = name temp['tot_owned'] = '0' temp['money_spent'] = '0' buff.append(temp) self.main.users_dict[username] = buff self.main.pass_dict[username] = bytes(password1, 'utf-8') k = getData.key() self.main.pass_dict2[username] = encode(bytes(password1, 'utf-8')) self.main.accounts[username] = { 'balance': str(10**4), 'profit': '0' } self.main.present_user = username self.main.p_user_dict = self.main.users_dict[username] self.main.login = True self.main.show_frame(VIEW_STOCK, SIGN_UP_PAGE) self.password.delete(0, END) self.password2.delete(0, END) self.user.delete(0, END)
field_label = Label(field_frame, text="Class") add_class_field = Entry(field_frame) # add_class_btn = Button(add_class_btn_frame, text="Add Class", command=add_class) btn_execute = Button(btn_group_frame, text="Browse and Execute", width=25, style='execute_btn.TButton', command=add_class) # btn_cancel = Button(btn_group_frame, text="Cancel", width=25, style='cancel_btn.TButton') # progress = Progressbar(execute_info_frame, length=400 ,mode='indeterminate', orient=HORIZONTAL) # exit_btn = Button(exit_btn_frame, text="Quit", width=30) # specifying rows and columns # label_file_explorer.grid(column=0, row=0) btn_execute.grid(column=0, row=1) field_label.grid(column=0, row=2, padx=15) add_class_field.grid(column=1, row=2) # btn_cancel.grid(column=1, row=0, padx=15) # progress.grid(column=0, row=0) #style s.configure('execute_btn.TButton', background='blue') # s.configure('cancel_btn.TButton', background='red') # show_img = cv2.imshow("Deteksi Gambar Balon", img) # key = cv2.waitKey(0)
def initUI(self): self.master.title("Calculator") Style().configure("TButton", padding=(0, 5, 0, 5), font='sans-serif 12') self.columnconfigure(0, pad=3) self.columnconfigure(1, pad=3) self.columnconfigure(2, pad=3) self.columnconfigure(3, pad=3) self.rowconfigure(0, pad=3) self.rowconfigure(1, pad=3) self.rowconfigure(2, pad=3) self.rowconfigure(3, pad=3) self.rowconfigure(4, pad=3) self.entry.grid(row=0, columnspan=4, sticky=W + E) cls = Button(self, text="Cls", command=self.clear_btn) cls.grid(row=1, column=0) bck = Button(self, text="Back", command=self.del_btn) bck.grid(row=1, column=1) lbl = Button(self) lbl.grid(row=1, column=2) clo = Button(self, text="Close", command=self.quit) clo.grid(row=1, column=3) sev = Button(self, text="7", command=lambda: self.number_btn_click(7)) sev.grid(row=2, column=0) eig = Button(self, text="8", command=lambda: self.number_btn_click(8)) eig.grid(row=2, column=1) nin = Button(self, text="9", command=lambda: self.number_btn_click(9)) nin.grid(row=2, column=2) div = Button(self, text="/", command=self.divide_btn_click) div.grid(row=2, column=3) fou = Button(self, text="4", command=lambda: self.number_btn_click(4)) fou.grid(row=3, column=0) fiv = Button(self, text="5", command=lambda: self.number_btn_click(5)) fiv.grid(row=3, column=1) six = Button(self, text="6", command=lambda: self.number_btn_click(6)) six.grid(row=3, column=2) mul = Button(self, text="*", command=self.multiply_btn_click) mul.grid(row=3, column=3) one = Button(self, text="1", command=lambda: self.number_btn_click(1)) one.grid(row=4, column=0) two = Button(self, text="2", command=lambda: self.number_btn_click(2)) two.grid(row=4, column=1) thr = Button(self, text="3", command=lambda: self.number_btn_click(3)) thr.grid(row=4, column=2) mns = Button(self, text="-", command=self.minus_btn_click) mns.grid(row=4, column=3) zer = Button(self, text="0", command=lambda: self.number_btn_click(0)) zer.grid(row=5, column=0) dot = Button(self, text=".", command=lambda: self.number_btn_click('.')) dot.grid(row=5, column=1) equ = Button(self, text="=", command=self.equals_btn) equ.grid(row=5, column=2) pls = Button(self, text="+", command=self.plus_btn_click) pls.grid(row=5, column=3) self.pack()
class MinutiaeEditorFrame(NotebookTabBase): # TODO: I'd like to remove the <minutiae> parameter def __init__(self, parent, load_fingerprint_func, load_minutiae_func, save_minutiae_file): super(self.__class__, self).__init__(parent, load_fingerprint_func) self.root = parent self.minutiae_count = StringVar() self._update_minutiae_count() self.current_minutiae = None self.load_minutiae_btn = Button(self, text="Load Minutiae", command=load_minutiae_func) self.load_minutiae_btn.grid(row=1, column=0, sticky=N + W + E) self.export_minutiae_btn = Button(self, text="Export Minutiae", command=save_minutiae_file) self.export_minutiae_btn.grid(row=2, column=0, sticky=N + W + E) self.info_frame = InfoFrame(self, "Info", self.minutiae_count) self.info_frame.grid(row=3, column=0, padx=4, sticky=N + W + E) @overrides def load_fingerprint_image(self, image): self._update_minutiae_count() @overrides def load_minutiae_file(self): self._update_minutiae_count() def _update_minutiae_count(self): self.minutiae_count.set("Minutiae: {}".format( self.root.number_of_minutiae())) @overrides def on_canvas_mouse_left_click(self, event): """ Adds a new bifurcation at the mouse click. """ x, y = event.x, event.y if not self.root.is_point_in_canvas_image(x, y): return self.current_minutiae = ((x, y), MinutiaType.RIDGE_ENDING) @overrides def on_canvas_ctrl_mouse_left_click(self, event): """ Adds a new ridge ending at the mouse click. """ x, y = event.x, event.y if not self.root.is_point_in_canvas_image(x, y): return self.current_minutiae = ((x, y), MinutiaType.BIFURCATION) @overrides def on_canvas_mouse_right_click(self, event): """ Removes a minutiae close to the mouse click. """ x, y = event.x, event.y if not self.root.is_point_in_canvas_image(x, y): return scale_factor = self.root.canvas_image_scale_factor() x, y = x * scale_factor, y * scale_factor possible_minutiae = [] for i in range(self.root.number_of_minutiae()): m = self.root.minutiae[i] dist = abs(m.x - x) + abs(m.y - y) if dist < 10: possible_minutiae.append((dist, i)) # Sort ascending, in-place. possible_minutiae.sort(key=lambda tup: tup[0]) if len(possible_minutiae) == 0: return else: del self.root.minutiae[possible_minutiae[0][1]] self.root.draw_minutiae() self._update_minutiae_count() @overrides def on_canvas_mouse_left_drag(self, event): """ Sets the angle of the minutiae being placed. """ x, y = event.x, event.y ((sx, sy), minutiae_type) = self.current_minutiae angle = math.degrees(math.atan2(y - sy, x - sx)) + 90 minutia = Minutia(round(sx), round(sy), angle, minutiae_type, 1.0) self.root.draw_single_minutia(minutia) @overrides def on_canvas_mouse_left_release(self, event): """ Places the minutiae currently being edited.. """ x, y = event.x, event.y scale_factor = self.root.canvas_image_scale_factor() ((px, py), minutiae_type) = self.current_minutiae angle = math.degrees(math.atan2(y - py, x - px)) + 90 self.root.minutiae.append( Minutia(round(px * scale_factor), round(py * scale_factor), angle, minutiae_type, 1.0)) self.current_minutiae = None self.root.draw_minutiae() self._update_minutiae_count()
class GetKeysDialog(Toplevel): # Dialog title for invalid key sequence keyerror_title = 'Key Sequence Error' def __init__(self, parent, title, action, current_key_sequences, *, _htest=False, _utest=False): """ parent - parent of this dialog title - string which is the title of the popup dialog action - string, the name of the virtual event these keys will be mapped to current_key_sequences - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest _utest - bool, do not wait when running unittest """ Toplevel.__init__(self, parent) self.withdraw() # Hide while setting geometry. self.configure(borderwidth=5) self.resizable(height=False, width=False) self.title(title) self.transient(parent) self.grab_set() self.protocol("WM_DELETE_WINDOW", self.cancel) self.parent = parent self.action = action self.current_key_sequences = current_key_sequences self.result = '' self.key_string = StringVar(self) self.key_string.set('') # Set self.modifiers, self.modifier_label. self.set_modifiers_for_platform() self.modifier_vars = [] for modifier in self.modifiers: variable = StringVar(self) variable.set('') self.modifier_vars.append(variable) self.advanced = False self.create_widgets() self.update_idletasks() self.geometry( "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width()/2 - self.winfo_reqwidth()/2), parent.winfo_rooty() + ((parent.winfo_height()/2 - self.winfo_reqheight()/2) if not _htest else 150) ) ) # Center dialog over parent (or below htest box). if not _utest: self.deiconify() # Geometry set, unhide. self.wait_window() def showerror(self, *args, **kwargs): # Make testing easier. Replace in #30751. messagebox.showerror(*args, **kwargs) def create_widgets(self): self.frame = frame = Frame(self, borderwidth=2, relief='sunken') frame.pack(side='top', expand=True, fill='both') frame_buttons = Frame(self) frame_buttons.pack(side='bottom', fill='x') self.button_ok = Button(frame_buttons, text='OK', width=8, command=self.ok) self.button_ok.grid(row=0, column=0, padx=5, pady=5) self.button_cancel = Button(frame_buttons, text='Cancel', width=8, command=self.cancel) self.button_cancel.grid(row=0, column=1, padx=5, pady=5) # Basic entry key sequence. self.frame_keyseq_basic = Frame(frame, name='keyseq_basic') self.frame_keyseq_basic.grid(row=0, column=0, sticky='nsew', padx=5, pady=5) basic_title = Label(self.frame_keyseq_basic, text=f"New keys for '{self.action}' :") basic_title.pack(anchor='w') basic_keys = Label(self.frame_keyseq_basic, justify='left', textvariable=self.key_string, relief='groove', borderwidth=2) basic_keys.pack(ipadx=5, ipady=5, fill='x') # Basic entry controls. self.frame_controls_basic = Frame(frame) self.frame_controls_basic.grid(row=1, column=0, sticky='nsew', padx=5) # Basic entry modifiers. self.modifier_checkbuttons = {} column = 0 for modifier, variable in zip(self.modifiers, self.modifier_vars): label = self.modifier_label.get(modifier, modifier) check = Checkbutton(self.frame_controls_basic, command=self.build_key_string, text=label, variable=variable, onvalue=modifier, offvalue='') check.grid(row=0, column=column, padx=2, sticky='w') self.modifier_checkbuttons[modifier] = check column += 1 # Basic entry help text. help_basic = Label(self.frame_controls_basic, justify='left', text="Select the desired modifier keys\n"+ "above, and the final key from the\n"+ "list on the right.\n\n" + "Use upper case Symbols when using\n" + "the Shift modifier. (Letters will be\n" + "converted automatically.)") help_basic.grid(row=1, column=0, columnspan=4, padx=2, sticky='w') # Basic entry key list. self.list_keys_final = Listbox(self.frame_controls_basic, width=15, height=10, selectmode='single') self.list_keys_final.insert('end', *AVAILABLE_KEYS) self.list_keys_final.bind('<ButtonRelease-1>', self.final_key_selected) self.list_keys_final.grid(row=0, column=4, rowspan=4, sticky='ns') scroll_keys_final = Scrollbar(self.frame_controls_basic, orient='vertical', command=self.list_keys_final.yview) self.list_keys_final.config(yscrollcommand=scroll_keys_final.set) scroll_keys_final.grid(row=0, column=5, rowspan=4, sticky='ns') self.button_clear = Button(self.frame_controls_basic, text='Clear Keys', command=self.clear_key_seq) self.button_clear.grid(row=2, column=0, columnspan=4) # Advanced entry key sequence. self.frame_keyseq_advanced = Frame(frame, name='keyseq_advanced') self.frame_keyseq_advanced.grid(row=0, column=0, sticky='nsew', padx=5, pady=5) advanced_title = Label(self.frame_keyseq_advanced, justify='left', text=f"Enter new binding(s) for '{self.action}' :\n" + "(These bindings will not be checked for validity!)") advanced_title.pack(anchor='w') self.advanced_keys = Entry(self.frame_keyseq_advanced, textvariable=self.key_string) self.advanced_keys.pack(fill='x') # Advanced entry help text. self.frame_help_advanced = Frame(frame) self.frame_help_advanced.grid(row=1, column=0, sticky='nsew', padx=5) help_advanced = Label(self.frame_help_advanced, justify='left', text="Key bindings are specified using Tkinter keysyms as\n"+ "in these samples: <Control-f>, <Shift-F2>, <F12>,\n" "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n" "Upper case is used when the Shift modifier is present!\n\n" + "'Emacs style' multi-keystroke bindings are specified as\n" + "follows: <Control-x><Control-y>, where the first key\n" + "is the 'do-nothing' keybinding.\n\n" + "Multiple separate bindings for one action should be\n"+ "separated by a space, eg., <Alt-v> <Meta-v>." ) help_advanced.grid(row=0, column=0, sticky='nsew') # Switch between basic and advanced. self.button_level = Button(frame, command=self.toggle_level, text='<< Basic Key Binding Entry') self.button_level.grid(row=2, column=0, stick='ew', padx=5, pady=5) self.toggle_level() def set_modifiers_for_platform(self): """Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn't matter if the keyboard has these keys; it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering. """ if sys.platform == "darwin": self.modifiers = ['Shift', 'Control', 'Option', 'Command'] else: self.modifiers = ['Control', 'Alt', 'Shift'] self.modifier_label = {'Control': 'Ctrl'} # Short name. def toggle_level(self): "Toggle between basic and advanced keys." if self.button_level.cget('text').startswith('Advanced'): self.clear_key_seq() self.button_level.config(text='<< Basic Key Binding Entry') self.frame_keyseq_advanced.lift() self.frame_help_advanced.lift() self.advanced_keys.focus_set() self.advanced = True else: self.clear_key_seq() self.button_level.config(text='Advanced Key Binding Entry >>') self.frame_keyseq_basic.lift() self.frame_controls_basic.lift() self.advanced = False def final_key_selected(self, event=None): "Handler for clicking on key in basic settings list." self.build_key_string() def build_key_string(self): "Create formatted string of modifiers plus the key." keylist = modifiers = self.get_modifiers() final_key = self.list_keys_final.get('anchor') if final_key: final_key = translate_key(final_key, modifiers) keylist.append(final_key) self.key_string.set(f"<{'-'.join(keylist)}>") def get_modifiers(self): "Return ordered list of modifiers that have been selected." mod_list = [variable.get() for variable in self.modifier_vars] return [mod for mod in mod_list if mod] def clear_key_seq(self): "Clear modifiers and keys selection." self.list_keys_final.select_clear(0, 'end') self.list_keys_final.yview('moveto', '0.0') for variable in self.modifier_vars: variable.set('') self.key_string.set('') def ok(self, event=None): keys = self.key_string.get().strip() if not keys: self.showerror(title=self.keyerror_title, parent=self, message="No key specified.") return if (self.advanced or self.keys_ok(keys)) and self.bind_ok(keys): self.result = keys self.grab_release() self.destroy() def cancel(self, event=None): self.result = '' self.grab_release() self.destroy() def keys_ok(self, keys): """Validity check on user's 'basic' keybinding selection. Doesn't check the string produced by the advanced dialog because 'modifiers' isn't set. """ final_key = self.list_keys_final.get('anchor') modifiers = self.get_modifiers() title = self.keyerror_title key_sequences = [key for keylist in self.current_key_sequences for key in keylist] if not keys.endswith('>'): self.showerror(title, parent=self, message='Missing the final Key') elif (not modifiers and final_key not in FUNCTION_KEYS + MOVE_KEYS): self.showerror(title=title, parent=self, message='No modifier key(s) specified.') elif (modifiers == ['Shift']) \ and (final_key not in FUNCTION_KEYS + MOVE_KEYS + ('Tab', 'Space')): msg = 'The shift modifier by itself may not be used with'\ ' this key symbol.' self.showerror(title=title, parent=self, message=msg) elif keys in key_sequences: msg = 'This key combination is already in use.' self.showerror(title=title, parent=self, message=msg) else: return True return False def bind_ok(self, keys): "Return True if Tcl accepts the new keys else show message." try: binding = self.bind(keys, lambda: None) except TclError as err: self.showerror( title=self.keyerror_title, parent=self, message=(f'The entered key sequence is not accepted.\n\n' f'Error: {err}')) return False else: self.unbind(keys, binding) return True
def __init__(self): tkinter.Tk.__init__(self) # Menu Setup menuBar = Menu(self) fileMenu = Menu(menuBar, tearoff=False) fileMenu.add_command(label="Open...", command=self.loadSequence) fileMenu.add_command(label="Close", command=self.closeSequence) fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self.destroy) aboutMenu = Menu(menuBar, tearoff=False) aboutMenu.add_command(label="Help", command=self.showHelp) aboutMenu.add_command(label="About...", command=self.showAbout) menuBar.add_cascade(label="File", menu=fileMenu) menuBar.add_cascade(label="About", menu=aboutMenu) # Window Setup self.title("Rotostitch " + __version__) self.config(menu=menuBar) self.iconbitmap(default=os.path.join(RESOURCE_DIR, "rotostitch-icon.ico")) masterFrame = Frame(self) masterFrame.pack(expand=1, fill=Tkc.BOTH, padx=2, pady=2) self.status = StatusBar(self) self.status.pack(anchor=Tkc.W, fill=Tkc.X, side=Tkc.BOTTOM) # Image review panels frame imgFrame = Frame(masterFrame, borderwidth=2, relief=Tkc.GROOVE) imgFrame.pack(expand=1, fill=Tkc.BOTH) imgFrame.columnconfigure(0, weight=1) imgFrame.columnconfigure(1, weight=0) imgFrame.columnconfigure(2, weight=1) imgFrame.rowconfigure(0, weight=1) imgFrame.rowconfigure(1, weight=0, pad=3) # Creation options frame settingsFrame = Frame(masterFrame, borderwidth=2, relief=Tkc.GROOVE) settingsFrame.pack(fill=Tkc.X) settingsFrame.columnconfigure(1, weight=1, pad=4) create = Button(masterFrame, text="Create", command=self.merge) create.pack(anchor='se', pady=2) self.previewStart = ZoomImage(imgFrame, width=200, height=200, borderwidth=2, relief=Tkc.RIDGE, cursor="crosshair") self.previewStart.grid(row=0, column=0, sticky=Tkc.NSEW) self.previewEnd = ZoomImage(imgFrame, width=200, height=200, borderwidth=2, relief=Tkc.RIDGE) self.previewEnd.grid(row=0, column=2, sticky=Tkc.NSEW) self.previewStart.bind("<Button>", self._startPreviewClicked) self.previewStart.bind("<<Dragged>>", self._previewDragged) self.previewEnd.bind("<<Dragged>>", self._previewDragged) # Binding just the previews to the MouseWheel event should work but doesn't. # The workaround is to bind everything to the mousewheel event # and filter it for just our previews in our callback... self.bind_all("<MouseWheel>", self.previewsScrollZoom) zoomFrame = Frame(imgFrame) zoomFrame.grid(row=0, column=1) self.zoomInImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "plus.gif")) zoomIn = Button(zoomFrame, image=self.zoomInImg, command=self.previewsZoomIn) zoomIn.pack() self.zoomResetImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "refresh.gif")) zoomReset = Button(zoomFrame, image=self.zoomResetImg, command=self.previewsResetZoom) zoomReset.pack() self.zoomOutImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "minus.gif")) zoomOut = Button(zoomFrame, image=self.zoomOutImg, command=self.previewsZoomOut) zoomOut.pack() self.differenceImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "difference.gif")) self.differenceBtn = ToggleButton(imgFrame, image=self.differenceImg) self.differenceBtn.grid(row=1, column=1) self.differenceBtn.bind("<Button1-ButtonRelease>", self.toggleDifference) startSpinFrame = Frame(imgFrame) startSpinFrame.grid(row=1, column=0) endSpinFrame = Frame(imgFrame) endSpinFrame.grid(row=1, column=2) startLabel = Label(startSpinFrame, text="Start Frame:") startLabel.pack(side=Tkc.LEFT) self.startSpin = Spinbox(startSpinFrame) self.startSpin.pack() self.startSpin.changedCallback = self.updateStartPreview endLabel = Label(endSpinFrame, text="End Frame:") endLabel.pack(side=Tkc.LEFT) self.endSpin = Spinbox(endSpinFrame) self.endSpin.pack() self.endSpin.changedCallback = self.updateEndPreview widthHeightFrame = Frame(settingsFrame) widthHeightFrame.grid(row=0, column=1, columnspan=2, sticky=Tkc.E+Tkc.W) widthLabel = Label(settingsFrame, text="Width:") widthLabel.grid(row=0, column=0, sticky=Tkc.W) self.activePic = PhotoImage(file=os.path.join(RESOURCE_DIR, "go.gif")) self.widthSetButton = Button(widthHeightFrame, text="Set", command=self.activateSetWidth, image=self.activePic, compound=Tkc.LEFT) self.widthSetButton.grid(row=0, column=1, sticky=Tkc.W) heightLabel = Label(widthHeightFrame, text="Height:") heightLabel.grid(row=0, column=2, padx=10, sticky=Tkc.E) self.unactivePic = PhotoImage(file=os.path.join(RESOURCE_DIR, "stop.gif")) self.heightSetButton = Button(widthHeightFrame, text="Set", command=self.activateSetHeight, image=self.unactivePic, compound=Tkc.LEFT) self.heightSetButton.grid(row=0, column=3, sticky=Tkc.W) rotationLabel = Label(settingsFrame, text="Rotation:") rotationLabel.grid(row=1, column=0, sticky=Tkc.W) rotFrame = Frame(settingsFrame) rotFrame.grid(row=1, column=1, sticky=Tkc.W) self.rotVar = IntVar() self.rotVar.set(1) rotLeft = Radiobutton(rotFrame, text="Counter Clockwise", value=1, variable=self.rotVar) rotLeft.pack(side=Tkc.LEFT, padx=4) rotRight = Radiobutton(rotFrame, text="Clockwise", value=2, variable=self.rotVar) rotRight.pack(padx=4) outputLabel = Label(settingsFrame, text="Save As:") outputLabel.grid(row=2, column=0, sticky=Tkc.W) self.outputPathVar = StringVar() outputEntry = Entry(settingsFrame, textvariable=self.outputPathVar) outputEntry.grid(row=2, column=1, sticky=Tkc.EW) self.outputImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "folder.gif")) outputSearch = Button(settingsFrame, image=self.outputImg, command=self.setSavePath) outputSearch.grid(row=2, column=2, sticky=Tkc.W) # Object variables self.sequenceLoaded = False self.currentSequence = None self.startImage = None self.endImage = None self.differenceOn = False self.overlayTag = "OverlayItems" self.settingWidth = True self.settingHeight = False self.width = {'start': Coord(), 'end': Coord()} self.height = {'start1': Coord(), 'end1': Coord(), 'start2': Coord(), 'end2': Coord()}
class Application(tkinter.Tk): def __init__(self): tkinter.Tk.__init__(self) # Menu Setup menuBar = Menu(self) fileMenu = Menu(menuBar, tearoff=False) fileMenu.add_command(label="Open...", command=self.loadSequence) fileMenu.add_command(label="Close", command=self.closeSequence) fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self.destroy) aboutMenu = Menu(menuBar, tearoff=False) aboutMenu.add_command(label="Help", command=self.showHelp) aboutMenu.add_command(label="About...", command=self.showAbout) menuBar.add_cascade(label="File", menu=fileMenu) menuBar.add_cascade(label="About", menu=aboutMenu) # Window Setup self.title("Rotostitch " + __version__) self.config(menu=menuBar) self.iconbitmap(default=os.path.join(RESOURCE_DIR, "rotostitch-icon.ico")) masterFrame = Frame(self) masterFrame.pack(expand=1, fill=Tkc.BOTH, padx=2, pady=2) self.status = StatusBar(self) self.status.pack(anchor=Tkc.W, fill=Tkc.X, side=Tkc.BOTTOM) # Image review panels frame imgFrame = Frame(masterFrame, borderwidth=2, relief=Tkc.GROOVE) imgFrame.pack(expand=1, fill=Tkc.BOTH) imgFrame.columnconfigure(0, weight=1) imgFrame.columnconfigure(1, weight=0) imgFrame.columnconfigure(2, weight=1) imgFrame.rowconfigure(0, weight=1) imgFrame.rowconfigure(1, weight=0, pad=3) # Creation options frame settingsFrame = Frame(masterFrame, borderwidth=2, relief=Tkc.GROOVE) settingsFrame.pack(fill=Tkc.X) settingsFrame.columnconfigure(1, weight=1, pad=4) create = Button(masterFrame, text="Create", command=self.merge) create.pack(anchor='se', pady=2) self.previewStart = ZoomImage(imgFrame, width=200, height=200, borderwidth=2, relief=Tkc.RIDGE, cursor="crosshair") self.previewStart.grid(row=0, column=0, sticky=Tkc.NSEW) self.previewEnd = ZoomImage(imgFrame, width=200, height=200, borderwidth=2, relief=Tkc.RIDGE) self.previewEnd.grid(row=0, column=2, sticky=Tkc.NSEW) self.previewStart.bind("<Button>", self._startPreviewClicked) self.previewStart.bind("<<Dragged>>", self._previewDragged) self.previewEnd.bind("<<Dragged>>", self._previewDragged) # Binding just the previews to the MouseWheel event should work but doesn't. # The workaround is to bind everything to the mousewheel event # and filter it for just our previews in our callback... self.bind_all("<MouseWheel>", self.previewsScrollZoom) zoomFrame = Frame(imgFrame) zoomFrame.grid(row=0, column=1) self.zoomInImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "plus.gif")) zoomIn = Button(zoomFrame, image=self.zoomInImg, command=self.previewsZoomIn) zoomIn.pack() self.zoomResetImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "refresh.gif")) zoomReset = Button(zoomFrame, image=self.zoomResetImg, command=self.previewsResetZoom) zoomReset.pack() self.zoomOutImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "minus.gif")) zoomOut = Button(zoomFrame, image=self.zoomOutImg, command=self.previewsZoomOut) zoomOut.pack() self.differenceImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "difference.gif")) self.differenceBtn = ToggleButton(imgFrame, image=self.differenceImg) self.differenceBtn.grid(row=1, column=1) self.differenceBtn.bind("<Button1-ButtonRelease>", self.toggleDifference) startSpinFrame = Frame(imgFrame) startSpinFrame.grid(row=1, column=0) endSpinFrame = Frame(imgFrame) endSpinFrame.grid(row=1, column=2) startLabel = Label(startSpinFrame, text="Start Frame:") startLabel.pack(side=Tkc.LEFT) self.startSpin = Spinbox(startSpinFrame) self.startSpin.pack() self.startSpin.changedCallback = self.updateStartPreview endLabel = Label(endSpinFrame, text="End Frame:") endLabel.pack(side=Tkc.LEFT) self.endSpin = Spinbox(endSpinFrame) self.endSpin.pack() self.endSpin.changedCallback = self.updateEndPreview widthHeightFrame = Frame(settingsFrame) widthHeightFrame.grid(row=0, column=1, columnspan=2, sticky=Tkc.E+Tkc.W) widthLabel = Label(settingsFrame, text="Width:") widthLabel.grid(row=0, column=0, sticky=Tkc.W) self.activePic = PhotoImage(file=os.path.join(RESOURCE_DIR, "go.gif")) self.widthSetButton = Button(widthHeightFrame, text="Set", command=self.activateSetWidth, image=self.activePic, compound=Tkc.LEFT) self.widthSetButton.grid(row=0, column=1, sticky=Tkc.W) heightLabel = Label(widthHeightFrame, text="Height:") heightLabel.grid(row=0, column=2, padx=10, sticky=Tkc.E) self.unactivePic = PhotoImage(file=os.path.join(RESOURCE_DIR, "stop.gif")) self.heightSetButton = Button(widthHeightFrame, text="Set", command=self.activateSetHeight, image=self.unactivePic, compound=Tkc.LEFT) self.heightSetButton.grid(row=0, column=3, sticky=Tkc.W) rotationLabel = Label(settingsFrame, text="Rotation:") rotationLabel.grid(row=1, column=0, sticky=Tkc.W) rotFrame = Frame(settingsFrame) rotFrame.grid(row=1, column=1, sticky=Tkc.W) self.rotVar = IntVar() self.rotVar.set(1) rotLeft = Radiobutton(rotFrame, text="Counter Clockwise", value=1, variable=self.rotVar) rotLeft.pack(side=Tkc.LEFT, padx=4) rotRight = Radiobutton(rotFrame, text="Clockwise", value=2, variable=self.rotVar) rotRight.pack(padx=4) outputLabel = Label(settingsFrame, text="Save As:") outputLabel.grid(row=2, column=0, sticky=Tkc.W) self.outputPathVar = StringVar() outputEntry = Entry(settingsFrame, textvariable=self.outputPathVar) outputEntry.grid(row=2, column=1, sticky=Tkc.EW) self.outputImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "folder.gif")) outputSearch = Button(settingsFrame, image=self.outputImg, command=self.setSavePath) outputSearch.grid(row=2, column=2, sticky=Tkc.W) # Object variables self.sequenceLoaded = False self.currentSequence = None self.startImage = None self.endImage = None self.differenceOn = False self.overlayTag = "OverlayItems" self.settingWidth = True self.settingHeight = False self.width = {'start': Coord(), 'end': Coord()} self.height = {'start1': Coord(), 'end1': Coord(), 'start2': Coord(), 'end2': Coord()} def showAbout(self): pass def showHelp(self): pass def loadSequence(self): path = filedialog.askopenfilename(title="Select image from image sequence...") if path and os.path.isfile(path): self.status.showText("Loading sequence: '{}'".format(path)) s = self.currentSequence = FrameSequence(path) self.sequenceLoaded = True self.setupForSequence() self.status.showText("Finished loading: '{}'".format(''.join([s.name, "#" * s.frameDigits, s.ext]))) else: self.status.showText("No sequence at: '{}'".format(path)) def closeSequence(self): self.currentSequence = None self.sequenceLoaded = False self.previewStart.delete(self.overlayTag) self.width = {'start': Coord(), 'end': Coord()} self.height = {'start1': Coord(), 'end1': Coord(), 'start2': Coord(), 'end2': Coord()} self.previewStart.reset() self.previewEnd.reset() self.startSpin.reset() self.endSpin.reset() def setSavePath(self): path = filedialog.asksaveasfilename(title="Select save location...") if path: self.outputPathVar.set(path) def setupForSequence(self): s = self.currentSequence if self.differenceOn: self.differenceBtn.setSelected(False) self.differenceOn = False start = s.start end = s.end self.setStartPreview(start) self.setEndPreview(end) self.startSpin.min(start) self.startSpin.set(start) self.endSpin.max(end) self.endSpin.set(end) self.startSpin.max(end) self.endSpin.min(start) def setStartPreview(self, frame): self.startImage = self.currentSequence.image(frame) if self.startImage: if self.startImage.mode != "RGBA": self.startImage = self.startImage.convert("RGBA") self._refreshStartPreview() def _refreshStartPreview(self): im = self.startImage.copy() if self.differenceOn: endIm = self.previewEnd.getImage() im = ImageChops.difference(im, endIm) im.putalpha(255) self.previewStart.setImage(im) def setEndPreview(self, frame): self.endImage = self.currentSequence.image(frame) if self.endImage: if self.endImage.mode != "RGBA": self.endImage = self.endImage.convert("RGBA") self._refreshEndPreview() def _refreshEndPreview(self): im = self.endImage if self.differenceOn: dif = ImageChops.difference(self.startImage, im) dif.putalpha(255) self.previewStart.setImage(dif) self.previewEnd.setImage(im) def updateStartPreview(self): i = self.startSpin.get() self.endSpin.min(i) if self.sequenceLoaded: self.setStartPreview(i) def updateEndPreview(self): i = self.endSpin.get() self.startSpin.max(i) if self.sequenceLoaded: self.setEndPreview(i) def previewsScrollZoom(self, event): w = self.winfo_containing(event.x_root, event.y_root) if w == self.previewStart or w == self.previewEnd: center = (event.x_root - w.winfo_rootx(), event.y_root - w.winfo_rooty()) if event.delta < 0: self.adjustZoom("out", center) else: self.adjustZoom("in", center) def previewsZoomIn(self): self.adjustZoom("in") def previewsZoomOut(self): self.adjustZoom("out") def adjustZoom(self, direction, center=None): if self.sequenceLoaded: x, y = center if center else (self.previewStart.size[0] / 2, self.previewStart.size[1] / 2) if direction == "in": self.previewStart.zoomIn(center) self.previewEnd.zoomIn(center) self.previewStart.scale(self.overlayTag, x, y, 2.0, 2.0) elif direction == "out": self.previewStart.zoomOut(center) self.previewEnd.zoomOut(center) self.previewStart.scale(self.overlayTag, x, y, .5, .5) self.drawOverlay() def previewsResetZoom(self): self.previewStart.resetZoom() self.previewEnd.resetZoom() self.drawOverlay() def _previewDragged(self, event): if event.widget == self.previewStart: self.previewEnd.moveImage(event.x, event.y) else: self.previewStart.moveImage(event.x, event.y) self.previewStart.move(self.overlayTag, -event.x, -event.y) def toggleDifference(self, event): if not self.differenceBtn.selected(): self.differenceOn = True else: self.differenceOn = False self.setDifference() def setDifference(self): if self.sequenceLoaded: if self.differenceOn: startIm = self.previewStart.getImage() endIm = self.previewEnd.getImage() dif = ImageChops.difference(startIm, endIm) dif.putalpha(255) self.previewStart.setImage(dif) self.differenceOn = True else: self.previewStart.setImage(self.startImage) self.differenceOn = False def activateSetWidth(self): self.widthSetButton.configure(image=self.activePic) self.heightSetButton.configure(image=self.unactivePic) self.settingWidth = True self.settingHeight = False def activateSetHeight(self): self.widthSetButton.configure(image=self.unactivePic) self.heightSetButton.configure(image=self.activePic) self.settingWidth = False self.settingHeight = True def _startPreviewClicked(self, event): if self.sequenceLoaded and (event.num == 1 or event.num == 3): x, y = self.previewStart.screenToWorld((event.x, event.y)) if self.settingWidth: self._setWidth(event.num, x, y) elif self.settingHeight: self._setHeight(event.num, x, y, event.state) def _setWidth(self, button, x, y): if button == 1: self.width['start'].set(x, y) else: self.width['end'].set(x, y) self.drawOverlay() def _setHeight(self, button, x, y, mod): shift = 0x0001 if button == 1: if mod & shift == shift: self.height['start2'].set(x, y) else: self.height['start1'].set(x, y) else: if mod & shift == shift: self.height['end2'].set(x, y) else: self.height['end1'].set(x, y) self.drawOverlay() def drawOverlay(self): prev = self.previewStart # Draw the width line and center line x, y = prev.worldToScreen(self.width['start'].get()) # Width line and dot start point x2, y2 = prev.worldToScreen(self.width['end'].get()) # Width line and dot end point x3 = (x + x2) / 2 # Rotation center line x __, y3 = prev.worldToScreen((0, 0)) # Rotation center line top y __, y4 = prev.worldToScreen(prev.getImage().size) # Rotation center line bottom y prev.delete(self.overlayTag) prev.create_line(x3, y3, x3, y4, tags=self.overlayTag, fill="blue") prev.create_line(x, y, x2, y2, tags=self.overlayTag, fill="red") prev.create_oval(x - 2, y - 2, x + 3, y + 3, tags=self.overlayTag, fill="green") prev.create_oval(x2 - 2, y2 - 2, x2 + 3, y2 + 3, tags=self.overlayTag, fill="green") # Draw the height lines x, y = prev.worldToScreen(self.height['start1'].get()) x2, y2 = prev.worldToScreen(self.height['end1'].get()) prev.create_line(x, y, x2, y2, tags=self.overlayTag, fill="violet") prev.create_oval(x - 2, y - 2, x + 3, y + 3, tags=self.overlayTag, fill="green") prev.create_oval(x2 - 2, y2 - 2, x2 + 3, y2 + 3, tags=self.overlayTag, fill="green") x, y = prev.worldToScreen(self.height['start2'].get()) x2, y2 = prev.worldToScreen(self.height['end2'].get()) prev.create_line(x, y, x2, y2, tags=self.overlayTag, fill="cyan") prev.create_oval(x - 2, y - 2, x + 3, y + 3, tags=self.overlayTag, fill="green") prev.create_oval(x2 - 2, y2 - 2, x2 + 3, y2 + 3, tags=self.overlayTag, fill="green") def merge(self): path = self.outputPathVar.get() if self.sequenceLoaded and path != "": self.status.showProgress() start = self.startSpin.get() end = self.endSpin.get() s = self.currentSequence rotationCenter = int((self.width['start'].x + self.width['end'].x) / 2) height = s.frameSize[1] frameCount = end - start self.status.setProgressMax(frameCount) h = self.height len1 = abs(h['start1'].y - h['end1'].y) len2 = abs(h['start2'].y - h['end2'].y) if len1 > len2: adjustmentRatio = len1/len2 else: adjustmentRatio = len2/len1 crossSection = abs(self.width['start'].x - self.width['end'].x) idealWidth = crossSection * math.pi * adjustmentRatio arcLen = (1.0 / frameCount) * idealWidth stripWidth = int(round(arcLen)) width = stripWidth * frameCount mergeIm = Image.new("RGB", (width, height), None) if self.rotVar.get() == 1: x = width - stripWidth dx = -1 else: x = 0 dx = 1 self.status.setProgress(0) for fnum in range(start, end): frame = s.image(fnum) if frame: frameStrip = frame.crop((rotationCenter, 0, rotationCenter + stripWidth, height)) mergeIm.paste(frameStrip, (x, 0)) x += (dx * stripWidth) self.status.setProgress(fnum) mergeIm = mergeIm.resize((int(idealWidth), height), Image.ANTIALIAS) try: mergeIm.save(path) except IOError: messagebox.showerror("Sorry...", message="Unable to save the final image.") self.status.showText("Finished merging. Unable to save to '{}'".format(path)) self.status.showText("Finished merging. Saved to '{}'".format(path))
def set_config(): sys_para = sys.argv file_path = os.path.split(sys_para[0])[0] gui = False if platform.uname()[0] == 'Windows': # Win默认打开 gui = True if platform.uname()[0] == 'Linux': # Linux 默认关闭 gui = False if '--gui' in sys.argv: # 指定 gui 模式 gui = True if '--nogui' in sys.argv: # 带 nogui 就覆盖前面Win打开要求 gui = False config_file = os.path.join(file_path, 's3_download_config.ini') # If no config file, read the default config if not os.path.exists(config_file): config_file += '.default' print("No customized config, use the default config") cfg = ConfigParser() print(f'Reading config file: {config_file}') try: global SrcBucket, S3Prefix, SrcFileIndex, SrcProfileName, DesDir, MaxRetry, MaxThread, MaxParallelFile, LoggingLevel cfg.read(config_file, encoding='utf-8-sig') SrcBucket = cfg.get('Basic', 'SrcBucket') S3Prefix = cfg.get('Basic', 'S3Prefix') SrcFileIndex = cfg.get('Basic', 'SrcFileIndex') SrcProfileName = cfg.get('Basic', 'SrcProfileName') DesDir = cfg.get('Basic', 'DesDir') Megabytes = 1024 * 1024 ChunkSize = cfg.getint('Advanced', 'ChunkSize') * Megabytes MaxRetry = cfg.getint('Advanced', 'MaxRetry') MaxThread = cfg.getint('Advanced', 'MaxThread') MaxParallelFile = cfg.getint('Advanced', 'MaxParallelFile') LoggingLevel = cfg.get('Advanced', 'LoggingLevel') except Exception as e: print("ERR loading s3_download_config.ini", str(e)) input('PRESS ENTER TO QUIT') sys.exit(0) if gui: # For GUI from tkinter import Tk, filedialog, END, StringVar, BooleanVar, messagebox from tkinter.ttk import Combobox, Label, Button, Entry, Spinbox, Checkbutton # get profile name list in ./aws/credentials pro_conf = RawConfigParser() pro_path = os.path.join(os.path.expanduser("~"), ".aws") cre_path = os.path.join(pro_path, "credentials") if os.path.exists(cre_path): pro_conf.read(cre_path) profile_list = pro_conf.sections() else: print( f"There is no aws_access_key in {cre_path}, please input for S3 Bucket: " ) os.mkdir(pro_path) aws_access_key_id = input('aws_access_key_id: ') aws_secret_access_key = input('aws_secret_access_key: ') region = input('region: ') pro_conf.add_section('default') pro_conf['default']['aws_access_key_id'] = aws_access_key_id pro_conf['default'][ 'aws_secret_access_key'] = aws_secret_access_key pro_conf['default']['region'] = region profile_list = ['default'] with open(cre_path, 'w') as f: print(f"Saving credentials to {cre_path}") pro_conf.write(f) # Click Select Folder def browse_folder(): local_dir = filedialog.askdirectory( initialdir=os.path.dirname(__file__)) url_txt.delete(0, END) url_txt.insert(0, local_dir) file_txt.delete(0, END) file_txt.insert(0, "*") # Finsih browse folder # Click List Buckets def ListBuckets(*args): SrcProfileName = SrcProfileName_txt.get() client = Session(profile_name=SrcProfileName).client('s3') bucket_list = [] try: response = client.list_buckets() if 'Buckets' in response: bucket_list = [b['Name'] for b in response['Buckets']] except Exception as e: messagebox.showerror( 'Error', f'Failt to List buckets. \n' f'Please verify your aws_access_key of profile: [{SrcProfileName}]\n' f'{str(e)}') bucket_list = ['CAN_NOT_GET_BUCKET_LIST'] SrcBucket_txt['values'] = bucket_list SrcBucket_txt.current(0) # Finish ListBuckets # Click List Prefix def ListPrefix(*args): SrcProfileName = SrcProfileName_txt.get() client = Session(profile_name=SrcProfileName).client('s3') prefix_list = [] this_bucket = SrcBucket_txt.get() max_get = 100 try: response = client.list_objects_v2( Bucket=this_bucket, Delimiter='/', RequestPayer='requester' ) # Only get the max 1000 prefix for simply list if 'CommonPrefixes' in response: prefix_list = [ c['Prefix'] for c in response['CommonPrefixes'] ] if not prefix_list: messagebox.showinfo( 'Message', f'There is no "/" Prefix in: {this_bucket}') if response['IsTruncated']: messagebox.showinfo( 'Message', f'More than {max_get} Prefix, cannot fully list here.') except Exception as e: messagebox.showinfo( 'Error', f'Cannot get prefix list from bucket: {this_bucket}, {str(e)}' ) S3Prefix_txt['values'] = prefix_list S3Prefix_txt.current(0) # Finish list prefix def browse_file(*args): SrcProfileName = SrcProfileName_txt.get() S3Prefix = S3Prefix_txt.get() client = Session(profile_name=SrcProfileName).client('s3') file_list = [] this_bucket = SrcBucket_txt.get() max_get = 100 try: response = client.list_objects_v2( Bucket=this_bucket, Prefix=str(PurePosixPath(S3Prefix)) + '/', RequestPayer='requester', Delimiter='/' ) # Only get the max 1000 files for simply list # For delete prefix in des_prefix if S3Prefix == '' or S3Prefix == '/': # 目的bucket没有设置 Prefix dp_len = 0 else: # 目的bucket的 "prefix/"长度 dp_len = len(str(PurePosixPath(S3Prefix))) + 1 if 'Contents' in response: file_list = [ c['Key'][dp_len:] for c in response['Contents'] ] # 去掉Prefix if not file_list: messagebox.showinfo( 'Message', f'There is no files in s3://{this_bucket}/{S3Prefix}') if response['IsTruncated']: messagebox.showinfo( 'Message', f'More than {max_get} files, cannot fully list here.') except Exception as e: messagebox.showinfo( 'Error', f'Cannot get file list from bucket s3://{this_bucket}/{S3Prefix}, {str(e)}' ) file_txt['values'] = file_list file_txt.current(0) # Finish list files # Click START button def close(): window.withdraw() ok = messagebox.askokcancel( 'Start downloading job', f'DOWNLOAD FROM s3://{SrcBucket_txt.get()}/{S3Prefix_txt.get()}\n' f'TO LOCAL {url_txt.get()}\n' f'Click OK to START') if not ok: window.deiconify() return window.quit() return # Finish close() # Start GUI window = Tk() window.title( "LONGBOW - AMAZON S3 DOWNLOAD TOOL WITH BREAK-POINT RESUMING") window.geometry('705x350') window.configure(background='#ECECEC') window.protocol("WM_DELETE_WINDOW", sys.exit) Label(window, text="S3 Bucket").grid(column=0, row=1, sticky='w', padx=2, pady=2) SrcBucket_txt = Combobox(window, width=48) SrcBucket_txt.grid(column=1, row=1, sticky='w', padx=2, pady=2) SrcBucket_txt['values'] = SrcBucket SrcBucket_txt.current(0) Button(window, text="List Buckets", width=10, command=ListBuckets) \ .grid(column=2, row=1, sticky='w', padx=2, pady=2) Label(window, text="S3 Prefix").grid(column=0, row=2, sticky='w', padx=2, pady=2) S3Prefix_txt = Combobox(window, width=48) S3Prefix_txt.grid(column=1, row=2, sticky='w', padx=2, pady=2) S3Prefix_txt['values'] = S3Prefix if S3Prefix != '': S3Prefix_txt.current(0) Button(window, text="List Prefix", width=10, command=ListPrefix) \ .grid(column=2, row=2, sticky='w', padx=2, pady=2) Label(window, text="Filename or *").grid(column=0, row=3, sticky='w', padx=2, pady=2) file_txt = Combobox(window, width=48) file_txt.grid(column=1, row=3, sticky='w', padx=2, pady=2) file_txt['values'] = SrcFileIndex if SrcFileIndex != '': file_txt.current(0) Button(window, text="Select File", width=10, command=browse_file) \ .grid(column=2, row=3, sticky='w', padx=2, pady=2) Label(window, text="AWS Profile").grid(column=0, row=4, sticky='w', padx=2, pady=2) SrcProfileName_txt = Combobox(window, width=15, state="readonly") SrcProfileName_txt['values'] = tuple(profile_list) SrcProfileName_txt.grid(column=1, row=4, sticky='w', padx=2, pady=2) if SrcProfileName in profile_list: position = profile_list.index(SrcProfileName) SrcProfileName_txt.current(position) else: SrcProfileName_txt.current(0) SrcProfileName = SrcProfileName_txt.get() SrcProfileName_txt.bind("<<ComboboxSelected>>", ListBuckets) Label(window, text="Folder").grid(column=0, row=5, sticky='w', padx=2, pady=2) url_txt = Entry(window, width=50) url_txt.grid(column=1, row=5, sticky='w', padx=2, pady=2) url_btn = Button(window, text="Select Folder", width=10, command=browse_folder) url_btn.grid(column=2, row=5, sticky='w', padx=2, pady=2) url_txt.insert(0, DesDir) Label(window, text="MaxThread/File").grid(column=0, row=6, sticky='w', padx=2, pady=2) if MaxThread < 1 or MaxThread > 100: MaxThread = 5 var_t = StringVar() var_t.set(str(MaxThread)) MaxThread_txt = Spinbox(window, from_=1, to=100, width=15, textvariable=var_t) MaxThread_txt.grid(column=1, row=6, sticky='w', padx=2, pady=2) Label(window, text="MaxParallelFile").grid(column=0, row=7, sticky='w', padx=2, pady=2) if MaxParallelFile < 1 or MaxParallelFile > 100: MaxParallelFile = 5 var_f = StringVar() var_f.set(str(MaxParallelFile)) MaxParallelFile_txt = Spinbox(window, from_=1, to=100, width=15, textvariable=var_f) MaxParallelFile_txt.grid(column=1, row=7, sticky='w', padx=2, pady=2) save_config = BooleanVar() save_config.set(True) save_config_txt = Checkbutton(window, text="Save to s3_download_config.ini", var=save_config) save_config_txt.grid(column=1, row=9, padx=2, pady=2) Button(window, text="Start Download", width=15, command=close).grid(column=1, row=10, padx=5, pady=5) window.mainloop() DesDir = url_txt.get() SrcFileIndex = file_txt.get() SrcBucket = SrcBucket_txt.get() S3Prefix = S3Prefix_txt.get() SrcProfileName = SrcProfileName_txt.get() MaxThread = int(MaxThread_txt.get()) MaxParallelFile = int(MaxParallelFile_txt.get()) if save_config: cfg['Basic']['SrcBucket'] = SrcBucket cfg['Basic']['S3Prefix'] = S3Prefix cfg['Basic']['SrcFileIndex'] = SrcFileIndex cfg['Basic']['SrcProfileName'] = SrcProfileName cfg['Basic']['DesDir'] = DesDir cfg['Advanced']['MaxThread'] = str(MaxThread) cfg['Advanced']['MaxParallelFile'] = str(MaxParallelFile) config_file = os.path.join(file_path, 's3_download_config.ini') with codecs.open(config_file, 'w', 'utf-8') as f: cfg.write(f) print(f"Save config to {config_file}") # GUI window finish if S3Prefix == '/': S3Prefix = '' # Finish set_config() return ChunkSize
class DialogOpenArchive(Toplevel): def __init__(self, parent, openType, filesource, filenames, title, colHeader, showAltViewButton=False): if isinstance(parent, Cntlr): cntlr = parent parent = parent.parent # parent is cntlrWinMain else: # parent is a Toplevel dialog cntlr = parent.cntlr super(DialogOpenArchive, self).__init__(parent) self.parent = parent self.showAltViewButton = showAltViewButton parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.accepted = False self.transient(self.parent) frame = Frame(self) treeFrame = Frame(frame, width=500) vScrollbar = Scrollbar(treeFrame, orient=VERTICAL) hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL) self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set) self.treeView.grid(row=0, column=0, sticky=(N, S, E, W)) hScrollbar["command"] = self.treeView.xview hScrollbar.grid(row=1, column=0, sticky=(E, W)) vScrollbar["command"] = self.treeView.yview vScrollbar.grid(row=0, column=1, sticky=(N, S)) treeFrame.columnconfigure(0, weight=1) treeFrame.rowconfigure(0, weight=1) treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.treeView.focus_set() if openType != PLUGIN: cntlr.showStatus(_("loading archive {0}").format(filesource.url)) self.filesource = filesource self.filenames = filenames self.selection = filesource.selection self.hasToolTip = False selectedNode = None if openType == ENTRY_POINTS: try: metadataFiles = filesource.taxonomyPackageMetadataFiles ''' take first for now if len(metadataFiles) != 1: raise IOError(_("Taxonomy package contained more than one metadata file: {0}.") .format(', '.join(metadataFiles))) ''' metadataFile = metadataFiles[0] metadata = filesource.url + os.sep + metadataFile self.metadataFilePrefix = os.sep.join( os.path.split(metadataFile)[:-1]) if self.metadataFilePrefix: self.metadataFilePrefix += "/" # zip contents have /, never \ file seps self.taxonomyPkgMetaInf = '{}/META-INF/'.format( os.path.splitext(os.path.basename(filesource.url))[0]) self.taxonomyPackage = parsePackage( cntlr, filesource, metadata, os.sep.join(os.path.split(metadata)[:-1]) + os.sep) # may be a catalog file with no entry oint names if not self.taxonomyPackage["nameToUrls"]: openType = ARCHIVE # no entry points to show, just archive self.showAltViewButton = False except Exception as e: self.close() err = _( "Failed to parse metadata; the underlying error was: {0}" ).format(e) messagebox.showerror(_("Malformed taxonomy package"), err) cntlr.addToLog(err) return if openType != PLUGIN: cntlr.showStatus(None) if openType in (DISCLOSURE_SYSTEM, PLUGIN): y = 3 else: y = 1 okButton = Button(frame, text=_("OK"), command=self.ok) cancelButton = Button(frame, text=_("Cancel"), command=self.close) okButton.grid(row=y, column=2, sticky=(S, E, W), pady=3) cancelButton.grid(row=y, column=3, sticky=(S, E, W), pady=3, padx=3) if self.showAltViewButton: self.altViewButton = Button(frame, command=self.showAltView) self.altViewButton.grid(row=y, column=0, sticky=(S, W), pady=3, padx=3) self.loadTreeView(openType, colHeader, title) self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100)) frame.grid(row=0, column=0, sticky=(N, S, E, W)) frame.columnconfigure(0, weight=1) frame.rowconfigure(0, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) window.rowconfigure(0, weight=1) self.bind("<Return>", self.ok) self.bind("<Escape>", self.close) self.toolTipText = StringVar() if self.hasToolTip: self.treeView.bind("<Motion>", self.motion, '+') self.treeView.bind("<Leave>", self.leave, '+') self.toolTipText = StringVar() self.toolTip = ToolTip(self.treeView, textvariable=self.toolTipText, wraplength=640, follow_mouse=True, state="disabled") self.toolTipRowId = None self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self) def loadTreeView(self, openType, title, colHeader): self.title(title) self.openType = openType selectedNode = None # clear previous treeview entries for previousNode in self.treeView.get_children(""): self.treeView.delete(previousNode) # set up treeView widget and tabbed pane if openType in (ARCHIVE, DISCLOSURE_SYSTEM, PLUGIN): if openType == PLUGIN: width = 700 else: width = 500 self.treeView.column("#0", width=width, anchor="w") self.treeView.heading("#0", text=colHeader) self.isRss = getattr(self.filesource, "isRss", False) if self.isRss: self.treeView.column("#0", width=350, anchor="w") self.treeView["columns"] = ("descr", "date", "instDoc") self.treeView.column("descr", width=50, anchor="center", stretch=False) self.treeView.heading("descr", text="Form") self.treeView.column("date", width=170, anchor="w", stretch=False) self.treeView.heading("date", text="Pub Date") self.treeView.column("instDoc", width=200, anchor="w", stretch=False) self.treeView.heading("instDoc", text="Instance Document") elif openType == PLUGIN: self.treeView.column("#0", width=150, anchor="w") self.treeView["columns"] = ("name", "vers", "descr") self.treeView.column("name", width=150, anchor="w", stretch=False) self.treeView.heading("name", text="Name") self.treeView.column("vers", width=60, anchor="w", stretch=False) self.treeView.heading("vers", text="Version") self.treeView.column("descr", width=300, anchor="w", stretch=False) self.treeView.heading("descr", text="Description") else: self.treeView["columns"] = tuple() loadedPaths = [] for i, filename in enumerate(self.filenames): if isinstance(filename, tuple): if self.isRss: form, date, instDoc = filename[2:5] elif openType == PLUGIN: name, vers, descr = filename[3:6] filename = filename[0] # ignore tooltip self.hasToolTip = True if filename.endswith("/"): filename = filename[:-1] path = filename.split("/") if not self.isRss and len( path) > 1 and path[:-1] in loadedPaths: parent = "file{0}".format(loadedPaths.index(path[:-1])) else: parent = "" node = self.treeView.insert(parent, "end", "file{0}".format(i), text=path[-1]) if self.isRss: self.treeView.set(node, "descr", form) self.treeView.set(node, "date", date) self.treeView.set(node, "instDoc", os.path.basename(instDoc)) elif openType == PLUGIN: self.treeView.set(node, "name", name) self.treeView.set(node, "vers", vers) self.treeView.set(node, "descr", descr) if self.selection == filename: selectedNode = node loadedPaths.append(path) elif openType == ENTRY_POINTS: self.treeView.column("#0", width=150, anchor="w") self.treeView.heading("#0", text="Name") self.treeView["columns"] = ("url", ) self.treeView.column("url", width=350, anchor="w") self.treeView.heading("url", text="URL") for name, urls in self.taxonomyPackage["nameToUrls"].items(): displayUrl = urls[1] # display the canonical URL self.treeView.insert("", "end", name, values=[displayUrl], text=name) self.hasToolTip = True else: # unknown openType return None if selectedNode: self.treeView.see(selectedNode) self.treeView.selection_set(selectedNode) if self.showAltViewButton: self.altViewButton.config(text=_("Show Files") if openType == ENTRY_POINTS else _("Show Entries")) def ok(self, event=None): selection = self.treeView.selection() if len(selection) > 0: if hasattr(self, "taxonomyPackage"): # load file source remappings self.filesource.mappedPaths = self.taxonomyPackage[ "remappings"] filename = None if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM): filename = self.filenames[int(selection[0][4:])] if isinstance(filename, tuple): if self.isRss: filename = filename[4] else: filename = filename[0] elif self.openType == ENTRY_POINTS: epName = selection[0] #index 0 is the remapped Url, as opposed to the canonical one used for display # Greg Acsone reports [0] does not work for Corep 1.6 pkgs, need [1], old style packages filename = self.taxonomyPackage["nameToUrls"][epName][0] if not filename.endswith("/"): # check if it's an absolute URL rather than a path into the archive if not isHttpUrl( filename ) and self.metadataFilePrefix != self.taxonomyPkgMetaInf: # assume it's a path inside the archive: filename = self.metadataFilePrefix + filename elif self.openType == PLUGIN: filename = self.filenames[int(selection[0][4:])][2] if filename is not None and not filename.endswith("/"): if hasattr(self, "taxonomyPackage"): # attempt to unmap the filename to original file # will be mapped again in loading, but this allows schemaLocation to be unmapped for prefix, remapping in self.taxonomyPackage[ "remappings"].items(): if isHttpUrl(remapping): remapStart = remapping else: remapStart = self.metadataFilePrefix + remapping if filename.startswith(remapStart): # set unmmapped file filename = prefix + filename[len(remapStart):] break if self.openType == PLUGIN: self.filesource.selection = filename else: self.filesource.select(filename) self.accepted = True self.close() def close(self, event=None): self.parent.focus_set() self.destroy() def showAltView(self, event=None): if self.openType == ENTRY_POINTS: self.loadTreeView(ARCHIVE, _("Select Entry Point"), _("File")) else: self.loadTreeView(ENTRY_POINTS, _("Select Archive File"), _("File")) def leave(self, *args): self.toolTipRowId = None def motion(self, *args): tvRowId = self.treeView.identify_row(args[0].y) if tvRowId != self.toolTipRowId: text = None if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM, PLUGIN): self.toolTipRowId = tvRowId if tvRowId and len(tvRowId) > 4: try: text = self.filenames[int(tvRowId[4:])] if isinstance(text, tuple): text = (text[1] or "").replace("\\n", "\n") except (KeyError, ValueError): pass elif self.openType == ENTRY_POINTS: try: epUrl = self.taxonomyPackage["nameToUrls"][tvRowId][1] text = "{0}\n{1}".format(tvRowId, epUrl) except KeyError: pass self.setToolTip(text) def setToolTip(self, text): self.toolTip._hide() if text: self.toolTipText.set(text) self.toolTip.configure(state="normal") self.toolTip._schedule() else: self.toolTipText.set("") self.toolTip.configure(state="disabled")
class Application(Frame): def __init__(self,master): super().__init__(master) self.toolsThickness = 20 self.rgb = "#%02x%02x%02x" % (255, 255, 255) self.cv = tk.Canvas(self) self.initUI() def initUI(self): self.frame = Frame(self,) self.master.title("Digit Recognition") self.pack(fill=BOTH, expand = True) root.iconbitmap('Logo of Digital Reconigiion.ico') #The canvas self.myCanvas = tk.Canvas(self, width = 800,height = 500,bg="black", borderwidth=5) self.myCanvas.grid(rowspan = 500,columnspan = 800) self.myCanvas.bind("<B1-Motion>", self.draw) self.myCanvas.bind("<Button-1>", self.setPreviousXY) #The Predict Button self.img = tk.PhotoImage(file = "button.png") self.Button1 = Button(self, text = "Predict", width=30, command = self.Predict, image = self.img) self.Button1.grid(row = 80, column = 802) #The Clear Button self.img2 = tk.PhotoImage(file = "button2.png") self.Button2 = Button(self, text = "Clear Screen", width=30, command=self.deleteAll, image = self.img2) self.Button2.grid(row = 120, column = 802) #The dsplay Button self.label2 = Label(self,width =20, text = str, font=("Times New Roman", 16,"bold")) self.label2.grid(row = 160, column = 802) self.var = StringVar(self) self.var.set("Team Members:") #The Dropdown self.box = ttk.Combobox(self, text = "Team:", values = choices, state = "readonly") self.box.set("Team members:") self.box.grid(row = 260, column = 802) self.button5 = Button(self,text = "Go", command = self.click) self.button5.grid(row =265,column = 802) #Display Team info self.label_chosen_variable= Label(self, text = chosen_option) self.label_chosen_variable.grid(row = 270, column = 802) #LOGO self.img3 = PhotoImage(file = 'final_digit.png') self.label = Label(self, image = self.img3) self.label.grid(row = 50, column = 802) def click(self): chosen_option = self.box.get() if chosen_option == "1505205": chosen_option = "Name : CHAMPAK SINHA\nRoll no. : 1505205\nSection : CS3" elif chosen_option == "1505137": chosen_option = "Name : RISHAB\nRoll no. : 1505137\nSection : CS2" elif chosen_option == "1505232": chosen_option = "Name : PRANESH BISWAS\nRoll no. : 1505232\nSection : CS3" elif chosen_option == "1505095": chosen_option = "Name : ANISH HOTA\nRoll no. : 1505095\nSection : CS2" elif chosen_option == "1505361": chosen_option = "Name : ANAND KUMAR\nRoll no. : 1505361\nSection : CS5" self.label_chosen_variable.config(text = chosen_option) def setThickness(self, event): print("Thickness is set to 20") self.toolsThickness = 20 def setPreviousXY(self, event): print("now") self.previousX = event.x self.previousY = event.y def draw(self, event): #line 2 self.myCanvas.create_oval(event.x - self.toolsThickness, event.y - self.toolsThickness, event.x + self.toolsThickness, event.y + self.toolsThickness, fill = self.rgb, outline ="" ) def SAVE(self): print('\n def _snapsaveCanvas(self):') canvas = self._canvas() # Get Window Coordinates of Canvas self.grabcanvas = ImageGrab.grab(bbox=canvas).save("out_snapsave.jpg") print('Screenshot tkinter canvas and saved as "out_snapsave.jpg w/o displaying screenshot."') def _canvas(self): print(' def _canvas(self):') print('self.cv.winfo_rootx() = ', root.winfo_rootx()) print('self.cv.winfo_rooty() = ', root.winfo_rooty()) print('self.cv.winfo_x() =', root.winfo_x()) print('self.cv.winfo_y() =', root.winfo_y()) print('self.cv.winfo_width() = 1000') print('self.cv.winfo_height() =', root.winfo_height()) x=root.winfo_rootx()+5 y=root.winfo_rooty()+5 x1=x+805 y1=y+root.winfo_height()-11 box=(x,y,x1,y1) print('box = ', box) return box def deleteAll(self): self.myCanvas.delete("all") def Predict(self): self.SAVE() call(["python", "script3.py"]) file = open("output.txt","r") str = " Output-> " + file.read() print (str) file.close() self.label2.config(text = str)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("") #self.style = Style() #self.style.theme_use("clam") #self.pack(fill=BOTH, expand = 1) self.labelU = Label(self, text="U:") self.labelP = Label(self, text="P:") self.mailrecipient = 'GoldenSights' self.entryUsername = Entry(self) self.entryUsername.focus_set() self.entryUsername.bind('<Return>', lambda event: self.entryPassword.focus_set()) self.entryPassword = Entry(self) self.entryPassword.config(show='•') self.entryPassword.bind( '<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton = Button( self, text="Login", command=lambda: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton.bind( '<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton.config(width=6) self.quitbutton = Button(self, text="Quit", command=lambda: self.quit()) self.quitbutton.config(width=6) self.labelU.grid(row=0, column=0, padx=0) self.entryUsername.grid(row=0, column=1) self.labelP.grid(row=1, column=0) self.entryPassword.grid(row=1, column=1, pady=4) self.newbutton.grid(row=2, column=1) self.quitbutton.grid(row=3, column=1, pady=4) self.labelErrorPointer = Label(self, text="◀") self.indicatorGreen = PhotoImage(file="indicatorGreen.gif") self.indicatorRed = PhotoImage(file="indicatorRed.gif") self.indicatorBlue = PhotoImage(file="indicatorBlue.gif") self.indicatorBlack = PhotoImage(file="indicatorBlack.gif") sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() w = 400 h = 480 x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y - 50)) def login(self, username, password): print('U: ' + username) self.username = username if username == '' or not all( char in string.ascii_letters + string.digits + '_-' for char in username): print('Please enter a username') self.entryUsername.focus_set() self.labelErrorPointer.grid(row=0, column=2) elif password == '': print('Please enter a password') self.entryPassword.focus_set() self.labelErrorPointer.grid(row=1, column=2) else: self.labelErrorPointer.grid_forget() print('Attempting login for ' + username) try: self.USERAGENT = username + ' practices Tkinter+PRAW mixing with utility by /u/GoldenSights.' self.r = praw.Reddit(self.USERAGENT) #self.r.login(username, password) print('Success') self.labelU.grid_forget() self.labelP.grid_forget() self.entryUsername.grid_forget() self.entryPassword.grid_forget() self.newbutton.grid_forget() self.quitbutton.grid_forget() self.usernamelabel = Label(self, text=username + ', Sending to /u/' + self.mailrecipient) self.usernamelabel.grid(row=0, column=0, columnspan=8) self.quitbutton.grid(row=900, column=0) self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] self.optionDiscuss = "Discussion Flair + Crossposting" self.optionRegister = "Register a new Candidate" self.prevmode = self.optionDiscuss self.curmode = self.optionDiscuss self.optionvar = tkinter.StringVar(self) self.optionvar.trace("w", self.permaloop) self.optionvar.set(self.optionDiscuss) self.option = OptionMenu(self, self.optionvar, self.optionDiscuss, self.optionRegister, "three", "four") self.newbutton.unbind("<Return>") self.entryUsername.unbind("<Return>") self.entryPassword.unbind("<Return>") self.option.grid(row=1, column=0, columnspan=8, pady=8) self.updategui(True) except praw.errors.InvalidUserPass: pass print('Invalid username or password') self.entryPassword.delete(0, 200) self.labelErrorPointer.grid(row=1, column=2) def permaloop(self, *args): self.curmode = self.optionvar.get() print('Was: ' + self.prevmode + ' | Now: ' + self.curmode) if self.curmode != self.prevmode: self.prevmode = self.curmode self.updategui(True) def updategui(self, *args): if args[0] == True: print('Cleaning GUI') for item in self.labellist: item.grid_forget() for item in self.entrylist: item.grid_forget() for item in self.verifylist: item.grid_forget() for item in self.misclist: item.grid_forget() self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] if self.curmode == self.optionDiscuss: self.newrowindex = 4 self.labelPermalink = Label(self, text="Thread Permalink:") self.entryPermalink = Entry(self) self.rowconfigure(2, weight=2) self.labelPermalink.grid(row=2, column=0) self.entryPermalink.grid(row=2, column=1) self.labelcrossposting = Label(self, text="Crosspost to:") self.labelcrossposting.grid(row=3, column=0, columnspan=2, sticky="w") for m in range(5): self.redditlabel = Label(self, text="/r/") self.redditlabel.grid(row=self.newrowindex, column=0, sticky="e") self.labellist.append(self.redditlabel) self.redditentry = Entry(self) self.redditentry.grid(row=self.newrowindex, column=1) self.entrylist.append(self.redditentry) self.newrowindex += 1 self.morerowbutton = Button( self, text="+row", command=lambda: self.morerows('/r/', 0, 1, 20)) self.morerowbutton.grid(row=898, column=0, columnspan=2) self.verifybutton = Button( self, text="Verify", command=lambda: self.updategui(False)) self.verifybutton.grid(row=899, column=0, columnspan=2) self.newrowindex += 2 self.misclist.append(self.labelPermalink) self.misclist.append(self.labelcrossposting) self.misclist.append(self.entryPermalink) self.misclist.append(self.morerowbutton) self.misclist.append(self.verifybutton) if self.curmode == self.optionRegister: self.newrowindex = 6 self.labelCanUsername = Label( self, text="Candidate's Username: /u/") self.entryCanUsername = Entry(self) self.labelCanRealname = Label(self, text="Candidate's Realname:") self.entryCanRealname = Entry(self) self.labelCanFlair = Label(self, text="Candidate's Flair:") self.entryCanFlair = Entry(self) self.entryMo = Spinbox( self, width=9, values=('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')) self.entryDa = Spinbox(self, width=2, from_=1, to=31) self.entryYr = Spinbox(self, width=4, from_=2014, to=2500) self.labelHH = Label(self, text="Schedule time UTC:") self.entryHH = Spinbox(self, from_=0, to=23, width=2) self.entryMM = Spinbox(self, from_=0, to=59, width=2) self.entryYr.delete(0, 'end') self.entryYr.insert(0, 2014) self.morerowbutton = Button( self, text="+question", command=lambda: self.morerows('Q:', 0, 1, 25)) self.morerowbutton.grid(row=898, column=0, columnspan=8) self.verifybutton = Button( self, text="Verify", command=lambda: self.updategui(False)) self.verifybutton.grid(row=899, column=0, columnspan=8) self.misclist.append(self.labelCanUsername) self.misclist.append(self.labelCanRealname) self.misclist.append(self.entryCanUsername) self.misclist.append(self.entryCanRealname) self.misclist.append(self.labelHH) self.misclist.append(self.entryHH) self.misclist.append(self.entryMM) self.misclist.append(self.entryMo) self.misclist.append(self.entryDa) self.misclist.append(self.entryYr) self.labelCanUsername.grid(row=2, column=0, sticky="e") self.labelCanRealname.grid(row=3, column=0, sticky="e") self.entryCanUsername.grid(row=2, column=1, columnspan=3) self.entryCanRealname.grid(row=3, column=1, columnspan=3) self.entryMo.grid(row=4, column=1, sticky="e") self.entryDa.grid(row=4, column=2) self.entryYr.grid(row=4, column=3) self.labelHH.grid(row=4, column=0, sticky="se", pady=5) self.entryHH.grid(row=5, column=1, sticky="e") self.entryMM.grid(row=5, column=2, sticky="w") else: if self.curmode == self.optionDiscuss: verifies = [] i = self.entryPermalink.get() if len(i) == 6: pid = i else: if 'www.reddit.com/r/' in i and '/comments/' in i: pid = i.split('/comments/')[1].split('/')[0] if 'http://redd.it/' in i: pid = i.split('redd.it/')[1] for flag in self.verifylist: flag.grid_forget() self.verifylist.remove(flag) try: print('Fetching Submission ' + pid) self.r.get_info(thing_id="t3_" + pid).title + 'Check' self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=2, column=2) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: print( 'Failed. Make sure to include the http://. Copy and paste straight from your browser for best result' ) self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2, column=2) self.verifylist.append(self.redditlabel) verifies.append(False) for entry in self.entrylist: i = entry.get() if i != '': print('Fetching /r/' + i) if all(char in string.ascii_letters + string.digits + '_-' for char in i): try: sub = self.r.get_subreddit(i, fetch=True) self.redditlabel = Label( self, image=self.indicatorGreen) self.redditlabel.grid( row=entry.grid_info()['row'], column=2) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: self.redditlabel = Label( self, image=self.indicatorRed) self.redditlabel.grid( row=entry.grid_info()['row'], column=2) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') time.sleep(2) else: self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=entry.grid_info()['row'], column=2) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') print(verifies) if self.curmode == self.optionRegister: verifies = [] u = self.entryCanUsername.get() print('Fetching /u/' + u) if not all(char in string.ascii_letters + string.digits + '_-' for char in u): self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2, column=4) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tBad characterage') else: try: u = self.r.get_redditor(u) print(u) self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=2, column=4) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2, column=4) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') try: print('Checking Time') t = self.entryMo.get() + ' ' + self.entryDa.get( ) + ' ' + self.entryYr.get() + ' ' + self.entryHH.get( ) + ':' + self.entryMM.get() plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M") plandate = datetime.datetime.utcfromtimestamp( plandate.timestamp()) print('\t' + str(plandate.timestamp())) self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=5, column=3) self.verifylist.append(self.redditlabel) verifies.append(True) except: print('\tFailed') self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=5, column=3) self.verifylist.append(self.redditlabel) verifies.append(False) print(verifies) def morerows(self, label, columnm, columnn, limit, *args): self.redditlabel = Label(self, text=label) self.redditlabel.grid(row=self.newrowindex, column=columnm, sticky="e") self.labellist.append(self.redditlabel) self.redditentry = Entry(self) self.redditentry.grid(row=self.newrowindex, column=columnn, columnspan=8) self.entrylist.append(self.redditentry) self.newrowindex += 1 if self.newrowindex >= limit: self.morerowbutton.grid_forget() print(self.newrowindex)
def initialize(self): """ Initialize all the tkinter objects of the frame """ self.title('RGINE Data Analysis') # frame top_frame = tkinter.Frame(self) top_frame.pack(side=tkinter.TOP, fill=tkinter.X) data_frame = tkinter.Frame(top_frame) data_frame.pack(side=tkinter.TOP, fill=tkinter.X) data_frame_csv = tkinter.Frame(data_frame, borderwidth=2, relief=tkinter.GROOVE) data_frame_csv.pack(side=tkinter.LEFT, fill=tkinter.X, padx=5, pady=5) data_frame_data = tkinter.Frame(data_frame, borderwidth=2, relief=tkinter.GROOVE) data_frame_data.pack(side=tkinter.RIGHT, fill=tkinter.X, padx=5, pady=5) plot_frame = tkinter.Frame(top_frame, borderwidth=2, relief=tkinter.GROOVE) plot_frame.pack(side=tkinter.LEFT, fill=tkinter.X, padx=5, pady=5) action_frame = tkinter.Frame(top_frame, borderwidth=2, relief=tkinter.GROOVE) action_frame.pack(side=tkinter.RIGHT, fill=tkinter.X, padx=5, pady=5) # button load_button = Button(data_frame_csv, text="Load CSV file", command=self.load_data, width=20) load_button.grid(row=1, column=1, columnspan=1, rowspan=1, padx=5, pady=5) refresh_file_button = Button(data_frame_csv, text="Refresh CSV file", command=self.refresh_file, width=20) refresh_file_button.grid(row=1, column=2, padx=5, pady=5) display_button = Button(data_frame_data, text="Display data", command=self.display_data, width=20) display_button.grid(row=1, column=3, padx=5, pady=5) save_button = Button(data_frame_data, text="Save data", command=self.save_data, width=20) save_button.grid(row=1, column=4, padx=5, pady=5) clear_button = Button(data_frame_data, text="Clear data", command=self.clear_data, width=20) clear_button.grid(row=1, column=5, padx=5, pady=5) add_button = Button(action_frame, text="Add plot", command=self.add_plot, width=20) add_button.grid(row=1, column=3, rowspan=1, padx=5, pady=5) function_button = Button(action_frame, text="Plot math function", command=self.add_plot_function, width=20) function_button.grid(row=2, column=3, columnspan=1, rowspan=1, padx=5, pady=5) add_plot_button = Button(plot_frame, text="Add Plot frame", command=self.add_plot_frame, width=20) add_plot_button.grid(row=1, column=1, columnspan=1, rowspan=1, padx=5, pady=5) clear_plot_button = Button(plot_frame, text="Clear all plots", command=self.clear_all_plots, width=20) clear_plot_button.grid(row=1, column=2, columnspan=1, rowspan=1, padx=5, pady=5) remove_plot_button = Button(plot_frame, text="Remove all plots", command=self.remove_all_plots, width=20) remove_plot_button.grid(row=2, column=2, columnspan=1, rowspan=1, padx=5, pady=5) # label label_x = Label(action_frame, text="Choose X axis data: ", width=20) label_x.grid(row=1, column=1, padx=5, pady=5) label_y = Label(action_frame, text="Choose Y axis data: ", width=20) label_y.grid(row=2, column=1, padx=5, pady=5) # combo self.__plot_frame_combo = Combobox( plot_frame, textvariable=self.__plot_frame_select_combo, values=self.__plot_frame_list, state='readonly', postcommand=lambda: self.__plot_frame_combo.configure( values=self.__plot_frame_list), width=17) self.__plot_frame_combo.current(0) self.__plot_frame_combo.grid(row=2, column=1, padx=5, pady=5) data_select_combo1 = tkinter.StringVar() self.__variable1_combo = Combobox( action_frame, textvariable=data_select_combo1, values=self.__data_manager.get_field_names(), state='readonly', postcommand=lambda: self.__variable1_combo.configure( values=self.__data_manager.get_field_names()), width=19) self.__variable1_combo.grid(row=1, column=2, padx=5, pady=5) data_select_combo2 = tkinter.StringVar() self.__variable2_combo = Combobox( action_frame, textvariable=data_select_combo2, values=self.__data_manager.get_field_names(), state='readonly', postcommand=lambda: self.__variable2_combo.configure( values=self.__data_manager.get_field_names()), width=19) self.__variable2_combo.grid(row=2, column=2, padx=5, pady=5) # menu frame_menu = tkinter.Menu(self) help_menu = tkinter.Menu(frame_menu, tearoff=0) help_menu.add_command(label="Logger", command=self.open_logger_command) help_menu.add_separator() help_menu.add_command(label="How to", command=self.how_to_command) help_menu.add_command(label="About", command=self.about_command) frame_menu.add_cascade(label="Help", menu=help_menu) self.config(menu=frame_menu)
seller_entry.delete(0, tk.END) cost_price_entry.delete(0, tk.END) selling_price_entry.delete(0, tk.END) def export_to_excel(): convert() calc_profit() statusbar_label["text"] = f"Status: Excel file created in {os.getcwd()}" # Buttons button_frame = Frame(root, borderwidth=2, relief="groove") add_item_btn = Button(button_frame, text="Add item", command=add_item) add_item_btn.grid(row=0, column=0, sticky="we", padx=10, pady=5) remove_item_btn = Button(button_frame, text="Remove item", command=remove_item) remove_item_btn.grid(row=0, column=1, sticky="we", padx=10, pady=5) update_item_btn = Button(button_frame, text="Update item", command=update_item) update_item_btn.grid(row=0, column=2, sticky="we", padx=10, pady=5) clear_item_btn = Button(button_frame, text="Clear Input", command=clear_input) clear_item_btn.grid(row=0, column=3, sticky="we", padx=10, pady=5) export_to_excel_btn = Button( button_frame, text="Export To Excel", command=export_to_excel ) export_to_excel_btn.grid(row=0, column=4, sticky="we", padx=10, pady=5)
e4 = Entry(window, textvariable=isbn_text) e4.grid(row=1, column=6, padx=10, pady=8, sticky=E, columnspan=4) #------------------------------------------------------------------------------------------------------------ list1 = Listbox(window, height=8, width=40) list1.grid(row=12, column=0, rowspan=8, columnspan=8) list1.bind('<<ListboxSelect>>', get_selected_row) sb1 = Scrollbar(window) sb1.grid(row=12, column=2, rowspan=6, columnspan=14) list1.configure(yscrollcommand=sb1.set) sb1.configure(command=list1.yview) b1 = Button(window, text="View all", width=12, command=view_command) b1.grid(row=12, column=10) b2 = Button(window, text="Add entry", width=12, command=add_command) b2.grid(row=13, column=10) b3 = Button(window, text="Update selected", width=12, command=update_command) b3.grid(row=14, column=10) b4 = Button(window, text="Delete selected", width=12, command=delete_command) b4.grid(row=15, column=10) b5 = Button(window, text="Close", width=12, command=window.destroy) b5.grid(row=17, column=10) window.mainloop()
except ValueError: return False return True vcmd = lf0.register(is_okay) entsv = IntVar() ent0 = Entry(lf0, validate='key', validatecommand=(vcmd, '%P'), textvariable=entsv) ent0.bind("<Return>", end_input) ent0.grid(row=1, column=0, padx=10) ent0.focus() mee_lbl = Label(lf0, text=messtext, style='brown.TLabel') mee_lbl.grid(row=2, column=0, pady=10, padx=10) if __name__ == "__main__": root = Tk() fra0 = Frame(root) fra0.grid(row=0, column=0) LF_TEXT = 'Number of Coils' L_LIMIT = 0 U_LIMIT = 100 out_var1 = IntVar() MESS_TEXT = 'Insert +ve or -ve integer, <Return> to confirm' entry_integer(fra0, LF_TEXT, L_LIMIT, U_LIMIT, MESS_TEXT, out_var1) b2 = Button(root, text='Click after selection', command=lambda: print(out_var1.get())) b2.grid(row=1, column=0) root.mainloop()
def __init__(self, edit_playlist_name, parent, playlist_table): RegularGateListWindow.count = RegularGateListWindow.count + 1 self.updateRegularGatesWindow = tk.Toplevel(parent) self.updateRegularGatesWindow.title("定型文メンテナンス") self.updateRegularGatesWindow.protocol("WM_DELETE_WINDOW", self.close_window) width_of_window = 500 height_of_window = 350 screen_width = self.updateRegularGatesWindow.winfo_screenwidth() screen_height = self.updateRegularGatesWindow.winfo_screenheight() x_coordinate = (screen_width / 2) - (width_of_window / 2) y_coordinate = (screen_height / 2) - (height_of_window / 2) self.updateRegularGatesWindow.geometry( "%dx%d+%d+%d" % (width_of_window, height_of_window, x_coordinate, y_coordinate)) self.updateRegularGatesWindow.columnconfigure(0, weight=1) self.updateRegularGatesWindow.columnconfigure(1, weight=1) self.updateRegularGatesWindow.rowconfigure(0, weight=1) self.text_regular_gates = tk.Text(self.updateRegularGatesWindow, width=50, height=24) self.text_regular_gates.grid(row=0, column=0, rowspan=3, sticky='wnse') readFile = open('data/data_05', 'rb') rg_values = pickle.load(readFile) readFile.close() for rg in rg_values: print(rg) self.text_regular_gates.insert(END, rg + '\n') btnRegularGateFrame = tk.Frame(self.updateRegularGatesWindow) btnRegularGateFrame.grid(row=0, column=1, sticky='wn') btn_add_regular_gates = Button(btnRegularGateFrame, text="OK", command=lambda: self.save_regular_gates( edit_playlist_name, playlist_table)) btn_add_regular_gates.grid(row=0, column=0, sticky='wn', padx=(10, 0), pady=(10, 10)) btn_cancel_regular_gates = Button(btnRegularGateFrame, text="キャンセル", command=self.close_window) btn_cancel_regular_gates.grid(row=1, column=0, sticky='wn', padx=(10, 0)) btn_load_regular_gates = Button( btnRegularGateFrame, text="Default", command=lambda: self.load_regular_gates()) btn_load_regular_gates.grid(row=2, column=0, sticky='wn', padx=(10, 0), pady=(30, 10))
def __init__(self, mainWin, options): self.mainWin = mainWin parent = mainWin.parent super(DialogRssWatch, self).__init__(parent) self.parent = parent self.options = options parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.accepted = False self.transient(self.parent) self.title(_("RSS Feed Processing Control")) frame = Frame(self) # checkbox entries row = 1 # row number (to allow future plugins label(frame, 1, row, "RSS Feed:") feedSources = sorted(rssFeeds.keys()) self.cellFeed = gridCombobox(frame, 2, row, options.get("feedSource",""), values=feedSources) self.cellFeed.grid(pady=2) ToolTip(self.cellFeed, text=_("Select an RSS feed to process for item matching, formulas, and validations as selected below"), wraplength=240) row += 1 label(frame, 1, row, "Match fact text:") self.cellMatchText = gridCell(frame, 2, row, options.get("matchTextExpr","")) ToolTip(self.cellMatchText, text=_("Enter a regular expression to be matched to the text of each filing instance fact item. " "Regular expressions may contain patterns to detect, such as ab.?c, for any single character between b and c, or ab.*c for any number of characters between b and c."), wraplength=240) row += 1 label(frame, 1, row, "Formula file:") self.cellFormulaFile = gridCell(frame,2, row, options.get("formulaFileUri","")) ToolTip(self.cellFormulaFile, text=_("Select a formula linkbase to to evaluate each filing. " "The formula linkbase may contain one or more assertions, the results of which is recorded in the log file. " "If unsuccessful assertion alerts are selected and an e-mail address provided, the recipient will be notified of filings with assertions that do not pass."), wraplength=240) openFileImage = PhotoImage(file=os.path.join(mainWin.imagesDir, "toolbarOpenFile.gif")) chooseFormulaFileButton = Button(frame, image=openFileImage, width=12, command=self.chooseFormulaFile) chooseFormulaFileButton.grid(row=row, column=3, sticky=W) row += 1 openDatabaseImage = PhotoImage(file=os.path.join(mainWin.imagesDir, "toolbarOpenDatabase.gif")) for pluginXbrlMethod in pluginClassMethods("DialogRssWatch.FileChoices"): pluginXbrlMethod(self, frame, row, options, mainWin, openFileImage, openDatabaseImage) row += 1 label(frame, 1, row, "Log file:") self.cellLogFile = gridCell(frame,2, row, options.get("logFileUri","")) ToolTip(self.cellLogFile, text=_("Select a log file in which to save an activity log, including validation results, matched item text, and formula results.\n\n " "If file ends in .xml it is xml-formatted, otherwise it is text. "), wraplength=240) chooseLogFileButton = Button(frame, image=openFileImage, width=12, command=self.chooseLogFile) chooseLogFileButton.grid(row=row, column=3, sticky=W) row += 1 label(frame, 1, row, "E-mail alerts to:") self.cellEmailAddress = gridCell(frame,2, row, options.get("emailAddress","")) ToolTip(self.cellEmailAddress, text=_("Specify e-mail recipient(s) for alerts per below."), wraplength=240) propertiesImage = PhotoImage(file=os.path.join(mainWin.imagesDir, "toolbarProperties.gif")) smtpSetupButton = Button(frame, image=propertiesImage, width=12, command=self.setupSmtp) smtpSetupButton.grid(row=row, column=3, sticky=W) ToolTip(smtpSetupButton, text=_("Enter/edit settings of outgoing e-mail server (SMTP)."), wraplength=240) row += 1 label(frame, 1, row, "Latest pub date:") pubdate = getattr(options,"latestPubDate",None) self.cellLatestPubDate = gridCell(frame,2, row, str(pubdate) if pubdate else "") ToolTip(self.cellLatestPubDate, text=_("Specify pub dateTime of last processed submission. Next item to examine will be after this dateTime."), wraplength=240) clearImage = PhotoImage(file=os.path.join(mainWin.imagesDir, "toolbarDelete.gif")) clearPubDateButton = Button(frame, image=clearImage, width=12, command=self.clearPubDate) clearPubDateButton.grid(row=row, column=3, sticky=W) ToolTip(clearPubDateButton, text=_("Clear pub dateTime so that next cycle processes all entries in RSS feed."), wraplength=240) row += 1 label(frame, 2, row, "Validate:") row += 1 self.checkboxes = ( checkbox(frame, 2, row, "XBRL 2.1 and Dimensions rules", "validateXbrlRules"), checkbox(frame, 2, row+1, "Selected disclosure system rules", "validateDisclosureSystemRules"), checkbox(frame, 2, row+2, "Calculation linkbase roll-up", "validateCalcLinkbase"), checkbox(frame, 2, row+3, "Formula assertions", "validateFormulaAssertions"), # Note: if adding to this list keep ModelFormulaObject.FormulaOptions in sync ) row += 4 for pluginXbrlMethod in pluginClassMethods("DialogRssWatch.ValidateChoices"): pluginXbrlMethod(self, frame, row, options, mainWin) row += 1 label(frame, 2, row, "Alert on:") row += 1 self.checkboxes += ( checkbox(frame, 2, row, "Facts with matching text", "alertMatchedFactText"), checkbox(frame, 2, row+1, "Unsuccessful formula assertions", "alertAssertionUnsuccessful"), checkbox(frame, 2, row+2, "Validation errors", "alertValiditionError"), # Note: if adding to this list keep ModelFormulaObject.FormulaOptions in sync ) row += 3 mainWin.showStatus(None) cancelButton = Button(frame, text=_("Cancel"), width=8, command=self.close) ToolTip(cancelButton, text=_("Cancel operation, discarding changes and entries")) okButton = Button(frame, text=_("OK"), width=8, command=self.ok) ToolTip(okButton, text=_("Accept the options as entered above")) cancelButton.grid(row=row, column=1, columnspan=3, sticky=E, pady=3, padx=3) okButton.grid(row=row, column=1, columnspan=3, sticky=E, pady=3, padx=86) frame.grid(row=0, column=0, sticky=(N,S,E,W)) frame.columnconfigure(2, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100)) #self.bind("<Return>", self.ok) #self.bind("<Escape>", self.close) self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self)
def __init__(self, parent, **options): """ créer le Toplevel permettant de modifier les paramètres """ Toplevel.__init__(self, parent, **options) self.grab_set() self.transient(parent) self.title(_("Settings")) self.resizable(0, 0) self.onglets = Notebook(self) self.onglets.grid(row=0,column=0,columnspan=2) self.im_color = PhotoImage(master=self, file=COLOR) self.style = Style(self) self.style.theme_use(STYLE) self.style.configure('title.TLabel', font='CMU\ Sans\ Serif\ Demi\ Condensed 12') self.okfct = self.register(valide_entree_nb) self.nb_task = len(CONFIG.options("Tasks")) # Général (temps, police et langue) self.general = Frame(self.onglets, padding=10) self.general.pack(fill="both", expand=True, padx=10, pady=10) self.onglets.add(self.general, text=_("General")) # Temps Label(self.general, text=_("Times:"), style='title.TLabel').grid(row=0, pady=4, sticky="w") self.time_frame = Frame(self.general) self.time_frame.grid(row=1, sticky="ew") Label(self.time_frame, text=_("Work: ")).grid(row=0, column=0) self.travail = Entry(self.time_frame, width=4, justify='center', validatecommand=(self.okfct, '%d', '%S'), validate='key') self.travail.insert(0, CONFIG.get("Work", "time")) self.travail.grid(row=0, column=1, padx=(0,10)) Label(self.time_frame, text=_("Break: ")).grid(row=0, column=2) self.pause = Entry(self.time_frame, width=4, justify='center', validatecommand=(self.okfct, '%d', '%S'), validate='key') self.pause.insert(0, CONFIG.get("Break", "time")) self.pause.grid(row=0, column=3, padx=(0,10)) Label(self.time_frame, text=_("Rest: ")).grid(row=0, column=4) self.rest = Entry(self.time_frame, width=4, justify='center', validatecommand=(self.okfct, '%d', '%S'), validate='key') self.rest.insert(0, CONFIG.get("Rest", "time")) self.rest.grid(row=0, column=5) Separator(self.general, orient='horizontal').grid(row=2, sticky="ew", pady=10) # Police self.font_frame = Frame(self.general) self.font_frame.grid(row=3, pady=4, sticky="ew") Label(self.font_frame, text=_("Font:"), style='title.TLabel').pack(anchor="n", side="left") self.exemple = Label(self.font_frame, text="02:17", anchor="center", font="%s %i" % (CONFIG.get("General", "font"), CONFIG.getint("General", "fontsize")), relief="groove") self.exemple.pack(side="right") self.font_frame2 = Frame(self.general) self.font_frame2.grid(row=4) Label(self.font_frame2, text=_("Family: ")).grid(row=0, column=0, sticky="e") self.font = Entry(self.font_frame2, justify='center') self.font.insert(0, CONFIG.get("General", "font")) self.font.grid(row=0, column=1, padx=(0,10), sticky="ew") self.font.bind('<FocusOut>', self.actualise_police) self.font.bind('<Key-Return>', self.actualise_police, True) Label(self.font_frame2, text=_("Size: ")).grid(row=0, column=2, sticky="e") self.size = Entry(self.font_frame2, width=4, justify='center', validatecommand=(self.okfct, '%d', '%S'), validate='key') self.size.insert(0, CONFIG.getint("General", "fontsize")) self.size.grid(row=0, column=3, pady=2, sticky="w") self.size.bind('<FocusOut>', self.actualise_police) self.size.bind('<Key-Return>', self.actualise_police, True) Separator(self.general, orient='horizontal').grid(row=5, sticky="ew", pady=10) # Langues self.lang_frame = Frame(self.general) self.lang_frame.grid(row=6, pady=4, sticky="ew") Label(self.lang_frame, text=_("Language:"), style='title.TLabel').pack(side="left") self.lang = StringVar(self.lang_frame, LANGUES[CONFIG.get("General", "language")]) b_lang = Menubutton(self.lang_frame, textvariable=self.lang) menu = Menu(b_lang, tearoff=False) menu.add_radiobutton(label="English", variable=self.lang, value="English", command=self.change_langue) menu.add_radiobutton(label="Français", variable=self.lang, value="Français", command=self.change_langue) b_lang.configure(menu=menu) b_lang.pack(side="right") # Son self.im_son = PhotoImage(master=self, file=SON) self.im_mute = PhotoImage(master=self, file=MUTE) self.son = Frame(self.onglets, padding=10) self.son.pack(fill="both", expand=True, padx=10, pady=10) self.son.columnconfigure(1, weight=1) self.onglets.add(self.son, text=_("Sound")) Label(self.son, text=_("Sound:"), style='title.TLabel').grid(row=0, pady=4, sticky="w") self.mute = BooleanVar(self) self.mute.set(not CONFIG.get("Sound", "mute")) def mute_unmute(): if self.mute.get(): self.mute.set(False) b_son.configure(image=self.im_son) else: self.mute.set(True) b_son.configure(image=self.im_mute) b_son = Button(self.son, command=mute_unmute) mute_unmute() b_son.grid(row=0, column=1, sticky="e", pady=4) self.son_frame = Frame(self.son) self.son_frame.grid(row=1, sticky="ew", columnspan=2) self.bip = Entry(self.son_frame, justify='center') self.bip.insert(0, CONFIG.get("Sound", "beep")) self.bip.pack(side="left", fill="both", expand=True) Button(self.son_frame, text="...", width=2, command=self.choix_son).pack(side="right", padx=(2,0)) if PL[0] != "w": Separator(self.son, orient='horizontal').grid(row=2, columnspan=2, sticky="ew", pady=10) son_frame2 = Frame(self.son) son_frame2.grid(row=3, sticky="ew", columnspan=2) Label(son_frame2, text=_("Audio player: "), style='title.TLabel').pack(side="left") self.player = Entry(son_frame2, justify='center') self.player.insert(0, CONFIG.get("Sound", "player")) self.player.pack(side="right", fill="both", expand=True) # Couleurs self.couleurs = Frame(self.onglets, padding=10) self.couleurs.pack(fill="both", expand=True, padx=10, pady=10) self.onglets.add(self.couleurs, text=_("Colors")) # style des boutons de choix des couleurs self.style.configure("fond_w.TButton", background=CONFIG.get("Work", "bg")) self.style.configure("fond_p.TButton", background=CONFIG.get("Break", "bg")) self.style.configure("fond_r.TButton", background=CONFIG.get("Rest", "bg")) self.style.configure("texte_w.TButton", background=CONFIG.get("Work", "fg")) self.style.configure("texte_p.TButton", background=CONFIG.get("Break", "fg")) self.style.configure("texte_r.TButton", background=CONFIG.get("Rest", "fg")) self.couleurs.grid_columnconfigure(3, weight=3) self.couleurs.grid_rowconfigure(0, weight=1) Label(self.couleurs, text=_("Work: "), style='title.TLabel').grid(row=0, column=0, pady=4, padx=(2,10), sticky="w") Label(self.couleurs, text=_("Background: ")).grid(row=0, column=1, sticky="e", pady=(6,4)) Button(self.couleurs, width=2, command=lambda: self.choix_couleur("fond_w"), style='fond_w.TButton').grid(row=0, column=2, pady=4) Label(self.couleurs, text=_("Text: ")).grid(row=1, column=1, sticky="e") Button(self.couleurs, width=2, command=lambda: self.choix_couleur("texte_w"), style='texte_w.TButton').grid(row=1, column=2, pady=4) Separator(self.couleurs, orient='horizontal').grid(row=2, sticky="ew", pady=10, columnspan=4) Label(self.couleurs, text=_("Break: "), style='title.TLabel').grid(row=3, column=0, pady=4, padx=(2,10), sticky="w") Label(self.couleurs, text=_("Background: ")).grid(row=3, column=1, sticky="e", pady=(6,4)) Button(self.couleurs, width=2, command=lambda: self.choix_couleur("fond_p"), style='fond_p.TButton').grid(row=3, column=2, pady=4) Label(self.couleurs, text=_("Text: ")).grid(row=4, column=1, sticky="e") Button(self.couleurs, width=2, command=lambda: self.choix_couleur("texte_p"), style='texte_p.TButton').grid(row=4, column=2, pady=4) Separator(self.couleurs, orient='horizontal').grid(row=5, sticky="ew", pady=10, columnspan=4) Label(self.couleurs, text=_("Rest: "), style='title.TLabel').grid(row=6, column=0, pady=4, sticky="w", padx=(2,10)) Label(self.couleurs, text=_("Background: ")).grid(row=6, column=1, sticky="e", pady=(6,4)) Button(self.couleurs, width=2, command=lambda: self.choix_couleur("fond_r"), style='fond_r.TButton').grid(row=6, column=2, pady=4) Label(self.couleurs, text=_("Text: ")).grid(row=7, column=1, sticky="e") Button(self.couleurs, width=2, command=lambda: self.choix_couleur("texte_r"), style='texte_r.TButton').grid(row=7, column=2, pady=4) # Stats self.stats = Frame(self.onglets, padding=10) self.stats.pack(fill="both", expand=True, padx=10, pady=10) self.stats.grid_columnconfigure(2, weight=1) self.onglets.add(self.stats, text=_("Statistics")) Label(self.stats, text=_("Statistics:"), style='title.TLabel').grid(row=0, column=0, pady=4, sticky="w") tasks = [t.capitalize() for t in CONFIG.options("Tasks")] cmap = [CONFIG.get("Tasks", task) for task in tasks] for i, coul, task in zip(range(self.nb_task), cmap , tasks): Label(self.stats, text=task).grid(row=i + 1, column=0, sticky="e", padx=4, pady=4) self.style.configure("t%i.TButton" % i, background=coul) Button(self.stats, style="t%i.TButton" % i, width=2, command=lambda j=i: self.coul_stat(j)).grid(row=i + 1, column=1, pady=4) # Validation Button(self, text="Ok", command=self.valide).grid(row=1,column=1, sticky="we") Button(self, text=_("Cancel"), command=self.destroy).grid(row=1,column=0, sticky="we")
def create_tab_inicio(self): #### TAB INICIO #### self.tabFrameCurso = Notebook(self.frameInicio) self.tabFrameCurso.grid(row=2, column=0, columnspan=970) frameInscriptos = Frame(self.tabFrameCurso, padding=(10, 10)) self.tabFrameCurso.add(frameInscriptos, text="Inscriptos") frameCurDoc = Frame(self.tabFrameCurso, padding=(10, 10)) self.tabFrameCurso.add(frameCurDoc, text="Docentes") frameAsiastencias = Frame(self.tabFrameCurso, padding=(10, 10)) self.tabFrameCurso.add(frameAsiastencias, text="Asistencias") self.formAddAlumno = FormInscriptos("add") self.formRemoveAlumno = FormInscriptos("remove") self.formRemoveAlumno.id_curso = self.id_curso.get() btn_add_cursante = Button( frameInscriptos, text="[+] Agregar", width=15, command=lambda: self.formAddAlumno.show(self.id_curso.get())) btn_add_cursante.grid(row=0, column=0, columnspan=15) btn_remove_cursante = Button( frameInscriptos, text="[-] Remover", width=15, command=lambda: self.formRemoveAlumno.show(self.id_curso.get())) btn_remove_cursante.grid(row=0, column=16, columnspan=15) frameTablaInscriptos = Frame(frameInscriptos, relief="groove", padding=(5, 5)) self.tablaInscriptos = Tabla(frameTablaInscriptos, self.formRemoveAlumno, btn=False, height=400) frameTablaInscriptos.grid(row=1, column=0, columnspan=150, pady=10) btn_certificate = Button(frameInscriptos, text="Generar certificados", width=25, command=lambda: self.generate_certificate()) btn_certificate.grid(row=0, column=126, columnspan=25) self.formAddDocente = FormDocentesCurso("add") self.formRemoveDocente = FormDocentesCurso("remove") self.formRemoveDocente.id_curso = self.id_curso.get() btn_add_doc = Button( frameCurDoc, text="[+] Agregar", width=15, command=lambda: self.formAddDocente.show(self.id_curso.get())) btn_add_doc.grid(row=0, column=0, columnspan=15) btn_remove_doc = Button( frameCurDoc, text="[-] Remover", width=15, command=lambda: self.formRemoveDocente.show(self.id_curso.get())) btn_remove_doc.grid(row=0, column=16, columnspan=15) frameTablaDocentesMiembro = Frame(frameCurDoc, relief="groove", padding=(5, 5)) self.tablaDocentesMiembro = Tabla(frameTablaDocentesMiembro, self.formRemoveDocente, btn=False, height=400) frameTablaDocentesMiembro.grid(row=1, column=0, columnspan=150, pady=10) self.formAsistencias = FormAsistencias() self.formAsistencias.id_curso = self.id_curso.get() btn_asistencia = Button( frameAsiastencias, text="Cargar asistencias", width=25, command=lambda: self.formAsistencias.show(self.id_curso.get())) btn_asistencia.grid(row=0, column=0, columnspan=25) frameTablaAsistencias = Frame(frameAsiastencias, relief="groove", padding=(5, 5)) self.tablaAsistencias = Tabla(frameTablaAsistencias, self.formAsistencias, btn=False, height=400) frameTablaAsistencias.grid(row=1, column=0, columnspan=150, pady=10)
class MainWindow(): '''Parent window''' def __init__(self, master: Tk): # TODO CLEAN INIT self.master = master self.error_var = StringVar() self.master.title('Area Calculator') val_float_cmd = (self.master.register(vcmdtk.test_float), '%d', '%S', '%s') # Labels self.fx_text = Label(self.master, text="Function") self.start_range_text = Label(self.master, text="Start Range") self.end_range_text = Label(self.master, text="End Range") self.n_text = Label(self.master, text="N") self.error_text = Label(self.master, fg="red", textvariable=self.error_var, font=(None, 12)) # Buttons self.graph_button = Button(self.master, text="Graph", command=self.run_graph) # Calculate Button self.calculate_button = Button(self.master, text="Calculate", command=self.run_calculate) # Settings Button self.settings_button = Button( self.master, text='Settings', command=lambda: settingswindow.SettingsWindow()) # Help Button self.help_button = Button(self.master, text='Help') # Text Entry Fields self.start_range_entry = Entry(self.master, validate="key", validatecommand=val_float_cmd) self.end_range_entry = Entry(self.master, validate="key", validatecommand=val_float_cmd) self.n_entry = Entry(self.master, validate='key', validatecommand=(self.master.register( vcmdtk.test_int), '%d', '%S')) self.fx_entry = Entry(self.master) self.splash = StringVar(self.master) self.splash.set('Riemman Draw Location') self.menu = Combobox(self.master, textvariable=self.splash, values=["Left", "Right", "Middle"], state="readonly", width=22) # CheckButton (radiobutton) self.tk_int_var = IntVar(value=2) self.is_riemann_check_box = Radiobutton(self.master, text="Riemann", value=0, variable=self.tk_int_var, command=self.radio_selection) self.is_trapezoid_check_box = Radiobutton(self.master, text="Trapezoid", value=1, variable=self.tk_int_var, command=self.radio_selection) self.only_graph_radio = Radiobutton(self.master, text='Only Graph', value=2, variable=self.tk_int_var, command=self.radio_selection) # Breakline self.break_line = ttk.Separator(orient=HORIZONTAL) self.grid_gui() def grid_gui(self): '''grids widgets''' self.fx_text.grid(row=0, column=0) self.is_riemann_check_box.grid(row=0, column=3, sticky=W, pady=2, padx=(4, 0)) self.fx_entry.grid(row=0, column=1, sticky=W, pady=2) self.only_graph_radio.grid(row=0, column=3, sticky=E) self.start_range_text.grid(row=1, column=0) self.start_range_entry.grid(row=1, column=1, sticky=W, pady=2) self.is_trapezoid_check_box.grid(row=1, column=3, sticky=W, pady=2, padx=(4, 0), columnspan=2) self.end_range_text.grid(row=2, column=0) self.end_range_entry.grid(row=2, column=1, stick=W, pady=2) self.break_line.grid(row=2, column=3, sticky=EW, pady=2, padx=(4, 5)) self.n_text.grid(row=3, column=0) self.n_entry.grid(row=3, column=1, stick=W, pady=2) self.menu.grid(row=3, column=3, sticky=EW, pady=2, padx=(4, 2)) self.calculate_button.grid(row=4, column=0, pady=2) self.graph_button.grid(row=4, column=1, pady=2, sticky=W) self.error_text.grid(row=4, column=3) self.settings_button.grid(row=5, column=0) #self.help_button.grid(row=5, column=1, sticky=W, pady=2) def validate(self): '''Grab input from tk.entrys''' status_s, strt_val = self.val_float( self.start_range_entry.get()) # statuses are a boolean return status_e, end_val = self.val_float(self.end_range_entry.get()) status_n, n_val = self.val_n() status_fx, fx = self.val_fx() if not status_s: self.error_var.set('Invalid Start Range') return False, [] elif not status_e: self.error_var.set('Invalid End Range') return False, [] elif not status_n: self.error_var.set("Invalid N") return False, [] elif not status_fx: self.error_var.set("Invalid Function") return False, [] elif int(self.start_range_entry.get()) > int( self.end_range_entry.get()): self.error_var.set("Invalid Range") return False, [] return True, [strt_val, end_val, n_val, fx] def run_graph(self) -> None: '''Grab input from tk.entrys''' is_good, argum = self.validate() if is_good: self.error_var.set('') try: graph.draw(*argum, self.tk_int_var.get(), self.menu.get()) # pylint: disable=no-value-for-parameter except ValueError: self.error_var.set("Function does not exist in range") def radio_selection(self) -> None: '''switches state of draw_type and combobox''' selection = self.tk_int_var.get() if selection == 0: self.menu.state(['!disabled']) elif selection > 0: # Riemann(selection 0 ) is the only one that needs the combobox self.menu.state(['disabled']) def run_calculate(self) -> None: '''Runs integral root''' is_good, argum = self.validate() if is_good: integral_window.IntegralWindow(*argum) # pylint: disable=no-value-for-parameter def val_float(self, entry: str) -> Tuple[bool, Union[None, int]]: '''checks for entry''' if entry: return True, float(entry) else: return False, None def val_n(self) -> Tuple[bool, Union[None, int]]: '''Retrieves and validates number of rectangles wanted''' if self.n_entry.get(): return True, int(self.n_entry.get()) else: return False, None def val_fx(self) -> Tuple[bool, str]: '''retrieve function''' temp_fx = self.fx_entry.get().lower() if temp_fx == '': return False, temp_fx temp_fx = temp_fx.replace("^", "**").replace("log", "log10").replace("ln", "log") fx = '' for i in range(0, len(temp_fx) - 1): fx += temp_fx[i] if temp_fx[i].isdigit() and (temp_fx[i + 1] == 'x' or temp_fx[i + 1] == '(' or temp_fx[i + 1].isalpha()): fx += '*' #5x -> 5*x which python can evaluate fx += temp_fx[-1] return True, fx
def __init__(self, mainWin, options): parent = mainWin.parent super(DialogFind, self).__init__(parent) self.parent = parent self.modelManager = mainWin.modelManager self.modelXbrl = None # set when Find pressed, this blocks next prematurely if options is None: options = newFindOptions self.options = options parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry()) dialogW = int(parentGeometry.group(1)) dialogH = int(parentGeometry.group(2)) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.accepted = False self.transient(self.parent) self.title(_("Find")) self.objsList = [] # next may be tried before anything is found frame = Frame(self) # load grid findLabel = gridHdr(frame, 1, 0, "Find:", anchor="w") findLabel.grid(padx=8) self.cbExpr = gridCombobox(frame, 1, 1, values=options["priorExpressions"]) self.cbExpr.grid(columnspan=3, padx=8) ToolTip( self.cbExpr, text= _("Enter expression to find, or select from combo box drop down history list." ), wraplength=240) y = 2 # checkbox entries label(frame, 1, y, "Direction:") label(frame, 1, y + 3, "Match:") scopeLabel = label(frame, 2, y, "Scope:") ToolTip(scopeLabel, text=_("Scope for an XBRL document (instance or DTS). " "For an RSS Feed, all properties are matched. "), wraplength=240) rbUp = radiobutton(frame, 1, y + 1, "Up", "up", "direction") ToolTip(rbUp, text=_("Find/Next up (on screen) from last to first match."), wraplength=240) rbDn = radiobutton(frame, 1, y + 2, "Down", "down", "direction", rbUp.valueVar) ToolTip(rbDn, text=_("Find/Next down (on screen) from first to last match."), wraplength=240) rbText = radiobutton(frame, 1, y + 4, "Text (ignore case)", "text", "exprType") ToolTip( rbText, text=_( "Expression is a set of characters to match, ignoring case. " "The match may occur anywhere within the scope. "), wraplength=360) rbRegex = radiobutton(frame, 1, y + 5, "Regular expression", "regex", "exprType", rbText.valueVar) ToolTip( rbRegex, text= _('A regular expression to match, anywhere in the scope, ignoring case. ' 'For example, "cash" would match cash anywhere in a string (like cash on hand), ' 'whereas "^cash$" would match a full string to only contain cash. ' 'Use regular expression metacharacters, e.g., "." for any single character, ' '".*" for any number of wild characters, .{3} for exactly 3 wild characters. ' ), wraplength=360) rbXPath = radiobutton(frame, 1, y + 6, "XPath 2 expression", "xpath", "exprType", rbText.valueVar) ToolTip( rbXPath, text= _('An XPath 2 expression, where the context element, ".", is a candidate concept QName, if any concept scope is checked, ' 'and a candidate fact item, if any fact scope is checked. The XPath 2 functions do not need an "fn:" prefix (but it is defined). ' 'The XBRL Functions Registry functions do require an "xfi:" prefix. Constructors require an "xs:" prefix. ' 'The expression is considered "matched" for the candidate concept QNames or fact items where the effective boolean value of the expression is "true()". ' ), wraplength=360) self.optionControls = ( rbUp, rbDn, rbText, rbRegex, rbXPath, #checkbox(frame, 2, y + 1, "All", "all"), checkbox(frame, 2, y + 1, "Concept label", "conceptLabel"), checkbox(frame, 2, y + 2, " name", "conceptName"), checkbox(frame, 2, y + 3, " type", "conceptType"), checkbox(frame, 2, y + 4, " subs group", "conceptSubs"), checkbox(frame, 2, y + 5, " period type", "conceptPer"), checkbox(frame, 2, y + 6, " balance", "conceptBal"), checkbox(frame, 3, y + 1, "Fact label", "factLabel"), checkbox(frame, 3, y + 2, " name", "factName"), checkbox(frame, 3, y + 3, " value", "factValue"), checkbox(frame, 3, y + 4, " context", "factCntx"), checkbox(frame, 3, y + 5, " unit", "factUnit"), checkbox(frame, 3, y + 6, "Messages", "messagesLog"), # Note: if adding to this list keep Finder.FindOptions in sync ) y += 7 resultLabel = gridHdr(frame, 1, y, "Result:", anchor="w") resultLabel.grid(padx=8) self.resultText = gridCell(frame, 1, y + 1) self.resultText.grid(columnspan=3, padx=8) self.resultText.config(state="readonly") y += 2 mainWin.showStatus(None) buttonFrame = Frame(frame) buttonFrame.grid(columnspan=4, sticky=E, padx=8) findButton = Button(buttonFrame, text=_("Find"), width=12, command=self.find) ToolTip( findButton, text= _('Compile (if regular expression or XPath 2), and find first match (if down direction) or last match (if up direction). ' ), wraplength=240) nextButton = Button(buttonFrame, text=_("Next"), width=12, command=self.next) ToolTip( nextButton, text=_( 'Advance to the next matched object (in selected direction). ' ), wraplength=240) closeButton = Button(buttonFrame, text=_("Close"), width=12, command=self.close) ToolTip(closeButton, text=_('Close the find dialog. '), wraplength=240) findButton.grid(row=1, column=1, pady=3) nextButton.grid(row=1, column=2, pady=3) closeButton.grid(row=1, column=3, padx=3) frame.grid(row=0, column=0, sticky=(N, S, E, W)) frame.columnconfigure(1, weight=1) frame.columnconfigure(2, weight=1) frame.columnconfigure(3, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) if self.options["geometry"]: self.geometry(self.options["geometry"]) else: self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100)) #self.bind("<Return>", self.ok) #self.bind("<Escape>", self.close) self.protocol("WM_DELETE_WINDOW", self.close) # make this dialog non-modal self.focus_set()
fr = Frame(root) fr.grid(row=0, column=0) # LF_TEXT = 'Beer Type' # DEF_TEXT = 'Pilsner' COLOUR = '' MOD = True ''' MESS_TEXT = 'Start with capital letter,\n use at least 6 characters\n <Return> to confirm' v = StringEntry(fr,LF_TEXT,MESS_TEXT,DEF_TEXT,COLOUR,MOD) LF_TEXT = 'Number of Coils' MESS_TEXT = 'Insert +ve or -ve integer,\n <Return> to confirm' DEF_TEXT = 10 L_LIMIT = 1 U_LIMIT= 100 v = IntegerEntry(fr,LF_TEXT,MESS_TEXT,L_LIMIT,U_LIMIT,DEF_TEXT,COLOUR,MOD) ''' LF_TEXT = 'Beer Strength v/v % alcohol' DEF_TEXT = 5.0 L_LIMIT = 0.5 U_LIMIT = 10.5 MESS_TEXT = 'Insert +ve or -ve float,\n <Return> to confirm' v = FloatEntry(fr, LF_TEXT, MESS_TEXT, L_LIMIT, U_LIMIT, DEF_TEXT, COLOUR, MOD) b2 = Button(root, text='Click after selection', command=lambda: print(v.out_var.get())) b2.grid(row=2, column=0) root.mainloop()
def __init__(self): # Modify root title & prevent empty Tkinter GUI window from appearing self.root = Tk() self.root.title("Pyxe Auto-Compiler") self.root.withdraw() # Popup that gets created when you click the 'About' menu option def about_popup(): top = Toplevel() top.title("About Me") top.geometry = "500x400" top.resizable(False, False) top.iconbitmap(pyxe_favicon) about_labelframe = LabelFrame(top, labelanchor="nw", text="Developer Profile:", width=600, height=200, font=('', 10)) about_labelframe.pack(fill="both", expand=True, padx=3, pady=3) profile_photo = Image.open( resource_path( r"pyxe_resources\data\DutytoDevelop_Profile_Pic.png")) resized = profile_photo.resize((150, 150)) profile_photo_resize = ImageTk.PhotoImage(resized) canvas = Canvas(about_labelframe, height=150, width=150) canvas.create_image(75, 75, image=profile_photo_resize) canvas.image = profile_photo_resize canvas.grid(row=1, column=1, padx=3, pady=(3, 0), sticky="nsew") about_label = Label( about_labelframe, text="Name: Nicholas H.\nGitHub: DutytoDevelop", font=('', 10, 'bold')) about_label.configure(anchor="center", justify='center') about_label.grid(row=2, column=1, padx=3, pady=(0, 3), sticky="nsew") return # Open default web browser to the Pyxe GitHub repository page def open_help_page(): help_page_url = "https://GitHub.com/DutytoDevelop/Pyxe" webbrowser.open_new(help_page_url) self.menubar = Menu(self.root) self.optionmenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Options", menu=self.optionmenu) self.optionmenu.add_command(label="About...", command=about_popup) self.optionmenu.add_command(label="Help", command=open_help_page) self.optionmenu.add_separator() self.optionmenu.add_command(label="Exit", command=self.exit_compiler) self.root.config(menu=self.menubar) # A grid frame that helps layout the widgets on the root window self.frame = Frame(self.root) Grid.rowconfigure(self.root, 0, weight=1) Grid.columnconfigure(self.root, 0, weight=1) self.frame.grid_columnconfigure(2, weight=1) # These widgets make up the function allowing you to select a Python file to compile Label(self.frame, text='Python File:').grid(row=1, column=1, sticky="E") # Variable that connects that's being typed to the textbox self.program_filepath_textbox = Entry(self.frame) self.program_filepath_textbox.configure(width=80, state="disabled") self.program_filepath_textbox.grid(row=1, column=2, sticky='EW', padx=(0, 5), pady=5, ipadx=5) self.file_selection_button = Button( self.frame, text='Select Python File', command=lambda: self.python_get_filepath_of_file( title="Select Python File", initialdir=project_dir, filetypes=[("Python File", "*.py")], element=self.program_filepath_textbox)) self.file_selection_button.configure(width=20) self.file_selection_button.grid(row=1, column=3, padx=5, pady=5, sticky="EW") # These widgets make up the function allowing you to select a picture to be the program's favicon Label(self.frame, text='Program Icon:').grid(row=2, column=1, sticky="E") self.icon_filepath_textbox = Entry(self.frame) self.icon_filepath_textbox.configure(width=80, state="disabled") self.icon_filepath_textbox.grid(row=2, column=2, sticky='EW', padx=(0, 5), pady=5, ipadx=5) self.python_icon_selector = Button( self.frame, text='Select Program Icon', command=lambda: self.python_get_filepath_of_file( title="Select Program Icon", initialdir=project_dir, filetypes=[("Pictures", "*.jpg;*.jpeg,*.png;*.svg;*.ico")], element=self.icon_filepath_textbox)) self.python_icon_selector.configure(width=20) self.python_icon_selector.grid(row=2, column=3, padx=5, pady=5, sticky="EW") # These widgets make up the function allowing you to give a name to the executable Label(self.frame, text='Program Name:').grid(row=3, column=1, sticky="E") self.program_name_textbox = Entry(self.frame) self.program_name_textbox.configure(width=80) self.program_name_textbox.grid(row=3, column=2, sticky='EW', padx=(0, 5), pady=5, ipadx=5) # Radio button options will return a boolean and GUI converts that into '--onefile' or '--onedir' parameter self.radiobtn_compile_option = BooleanVar() self.onefile_compile = Radiobutton( self.frame, text="One File", variable=self.radiobtn_compile_option, value=True, command=None) self.onefile_compile.grid(row=3, column=3, sticky='W', padx=(0, 5), pady=5, ipadx=5) self.onedir_compile = Radiobutton( self.frame, text="One Dir", variable=self.radiobtn_compile_option, value=False, command=None) self.onedir_compile.grid(row=3, column=3, sticky='E', padx=(0, 5), pady=5, ipadx=5) self.radiobtn_compile_option.set( True) # Set this option as the default option # These widgets make up the function allowing you to select where you want to create the executable Label(self.frame, text='Build Folder:').grid(row=4, column=1, sticky="E") self.build_directory_textbox = Entry(self.frame) self.build_directory_textbox.configure(state='disabled') self.build_directory_textbox.grid(row=4, column=2, sticky='EW', padx=(0, 5), pady=5, ipadx=5) select_directory = Button(self.frame, text="Select Directory", command=lambda: self.set_directory_path( title="Select Directory", initialdir=project_dir, element=self.build_directory_textbox)) select_directory.configure(width=20) select_directory.grid(row=4, column=3, sticky="EW", padx=10, pady=5, ipadx=5) # These widgets make up the function allowing you to select where you add the data Label(self.frame, text='Data Folders:').grid(row=5, column=1, sticky="E") self.data_folder_directory_textbox = Entry(self.frame) self.data_folder_directory_textbox.configure(state='disabled') self.data_folder_directory_textbox.grid(row=5, column=2, sticky='EW', padx=(0, 5), pady=5, ipadx=5) add_data_folder = Button( self.frame, text="Add Folder", command=lambda: self.set_directory_path( title="Add Path", initialdir=project_dir, element=self.data_folder_directory_textbox, append_directory=True)) add_data_folder.configure(width=8) add_data_folder.grid(row=5, column=3, sticky="W", padx=10, pady=5, ipadx=5) clear_data_folder = Button( self.frame, text="Clear", command=lambda: self.set_directory_path( title="Add Directory", initialdir=project_dir, element=self.data_folder_directory_textbox, append_directory=True)) clear_data_folder.configure(width=8) clear_data_folder.grid(row=5, column=3, sticky="E", padx=10, pady=5, ipadx=5) # These widgets make up the function that allows you to compile the executable self.compile_button = Button( self.frame, text="Compile", command=lambda: thread_function(function=self.compile_executable)) self.compile_button.grid(row=6, column=1, columnspan=2, sticky='EW', padx=(10, 5), pady=5, ipadx=5) self.compilation_section = LabelFrame(self.frame, text='Console Output:', labelanchor="nw") self.compilation_section.configure(height=11) self.compilation_section.grid(row=7, column=1, columnspan=4, sticky="NESW", padx=10, pady=10) self.compiler_text = ScrolledText(self.compilation_section, yscrollcommand=True, bg='lightgrey', font=('Nimbus Mono L', 9), fg='green') self.compiler_text.configure(height=11, state="disabled") self.compiler_text.bind("<Key>", lambda e: "break") self.compiler_text.yview_pickplace("end") self.compiler_text.pack(expand=True, fill="both", padx=5, pady=7) # This widget make up the function allowing you to discontinue compiling the executable self.quit_button = Button(self.frame, text="Quit", command=lambda: self.exit_compiler()) self.quit_button.grid(row=6, column=3, sticky='EW', padx=10, pady=5, ipadx=5) # Expand self.frame to fit the root window self.frame.grid(sticky="nsew", padx=2, pady=2) # GUI size and placement on the screen self.screen_width = GetSystemMetrics(0) self.screen_height = GetSystemMetrics(1) self.app_width = 800 self.app_height = 430 self.root.geometry( str(self.app_width) + "x" + str(self.app_height) + "+" + str(int((self.screen_width / 2) - (self.app_width / 2))) + "+" + str(int((self.screen_height / 2) - (self.app_height / 2)))) # The icon that appears in the corner of the executable self.root.iconbitmap(pyxe_favicon) # Restricts the GUI from being resized self.root.resizable(False, False) # Get rid of extra GUI window when creating dialog boxes self.root.deiconify()
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("") self.style = Style() self.style.theme_use("clam") self.pack(fill=BOTH, expand=1) self.labelU = Label(self, text="U:") self.labelP = Label(self, text="P:") self.entryUsername = Entry(self) self.entryUsername.config(relief='flat') self.entryUsername.focus_set() self.entryUsername.bind('<Return>', lambda event: self.entryPassword.focus_set()) self.entryPassword = Entry(self) self.entryPassword.config(relief='flat', show='•') self.entryPassword.bind( '<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton = Button( self, text="Login", command=lambda: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton.bind( '<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton.config(width=6) self.quitbutton = Button(self, text="Quit", command=lambda: self.quit()) self.quitbutton.config(width=6) self.mailIconRed = PhotoImage(file="mail.gif") self.labelRed = Label(self, image=self.mailIconRed) self.mailIconGray = PhotoImage(file="mail2.gif") self.labelGray = Label(self, image=self.mailIconGray) self.labelKarma = Label(self, text='•') self.labelU.grid(row=0, column=0) self.entryUsername.grid(row=0, column=1) self.labelP.grid(row=1, column=0) self.entryPassword.grid(row=1, column=1, pady=4) self.newbutton.grid(row=2, column=1) self.quitbutton.grid(row=3, column=1, pady=4) ''' sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() w=150 h=112 x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y-50)) ''' def login(self, username, password): #print('U: ' + username) self.username = username if username == '': #print('Please enter a username') self.entryUsername.focus_set() elif password == '': #print('Please enter a password') self.entryPassword.set_focus() if username != '' and password != '': #print('Attempting login for ' + username) try: self.USERAGENT = username + ' scans his inbox for new mail.' self.r = praw.Reddit(self.USERAGENT) #self.r.config._ssl_url = None self.r.login(username, password) #print('You have logged in as ' + username) self.labelU.grid_forget() self.labelP.grid_forget() self.entryUsername.grid_forget() self.entryPassword.grid_forget() self.newbutton.grid_forget() self.quitbutton.grid_forget() self.usernamelabel = Label(self, text=username) self.usernamelabel.grid(row=0, column=0, pady=10, padx=30) self.quitbutton.grid(row=1, column=0) self.labelKarma.grid(row=3, column=0) self.playedSound = 'false' self.loop() except praw.errors.InvalidUserPass: pass #print('Invalid username or password') def loop(self): while True: try: #print('Starting new search') hasmail = 'false' for msg in self.r.get_unread(limit=None): hasmail = 'true' if hasmail == 'true': #print("You've got mail!") if self.playedSound == 'false': winsound.PlaySound('pop.wav', winsound.SND_FILENAME) self.playedSound = 'true' self.labelGray.grid_forget() self.labelRed.grid(row=2, column=0) if hasmail == 'false': self.playedSound = 'false' #print('No mail!') self.labelRed.grid_forget() self.labelGray.grid(row=2, column=0) self.user = self.r.get_redditor(self.username) lkarma = str(self.user.link_karma) ckarma = str(self.user.comment_karma) lkarma = self.karmaRound(lkarma) ckarma = self.karmaRound(ckarma) karmastring = lkarma + ' • ' + ckarma self.labelKarma.config(text=karmastring) time.sleep(10) except Exception: time.sleep(10) def karmaRound(self, karma): if len(karma) > 4 and len(karma) < 7: tstring = karma[:-3] tstring2 = karma[-3:] karma = tstring + '.' + tstring2[:2] + 'K' return karma if len(karma) > 6: tstring = karma[:-6] tstring2 = karma[-6:] karma = tstring + '.' + tstring2[:2] + 'M' return karma else: return karma
class Query(Toplevel): """Base class for getting verified answer from a user. For this base class, accept any non-blank string. """ def __init__(self, parent, title, message, *, text0='', used_names={}, _htest=False, _utest=False): """Create modal popup, return when destroyed. Additional subclass init must be done before this unless _utest=True is passed to suppress wait_window(). title - string, title of popup dialog message - string, informational message to display text0 - initial value for entry used_names - names already in use _htest - bool, change box location when running htest _utest - bool, leave window hidden and not modal """ self.parent = parent # Needed for Font call. self.message = message self.text0 = text0 self.used_names = used_names Toplevel.__init__(self, parent) self.withdraw() # Hide while configuring, especially geometry. self.title(title) self.transient(parent) if not _utest: # Otherwise fail when directly run unittest. self.grab_set() _setup_dialog(self) if self._windowingsystem == 'aqua': self.bind("<Command-.>", self.cancel) self.bind('<Key-Escape>', self.cancel) self.protocol("WM_DELETE_WINDOW", self.cancel) self.bind('<Key-Return>', self.ok) self.bind("<KP_Enter>", self.ok) self.create_widgets() self.update_idletasks() # Need here for winfo_reqwidth below. self.geometry( # Center dialog over parent (or below htest box). "+%d+%d" % (parent.winfo_rootx() + (parent.winfo_width() / 2 - self.winfo_reqwidth() / 2), parent.winfo_rooty() + ((parent.winfo_height() / 2 - self.winfo_reqheight() / 2) if not _htest else 150))) self.resizable(height=False, width=False) if not _utest: self.deiconify() # Unhide now that geometry set. self.entry.focus_set() self.wait_window() def create_widgets(self, ok_text='OK'): # Do not replace. """Create entry (rows, extras, buttons. Entry stuff on rows 0-2, spanning cols 0-2. Buttons on row 99, cols 1, 2. """ # Bind to self the widgets needed for entry_ok or unittest. self.frame = frame = Frame(self, padding=10) frame.grid(column=0, row=0, sticky='news') frame.grid_columnconfigure(0, weight=1) entrylabel = Label(frame, anchor='w', justify='left', text=self.message) self.entryvar = StringVar(self, self.text0) self.entry = Entry(frame, width=30, textvariable=self.entryvar) self.error_font = Font(name='TkCaptionFont', exists=True, root=self.parent) self.entry_error = Label(frame, text=' ', foreground='red', font=self.error_font) # Display or blank error by setting ['text'] =. entrylabel.grid(column=0, row=0, columnspan=3, padx=5, sticky=W) self.entry.grid(column=0, row=1, columnspan=3, padx=5, sticky=W + E, pady=[10, 0]) self.entry_error.grid(column=0, row=2, columnspan=3, padx=5, sticky=W + E) self.create_extra() self.button_ok = Button(frame, text=ok_text, default='active', command=self.ok) self.button_cancel = Button(frame, text='Cancel', command=self.cancel) self.button_ok.grid(column=1, row=99, padx=5) self.button_cancel.grid(column=2, row=99, padx=5) def create_extra(self): pass # Override to add widgets. def showerror(self, message, widget=None): #self.bell(displayof=self) (widget or self.entry_error)['text'] = 'ERROR: ' + message def entry_ok(self): # Example: usually replace. "Return non-blank entry or None." entry = self.entry.get().strip() if not entry: self.showerror('blank line.') return None return entry def ok(self, event=None): # Do not replace. '''If entry is valid, bind it to 'result' and destroy tk widget. Otherwise leave dialog open for user to correct entry or cancel. ''' self.entry_error['text'] = '' entry = self.entry_ok() if entry is not None: self.result = entry self.destroy() else: # [Ok] moves focus. (<Return> does not.) Move it back. self.entry.focus_set() def cancel(self, event=None): # Do not replace. "Set dialog result to None and destroy tk widget." self.result = None self.destroy() def destroy(self): self.grab_release() super().destroy()
canvas.itemconfigure(yellow_lamp, fill='yellow') elif color == 'yellow': color = 'red' canvas.itemconfigure(yellow_lamp, fill='black') canvas.itemconfigure(red_lamp, fill='red') color = 'red' root = Tk() root.title("Traffic Light") frame = Frame(root) frame.pack() canvas = Canvas(frame, width=150, height=300) canvas.create_rectangle(50, 20, 150, 280, fill='gray') red_lamp = canvas.create_oval(70, 40, 130, 100, fill='red') yellow_lamp = canvas.create_oval(70, 120, 130, 180, fill='black') green_lamp = canvas.create_oval(70, 200, 130, 260, fill='black') button = Button(frame, text='Change', command=do_button_press) button.grid(row=0, column=0) canvas.grid(row=0, column=1) root.mainloop()
def __init__(self, title): root = Tk() root.title(title) root.focus_set() root.rowconfigure(0, weight=0) root.columnconfigure(0, weight=1) root.rowconfigure(1, weight=1) self._root = root self.menubar = Frame(root) self.menubar.grid(row=0, column=0, sticky=(W, E)) self.menubar['takefocus'] = False quit_button = Button(self.menubar, text='Quit', command=self.quit) quit_button.grid(row=0, column=0) self._menucolumn = 1 self.views = list() self.paned_win = PanedWindow(root, orient=HORIZONTAL) self.paned_win.grid(row=1, column=0, sticky=(N, S, W, E)) self._query = None self._accept_func = None self.sidebar_views = dict() self.sidebar_count = 0 self.sidebar = PanedWindow(self.paned_win) self.paned_win.add(self.sidebar, weight=1) self.tabs = Notebook(self.paned_win) self.tabs.enable_traversal() self.paned_win.add(self.tabs, weight=5) self.root = self.tabs