def createStatusBar( self ): """ Create a status bar containing only one text label at the bottom of the main window. """ if BibleOrgSysGlobals.debugFlag and debuggingThisModule: print( exp("createStatusBar()") ) Style().configure('HTMLStatusBar.TFrame', background='yellow') Style().configure( 'StatusBar.TLabel', background='white' ) #Style().map("Halt.TButton", foreground=[('pressed', 'red'), ('active', 'yellow')], #background=[('pressed', '!disabled', 'black'), ('active', 'pink')] ) self.statusBar = Frame( self, cursor='hand2', relief=tk.RAISED, style='HTMLStatusBar.TFrame' ) self.statusTextLabel = Label( self.statusBar, relief=tk.SUNKEN, textvariable=self._statusTextVar, style='StatusBar.TLabel' ) #, font=('arial',16,tk.NORMAL) ) self.statusTextLabel.pack( side=tk.LEFT, fill=tk.X ) # style='Halt.TButton', self.forwardButton = Button( self.statusBar, text='Forward', command=self.doGoForward ) self.forwardButton.pack( side=tk.RIGHT, padx=2, pady=2 ) self.backButton = Button( self.statusBar, text='Back', command=self.doGoBackward ) self.backButton.pack( side=tk.RIGHT, padx=2, pady=2 ) self.statusBar.pack( side=tk.BOTTOM, fill=tk.X ) #self.setReadyStatus() self.setStatus() # Clear it
class Form(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.parent.title("Example Form") self.pack(fill=BOTH, expand=True) f = Frame(self) f.pack(fill=X) l = Label(f, text='First Name', width=10) l.pack(side=LEFT, padx=5, pady=5) self.firstName = Entry(f) self.firstName.pack(fill=X, padx=5, expand=True) f = Frame(self) f.pack(fill=X) l = Label(f, text='Last Name', width=10) l.pack(side=LEFT, padx=5, pady=5) self.lastName = Entry(f) self.lastName.pack(fill=X, padx=5, expand=True) f = Frame(self) f.pack(fill=X) l = Label(f, text='Full Name', width=10) l.pack(side=LEFT, padx=5, pady=5) self.fullName = Label(f, text='ALEX POOPKIN', width=10) self.fullName.pack(fill=X, padx=5, expand=True) f = Frame(self) f.pack(fill=X) l = Label(f, text='', width=10) l.pack(side=LEFT, padx=5, pady=0) self.errorMessage = Label(f, text='Invalid character int the name!', foreground='red', width=30) self.errorMessage.pack(fill=X, padx=5, expand=True) f = Frame(self) f.pack(fill=X) b = Button(f, text='Close', command=lambda : self.parent.quit()) b.pack(side=RIGHT, padx=5, pady=10) b['default'] = ACTIVE b.focus_set() self.clearButton = Button(f, text='Clear') self.clearButton.pack(side=RIGHT, padx=5, pady=10) self.clearButton['state'] = DISABLED self.sendButton = Button(f, text='Send') self.sendButton.pack(side=RIGHT, padx=5, pady=10)
def create_widgets(self): # Call from override, if any. # Bind to self 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.entry.focus_set() self.error_font = Font(name='TkCaptionFont', exists=True, root=self.parent) self.entry_error = Label(frame, text=' ', foreground='red', font=self.error_font) self.button_ok = Button( frame, text='OK', default='active', command=self.ok) self.button_cancel = Button( frame, text='Cancel', command=self.cancel) 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.button_ok.grid(column=1, row=99, padx=5) self.button_cancel.grid(column=2, row=99, padx=5)
def initialize_ui(self): default_padding = {'padx': 10, 'pady' : 10} customer_frame = Frame(self) self.customer_id_label = Label(customer_frame, text = "Customer id:", style="BW.TLabel") self.customer_id_label.pack(default_padding, side = LEFT) self.customer_id_value = Label(customer_frame,style="BW.TLabel") self.customer_id_value["textvariable"] = self.controller.customer_id self.customer_id_value.pack(default_padding, side = LEFT) customer_frame.pack(expand = True, fill = "x") self.take_picture_frame = Frame(self, border = 10) self.picture_mode = IntVar() Radiobutton(self.take_picture_frame, text = "Light", variable = self.picture_mode, value = 1).pack(side = LEFT) Radiobutton(self.take_picture_frame, text = "Dark", variable = self.picture_mode, value = 2).pack(side = LEFT) self.button_take_picture = Button(self.take_picture_frame, text = "Take picture", command = self.take_picture) self.button_take_picture.pack(expand = True, fill = "x", side = BOTTOM) self.take_picture_frame.pack(expand = True) self.button_update = Button(self, text = "Update", command = self.controller.run_update_script) self.button_update.pack(expand = True, fill = "x")
def add_pairs( self, parent ) : if not self.pairs : self.pairs = LabelFrame(parent, text='Pairs') self.pairs_text = Text( self.pairs, width=50, height=8, #bg=projectBgColor, #fg=projectFgColor, font=("nimbus mono bold","11") ) self.pairs_save_button = Button(self.pairs, text="Save", command = self.writepair ) self.pairs_load_button = Button(self.pairs, text="Load", command = self.readpair ) #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 ) #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 ) self.pairs_load_button.grid( row=5, column=5, padx=10, pady=5 ) self.pairs_save_button.grid( row=5, column=6, padx=10, pady=5 ) self.pairs_text.grid( row=1, rowspan=3, column=1, columnspan=7, padx=5, pady=5 ) self.pairs.grid(row=7,column=0, columnspan=6, sticky=W, padx=20, pady=10 )
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 __init__(self): super().__init__() self.title('Treepace Tree Transformation GUI Demo') self.geometry('640x400') self.resizable(False, False) self.tree_frame = Frame() self.tree_button = Button(self.tree_frame, text="Load tree", command=self.load) self.tree_button.pack(expand=True, fill=BOTH) self.tree_text = Text(self.tree_frame, width=20) self.tree_text.pack(expand=True, fill=BOTH) self.tree_text.insert('1.0', DEFAULT_TREE) self.tree_frame.pack(side=LEFT, expand=True, fill=BOTH) self.program_frame = Frame() self.program_button = Button(self.program_frame, text="Transform", command=self.transform) self.program_button.pack(expand=True, fill=BOTH) self.program_text = Text(self.program_frame, width=60, height=8) self.program_text.pack(expand=True, fill=BOTH) self.program_text.insert('1.0', DEFAULT_PROGRAM) self.tv = Treeview(self.program_frame) self.tv.pack(expand=True, fill=BOTH) self.program_frame.pack(side=LEFT, expand=True, fill=BOTH) GuiNode.tv = self.tv self.load()
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 __init__(self, parent, music_filepath): Frame.__init__(self, parent) self.player = Player(music_filepath) title = os.path.basename(music_filepath) label = tkinter.Label(self, text=title, width=30) label.pack(side=LEFT) padx = 10 #image = tkinter.PhotoImage(file=icon_play) play_button = Button(self, text="Play")#image=image) play_button.pack(side=LEFT, padx=padx) play_button.bind("<Button-1>", self.play) #image = tkinter.PhotoImage(file=icon_pause) #pause_button = Button(self, text="Pause")#image=image) #pause_button.pack(side=LEFT, padx=padx) #pause_button.bind("<Button-1>", self.pause) #self.pausing = False #image = tkinter.PhotoImage(file=icon_stop) stop_button = Button(self, text="Stop")#image=image) stop_button.pack(side=LEFT, padx=padx) stop_button.bind("<Button-1>", self.stop)
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)
def _replace_dialog(parent): # htest # from tkinter import Toplevel, Text, END, SEL from tkinter.ttk import Frame, Button top = Toplevel(parent) top.title("Test ReplaceDialog") x, y = map(int, parent.geometry().split('+')[1:]) top.geometry("+%d+%d" % (x, y + 175)) # mock undo delegator methods def undo_block_start(): pass def undo_block_stop(): pass frame = Frame(top) frame.pack() text = Text(frame, inactiveselectbackground='gray') text.undo_block_start = undo_block_start text.undo_block_stop = undo_block_stop text.pack() text.insert("insert","This is a sample sTring\nPlus MORE.") text.focus_set() def show_replace(): text.tag_add(SEL, "1.0", END) replace(text) text.tag_remove(SEL, "1.0", END) button = Button(frame, text="Replace", command=show_replace) button.pack()
class DateWidget(Frame): """Gets a date from the user.""" def __init__(self, master): """Make boxes, register callbacks etc.""" Frame.__init__(self, master) self.label = Label(self, text="När är du född?") self.label.pack() self.entry_text = StringVar() self.entry_text.trace("w", lambda *args: self.onEntryChanged()) self.entry = Entry(self, width=date_entry_width, textvariable=self.entry_text) self.entry.insert(0, "ÅÅÅÅ-MM-DD") self.entry.pack(pady=small_pad) self.button = Button(self, text="Uppdatera", command=lambda: self.onDateChanged()) self.button.pack() self.entry.focus_set() self.entry.select_range(0, END) self.entry.bind("<Return>", lambda x: self.onDateChanged()) def setListener(self, pred_view): """Select whom to notify when a new date is entered.""" self.pred_view = pred_view def onDateChanged(self): """Notifies the PredictionWidget that the date has been changed.""" try: date = datetime.datetime.strptime(self.entry.get(), "%Y-%m-%d").date() self.pred_view.update(date) except ValueError: self.entry.configure(foreground="red") def onEntryChanged(self): """Reset the text color.""" self.entry.configure(foreground="")
def initialize(self): self.top = Frame(self.canvas) self.top.grid(row=0,column=0, columnspan=3, padx=5, pady=10) self.label = Label(self.top, text="PATH :", anchor="w", fg="black") self.label.pack(side=LEFT) self.pathEntry = Entry(self.top, textvariable=self.trackPath, width="75") self.pathEntry.pack(side=LEFT, padx=5) self.sliderFrame = Frame(self.canvas) self.sliderFrame.grid(row=1, column=0,columnspan=4, pady=10, padx=5) for i in range(10): slider = SliderFrequency(self.sliderFrame, self.freqs[i],10.0,0.0,20.0, i) self.sliders.append(slider) self.infoLabel = Label(self.canvas, text="", textvariable=self.info) self.infoLabel.grid(row=2, column=0,columnspan=2) self._afficheInfo("Choose music to equalize") self.startBtn = Button(self.canvas, text="Start", command=self.start) self.startBtn.grid(row=2, column=2, pady=10) self.startBtn = Button(self.canvas, text="Reset", command=self.reset) self.startBtn.grid(row=2, column=3, pady=10)
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 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)
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, 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 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, url): self.url = url self.root = Tk() self.root.title("验证码") while True: try: image_bytes = urlopen(self.url).read() break except socket.timeout: print('获取验证码超时:%s\r\n重新获取.' % (self.url)) continue except urllib.error.URLError as e: if isinstance(e.reason, socket.timeout): print('获取验证码超时:%s\r\n重新获取.' % (self.url)) continue # internal data file data_stream = io.BytesIO(image_bytes) # open as a PIL image object self.pil_image = Image.open(data_stream) # convert PIL image object to Tkinter PhotoImage object self.tk_image = ImageTk.PhotoImage(self.pil_image) self.label = Label(self.root, image=self.tk_image, background='brown') self.label.pack(padx=5, pady=5) self.button = Button(self.root, text="刷新验证码", command=self.refreshImg) self.button.pack(padx=5, pady=5) randCodeLable = Label(self.root, text="验证码:") randCodeLable.pack(padx=5, pady=5) self.randCode = Entry(self.root) self.randCode.pack(padx=5, pady=5) self.loginButton = Button(self.root, text="登录", default=tkinter.ACTIVE) self.loginButton.pack(padx=5, pady=5)
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, 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()
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()
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 __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)
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 Main(Frame): """Main class for our browser. Note that we inherit from Frame, making this a Frame object. """ def __init__(self, master): Frame.__init__(self, master) self.master = master self.master.title("Browser") self.header = {"User-Agent":"Tkinter Browser 0.1"} # Here we make our widgets. self.top_frame = Frame(self) self.url_frame = Frame(self.top_frame) self.url_label = Label(self.url_frame, text="Url: ", anchor="n") self.url_entry = Entry(self.url_frame, width=80) self.url_button = Button(self.url_frame, text="Go", command=self.go_button) self.bottom_frame = Frame(self) self.text_field = Text(self.bottom_frame) #Here we pack our widgets. self.top_frame.pack(side="top", padx=15, pady=15) self.url_frame.pack(anchor="center") self.bottom_frame.pack(side="bottom", fill="both", expand=True) self.text_field.pack(side="bottom", fill="both", expand=True) self.url_label.pack(side="left") self.url_entry.pack(side="left", fill="x", expand=True) self.url_button.pack(side="left", padx=5) self.text_field.config(state="disabled", padx=5, pady=5) def go_button(self): url = self.url_entry.get() if url: if "http://" not in url: url = "http://"+url page_text = self.get_page(url) self.text_field.config(state="normal") self.text_field.delete(1.0, "end") self.text_field.insert("end", page_text) self.text_field.config(state="disable") def get_page(self, url): s = requests.Session() resp = s.get(url, headers=self.header) data = resp.text soup = bs(data, "html.parser") page_text = soup.find_all(text=True) page_text = filter(self.visible, page_text) return "".join([str(i)+'\n' for i in page_text]) def visible(self, e): if e.parent.name in ('style', 'script', '[document]', 'head', 'title'): return False elif re.match('<!--.*-->', str(e.encode('utf-8'))): return False return True
def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.master.title('Moving Files') start_label = Label(self.master, text='start location') end_label = Label(self.master, text='end location') start_label.grid(row=0, column=1) end_label.grid(row=2, column=1) self.start_label_var = Label(self.master, width=25, anchor=CENTER, relief=RIDGE) self.end_label_var = Label(self.master, width=25, anchor=CENTER, relief=RIDGE) self.start_label_var.grid(row=1, column=1, padx=(5, 10)) self.end_label_var.grid(row=3, column=1, padx=(5, 10)) #----------------------------------------------------------------- self.start_point = '' self.end_point = '' #----------------------------------------------------------------- # Start and end location start_button = Button(self.master, text='start_location', width=17, command=self.start_location) end_button = Button(self.master, text='end location', width=17, command=self.end_location) start_button.grid(row=1, column=0, padx=(10, 0)) end_button.grid(row=3, column=0, padx=(10, 0)) # Radio buttons and entry fields self.radio_button_status = IntVar() radio_button_0 = Radiobutton(self.master, \ text='Put files in folder named as their extension\n(Enter file extensions separated with "space")', variable=self.radio_button_status, value=0, command=self.radio_status) radio_button_0.select() radio_button_1 = Radiobutton(self.master, text='Associate folder name to extensions\n(images=jpg,png video=mp4)', variable=self.radio_button_status, value=1, command=self.radio_status) radio_button_2 = Radiobutton(self.master, text='Just move files. Do not create new folders\n(png jpg mp4)', variable=self.radio_button_status, value=2, command=self.radio_status) radio_button_0.grid(row=4, columnspan=2, sticky=W, padx=(10, 0), pady=(5, 0)) self.extension = Entry(self.master, relief=GROOVE, state=NORMAL) self.extension.grid(row=5, columnspan=2, padx=(15, 10), pady=(2, 2), sticky=(W, E)) radio_button_1.grid(row=6, columnspan=2, sticky=W, padx=(10, 10)) self.key_value_entry = Entry(self.master, relief=GROOVE, state=DISABLED) self.key_value_entry.grid(row=7, columnspan=2, padx=(15, 10), pady=(2, 2), sticky=(W, E)) #self.master.rowconfigure(6, weight=1) radio_button_2.grid(row=8, columnspan=2, padx=(10, 0), pady=(0, 2), sticky=W) self.extension_2 = Entry(self.master, relief=GROOVE, state=DISABLED) self.extension_2.grid(row=9, columnspan=2, padx=(15, 10), pady=(2, 10), sticky=(W, E)) # Button for moving files move_button = Button(self.master, text='Move Files', width=30, command=self.moving_files) move_button.grid(row=10, columnspan=2, pady=(0, 6))
def initUI(self): self.parent.title("GPA Calculator") self.style = Style() self.style.theme_use("default") frame = Frame(self, relief=RAISED, borderwidth=1) frame.pack(fill=BOTH, expand=True) self.pack(fill=BOTH, expand=True) calculateButton = Button(self, text="Calculate", command=lambda: self.onPressCalc) calculateButton.pack(side=RIGHT, padx=5, pady=5)
def addButton(self, **kw): return self.add(Button(**kw))
def __init__(self, master, pwd): """Create the mailbox manager dialog.""" Toplevel.__init__(self, master, class_="CheckMails") self.title(_("Mailbox Manager")) self.minsize(200, 10) self.pwd = pwd self.resizable(False, False) self.protocol("WM_DELETE_WINDOW", self.quit) self.im_add = PhotoImage(master=self, file=ADD) self.im_del = PhotoImage(master=self, file=DEL) self.im_edit = PhotoImage(master=self, file=EDIT) self.mailboxes = {} active = CONFIG.get("Mailboxes", "active").split(", ") inactive = CONFIG.get("Mailboxes", "inactive").split(", ") while "" in active: active.remove("") while "" in inactive: inactive.remove("") active.sort() inactive.sort() self.frame = Frame(self) self.columnconfigure(0, weight=1) self.frame.columnconfigure(1, weight=1) self.frame.grid(row=0, column=0, padx=10, pady=10, sticky="eswn") i = -1 for i, box in enumerate(active): c = Checkbutton(self.frame) c.state(('selected',)) c.grid(row=i, column=0, pady=4, padx=(4, 0)) l = Label(self.frame, text=box) l.grid(row=i, column=1, padx=4, pady=4) b_edit = Button(self.frame, image=self.im_edit, width=1, command=lambda m=box: self.mailbox_info(m)) b_edit.grid(row=i, column=2, padx=4, pady=4) b_del = Button(self.frame, image=self.im_del, width=1, command=lambda m=box: self.del_mailbox(m)) b_del.grid(row=i, column=3, padx=4, pady=4) self.mailboxes[box] = [c, l, b_edit, b_del] for box in inactive: i += 1 c = Checkbutton(self.frame) c.grid(row=i, column=0, pady=4, padx=(4, 0)) l = Label(self.frame, text=box) l.grid(row=i, column=1, padx=4, pady=4) b_edit = Button(self.frame, image=self.im_edit, width=1, command=lambda m=box: self.mailbox_info(m)) b_edit.grid(row=i, column=2, padx=4, pady=4) b_del = Button(self.frame, image=self.im_del, width=1, command=lambda m=box: self.del_mailbox(m)) b_del.grid(row=i, column=3, padx=4, pady=4) self.mailboxes[box] = [c, l, b_edit, b_del] self.b_add = Button(self.frame, image=self.im_add, command=self.mailbox_info, width=1) self.b_add.grid(row=i + 1, column=0, columnspan=4, pady=4, padx=4, sticky='w')
def add_buttons(self, hide_plot_button): '''Add the buttons at the bottom of the UI''' myfrm = Frame(self.get_win()) myfrm.grid(row=self.get_row(), column=0, pady=(5, 5)) abtn = Button(myfrm, text="Fit", command=self.fit) abtn.grid(row=self.get_row(), column=0, columnspan=1, padx=(20, 20), pady=(5, 5)) if hide_plot_button is False: abtn = Button(myfrm, text="Plot", command=self.plot) abtn.grid(row=self.get_row(), column=1, columnspan=1, padx=(20, 20), pady=(5, 5)) abtn = Button(myfrm, text="Conf", command=self.conf) abtn.grid(row=self.get_row(), column=2, columnspan=1, padx=(20, 20), pady=(5, 5)) abtn = Button(myfrm, text="Quit", command=self.quit) abtn.grid(row=self.get_row(), column=3, columnspan=1, padx=(20, 20), pady=(5, 5)) abtn = Button(myfrm, text="Reset", command=self.reset) abtn.grid(row=self.get_row(), column=4, columnspan=1, padx=(20, 20), pady=(5, 5)) abtn = Button(myfrm, text="Cancel", command=self.cancel) abtn.grid(row=self.get_row(), column=5, columnspan=1, padx=(20, 20), pady=(5, 5))
class PyCoin(Frame): coin_balance = 0 def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.parent.protocol("WM_DELETE_WINDOW", self.quit) self.coin_balance = StringVar(self.parent, '0') self.status_message = StringVar(self.parent, 'Ready') self.db = DB() self.initApp() self.setupGUI() def quit(self, event=None): log.debug('quiting...') P2PClientManager.deleteClient() self.parent.destroy() def initApp(self): #Connect Here self.client = P2PClientManager.getClient(port=random.randint(40000, 60000)) self.client.subscribe(Message.NEW_TRANSACTION, self.update_balance) self.client.subscribe_to_info(self.update_status) t = threading.Thread(target=self.start_miner) t.start() if not self.db.hasRanBefore(): c = CoinBase(owner=KeyStore.getPrivateKey(), amt=100) c.finish_transaction() self.db.setRanBefore() #messagebox.showinfo('Welcome', 'This is your first time running the app. You get to start off with 100 PyCoins!') #Get balance, Save to variable below self.coin_balance.set(str(KeyStore.get_balance())) print('PyCoin Address: ', SHA.new(KeyStore.getPublicKey().exportKey()).hexdigest()) log.debug("GUI created") def start_miner(self): self.miner = Miner() self.miner.subscribe(self.display_info) def display_info(self, info): #messagebox.showinfo("Info", info) pass def update_status(self, info): self.status_message.set(info) def set_debug_level(self): pass def update_balance(self, t=None): bal = str(KeyStore.get_balance()) self.coin_balance.set(bal) def create_menu(self): top = self.winfo_toplevel() self.menuBar = Menu(top) top['menu'] = self.menuBar self.subMenu = Menu(self.menuBar, tearoff=0) self.menuBar.add_cascade(label='File', menu=self.subMenu) self.subMenu.add_command(label='Verify Blockchain', command=self.verify_block_chain) self.subMenu.add_command(label='My PyCoin Address', command=self.show_address) self.subMenu.add_separator() self.subMenu.add_command(label='Quit', command=self.quit) def show_address(self): f = Tk() label = Label(f, text='PyCoin Address') label.pack() k = SHA.new(KeyStore.getPublicKey().exportKey()).hexdigest() key = Text(f, width=42, height=1) key.insert(INSERT, k) key.pack() def verify_block_chain(self): if self.miner.verify_block_chain(debug=True): messagebox.showinfo("Verified", "Block chain verified.") else: messagebox.showwarning("Warning", "Block chain is invalid.") def open_debug_window(self): self.debug = Tk() self.tw = Text(self.debug, relief='flat') self.tw.pack() def setupGUI(self): self.parent.bind('<Control-q>', self.quit) self.parent.title("PyCoin") self.pack(fill=BOTH, expand=1) self.create_menu() #Labeled Frames for Status and Send lf = LabelFrame(self, text="Send BitCoins") lf.pack(side=BOTTOM, fill="both", expand="yes", padx=7, pady=7) lf2 = LabelFrame(self, text="BitCoin Status") lf2.pack(side=TOP, fill="both", expand="yes", padx=7, pady=7) #Labels for Bitcoin balance self.balanceHeading = Label(lf2, text="BitCoin Balance:", font = "Helvetica 20") self.balanceHeading.pack() self.balance = Label(lf2, textvariable=self.coin_balance, font="Helvetica 20") self.balance.pack() #Label and Text field for BitCoin Amount self.amtFrame = Frame(lf) self.amtFrame.pack() self.label = Label(self.amtFrame, text="BitCoin Amount :") self.label.pack(side=LEFT) self.amountBox = Entry(self.amtFrame, bd=2) self.amountBox.pack(side=LEFT, pady=10, fill=X) #Label and Text filed for Reciever Key self.label = Label(lf, text="Receivers Public Key:") self.label.pack() self.recieverKey = Text(lf, width=42, height=1) self.recieverKey.pack() #Send Button self.sendBtn = Button(lf, text='\nSend BitCoin(s)\n', command=self.sendCoins) self.sendBtn.pack(fill=X, pady=5) #Status Bar status = Label(self.winfo_toplevel(), textvariable=self.status_message, bd=1, relief=SUNKEN, anchor=W) status.pack(side=BOTTOM, fill=X) #Send Button Callback Function def sendCoins(self): sendAmt = self.amountBox.get() #Amount to send recvKey = self.recieverKey.get("1.0",'end-1c') #recievers public key if not sendAmt: messagebox.showwarning("Warning", "Please enter a BitCoin amount.") elif len(recvKey) <= 1: messagebox.showwarning("Warning", "Please enter the receivers key.") else: result = messagebox.askyesno("Send Confirmation", 'Sending {} BitCoins to reciever:\n {}'.format(sendAmt, recvKey)) if result: print('Sending {} BitCoins to reciever:\n {}'.format(sendAmt, recvKey)) t = Transaction(owner=KeyStore.getPrivateKey(), callback=self.update_balance) try: pubKey = self.client.keyTable[recvKey] except: messagebox.showwarning('Address not found.', 'Oops. That PyCoin address could not be found.') return try: t.add_output(Transaction.Output(int(sendAmt), RSA.importKey(pubKey))) except: messagebox.showwarning('Insufficient funds.', 'Oops. It looks like you ran out of money. :(') return t.finish_transaction() self.amountBox.delete(0,END)
def init_ui(self): """ setup the GUI for the app """ self.master.title("Test") self.pack(fill=BOTH, expand=True) # Input section input_frame = LabelFrame(self, text="Input") input_frame.bind("-", self.on_minus_key) input_frame.bind("+", self.on_plus_key) input_frame.pack(fill=X) self.play_button = Button(input_frame, text="Play", command=self.on_play_button_click) self.play_button.pack(side=RIGHT, padx=4) self.rec_button = Button(input_frame, text="Rec", command=self.on_rec_button_click) self.rec_button.pack(side=RIGHT, padx=4) self.wav_filename_entry = Entry(input_frame, width=24) self.wav_filename_entry.pack(fill=X) self.wav_filename_entry.delete(0, END) if self.wav_filename: self.wav_filename_entry.insert(0, self.wav_filename) # Feature section features_frame = LabelFrame(self, text="Features") features_frame.pack(fill=X) features_control_frame = Frame(features_frame) features_control_frame.pack(fill=X) load_features_button = Button(features_control_frame, text="Load", command=self.on_load_featurizer_model) load_features_button.pack(side=RIGHT) self.features_entry = Entry(features_control_frame, width=8) self.features_entry.pack(fill=X) self.features_entry.delete(0, END) if self.featurizer_model: self.features_entry.insert(0, self.featurizer_model) viz_frame = Frame(features_frame) viz_frame.pack(fill=X) self.features_figure = Figure(figsize=(5, 4), dpi=100) self.subplot = self.features_figure.add_subplot(111) canvas = FigureCanvasTkAgg(self.features_figure, master=viz_frame) canvas.draw() canvas.show() canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=True) # Classifier section classifier_frame = LabelFrame(self, text="Classifier") classifier_frame.pack(fill=X) load_classifier_button = Button(classifier_frame, text="Load", command=self.on_load_classifier) load_classifier_button.pack(side=RIGHT) self.classifier_entry = Entry(classifier_frame, width=8) self.classifier_entry.pack(fill=X) self.classifier_entry.delete(0, END) if self.classifier_model: self.classifier_entry.insert(0, self.classifier_model) # Output section output_frame = LabelFrame(self, text="Output") output_frame.pack(fill=BOTH, expand=True) self.output_text = Text(output_frame) self.output_text.pack(fill=BOTH, padx=4, expand=True)
def mailbox_info(self, mailbox=""): """GUI to add or modify a mailbox login information.""" def on_click(event): event.widget.focus_set() event.widget.selection_range(0, 'end') event.widget.unbind('<1>') return "break" def save(event=None): name = name_entry.get().strip() if not mailbox: # new mailbox i = self.b_add.grid_info()['row'] self.b_add.grid_configure(row=i + 1) c = Checkbutton(self.frame) c.state(('selected',)) c.grid(row=i, column=0, pady=4, padx=(4, 0)) l = Label(self.frame, text=name) l.grid(row=i, column=1, padx=4, pady=4) b_edit = Button(self.frame, image=self.im_edit, width=1, command=lambda m=name: self.mailbox_info(m)) b_edit.grid(row=i, column=2, padx=4, pady=4) b_del = Button(self.frame, image=self.im_del, width=1, command=lambda m=name: self.del_mailbox(m)) b_del.grid(row=i, column=3, padx=4, pady=4) self.mailboxes[name] = [c, l, b_edit, b_del] elif name != mailbox: # change name of mailbox os.remove(os.path.join(LOCAL_PATH, mailbox)) c, l, b_edit, b_del = self.mailboxes[mailbox] del(self.mailboxes[mailbox]) l.configure(text=name) b_edit.configure(command=lambda m=name: self.mailbox_info(m)) b_del.configure(command=lambda m=name: self.del_mailbox(m)) self.mailboxes[name] = [c, l, b_edit, b_del] encrypt(name, self.pwd, server_entry.get().strip(), login_entry.get().strip(), password_entry.get().strip(), folder_entry.get().strip()) top.destroy() top = Toplevel(self, class_="CheckMails") top.title(_("Login information")) top.transient(self) top.resizable(False, False) name_entry = Entry(top, justify='center', width=32) server_entry = Entry(top, justify='center', width=32) login_entry = Entry(top, justify='center', width=32) password_entry = Entry(top, show='*', justify='center', width=32) folder_entry = Entry(top, justify='center', width=32) if mailbox: name_entry.insert(0, mailbox) server, login, password, folder = decrypt(mailbox, self.pwd) if server is None: top.destroy() self.del_mailbox(mailbox) return server_entry.insert(0, server) login_entry.insert(0, login) password_entry.insert(0, password) folder_entry.insert(0, folder) else: name_entry.insert(0, "Mailbox name") server_entry.insert(0, "IMAP.mailbox.com") login_entry.insert(0, "*****@*****.**") folder_entry.insert(0, "inbox") name_entry.bind("<1>", on_click) server_entry.bind("<1>", on_click) login_entry.bind("<1>", on_click) password_entry.bind("<1>", on_click) folder_entry.bind("<1>", on_click) Label(top, text=_("Mailbox name")).grid(row=0, column=0, sticky="e", pady=(10, 4), padx=(10, 1)) Label(top, text=_("IMAP server")).grid(row=1, column=0, sticky="e", pady=4, padx=(10, 1)) Label(top, text=_("Login")).grid(row=2, column=0, sticky="e", pady=4, padx=(10, 1)) Label(top, text=_("Password")).grid(row=3, column=0, sticky="e", pady=4, padx=(10, 1)) Label(top, text=_("Folder to check")).grid(row=4, column=0, sticky="e", pady=4, padx=(10, 1)) name_entry.grid(row=0, column=1, sticky="w", pady=4, padx=(1, 10)) server_entry.grid(row=1, column=1, sticky="w", pady=4, padx=(1, 10)) login_entry.grid(row=2, column=1, sticky="w", pady=4, padx=(1, 10)) password_entry.grid(row=3, column=1, sticky="w", pady=4, padx=(1, 10)) folder_entry.grid(row=4, column=1, sticky="w", pady=4, padx=(1, 10)) frame = Frame(top) frame.grid(row=5, columnspan=2, pady=(0, 6)) Button(frame, text="Ok", command=save).grid(row=0, column=0, padx=(10, 4), pady=4) Button(frame, text=_("Cancel"), command=top.destroy).grid(row=0, column=1, pady=4, padx=(10, 4)) top.grab_set() name_entry.bind("<Key-Return>", save) server_entry.bind("<Key-Return>", save) login_entry.bind("<Key-Return>", save) password_entry.bind("<Key-Return>", save) folder_entry.bind("<Key-Return>", save) name_entry.focus_set()
# importing tkinter as tk from tkinter import Tk, mainloop, BOTTOM from tkinter.ttk import Button # creating tkinter window root = Tk() # creting fixed size window root.geometry('200x150') button = Button(root, text="Ok") button.pack(side=BOTTOM, pady=5) mainloop()
class SimpleBC_Gui(Frame): def __init__(self, parent, my_port, c_host, c_port): Frame.__init__(self, parent) self.parent = parent self.parent.protocol('WM_DELETE_WINDOW', self.quit) self.coin_balance = StringVar(self.parent, '0') self.status_message = StringVar(self.parent, 'Ready') self.c_core = None self.initApp(my_port, c_host, c_port) self.setupGUI() def quit(self, event=None): """ アプリの終了 """ self.c_core.shutdown() self.parent.destroy() def initApp(self, my_port, c_host, c_port): """ ClientCoreとの接続含めて必要な初期化処理はここで実行する """ print('SimpleBitcoin client is now activating ...: ') self.km = KeyManager() self.um = UTXM(self.km.my_address()) self.rsa_util = RSAUtil() self.c_core = Core(my_port, c_host, c_port, self.update_callback, self.get_message_callback) self.c_core.start(self.km.my_address()) # テスト用途(本来はこんな処理しない) t1 = CoinbaseTransaction(self.km.my_address()) t2 = CoinbaseTransaction(self.km.my_address()) t3 = CoinbaseTransaction(self.km.my_address()) transactions = [] transactions.append(t1.to_dict()) transactions.append(t2.to_dict()) transactions.append(t3.to_dict()) self.um.extract_utxos(transactions) self.update_balance() def display_info(self, title, info): """ ダイアログボックスを使ったメッセージの表示 """ f = Tk() label = Label(f, text=title) label.pack() info_area = Text(f, width=70, height=50) info_area.insert(INSERT, info) info_area.pack() def get_message_callback(self, target_message): print('get_message_callback called!') if target_message['message_type'] == 'cipher_message': try: encrypted_key = base64.b64decode(binascii.unhexlify(target_message['enc_key'])) print('encripted_key : ', encrypted_key) decrypted_key = self.km.decrypt_with_private_key(encrypted_key) print('decrypted_key : ', binascii.hexlify(decrypted_key).decode('ascii')) # 流石に名前解決をしないで公開鍵のまま出しても意味なさそうなのでコメントアウト #sender = binascii.unhexlify(target_message['sender']) aes_util = AESUtil() decrypted_message = aes_util.decrypt_with_key(base64.b64decode(binascii.unhexlify(target_message['body'])), decrypted_key) print(decrypted_message.decode('utf-8')) """ message = { 'from' : sender, 'message' : decrypted_message.decode('utf-8') } message_4_display = pprint.pformat(message, indent=2) """ messagebox.showwarning('You received an instant encrypted message !', decrypted_message.decode('utf-8')) except Exception as e: print(e, 'error occurred') elif target_message['message_type'] == 'engraved': sender_name = target_message['sender_alt_name'] msg_body = base64.b64decode(binascii.unhexlify(target_message['message'])).decode('utf-8') timestamp = datetime.datetime.fromtimestamp(int(target_message['timestamp'])) messagebox.showwarning('You received a new engraved message!', '{} :\n {} \n {}'.format(sender_name, msg_body, timestamp)) def update_callback(self): print('update_callback was called!') s_transactions = self.c_core.get_stored_transactions_from_bc() print(s_transactions) self.um.extract_utxos(s_transactions) self.update_balance() def update_status(self, info): """ 画面下部のステータス表示内容を変更する """ self.status_message.set(info) def update_balance(self): """ 総額表示の内容を最新状態に合わせて変更する """ bal = str(self.um.my_balance) self.coin_balance.set(bal) def create_menu(self): """ メニューバーに表示するメニューを定義する """ top = self.winfo_toplevel() self.menuBar = Menu(top) top['menu'] = self.menuBar self.subMenu = Menu(self.menuBar, tearoff=0) self.menuBar.add_cascade(label='Menu', menu=self.subMenu) self.subMenu.add_command(label='Show My Address', command=self.show_my_address) self.subMenu.add_command(label='Load my Keys', command=self.show_input_dialog_for_key_loading) self.subMenu.add_command(label='Update Blockchain', command=self.update_block_chain) self.subMenu.add_separator() self.subMenu.add_command(label='Quit', command=self.quit) self.subMenu2 = Menu(self.menuBar, tearoff=0) self.menuBar.add_cascade(label='Settings', menu=self.subMenu2) self.subMenu2.add_command(label='Renew my Keys', command=self.renew_my_keypairs) self.subMenu3 = Menu(self.menuBar, tearoff=0) self.menuBar.add_cascade(label='Advance', menu=self.subMenu3) self.subMenu3.add_command(label='Send Encrypted Instant Message', command=self.send_instant_message) self.subMenu3.add_command(label='Show Logs (Received)', command=self.open_r_log_window) self.subMenu3.add_command(label='Show Logs (Send)', command=self.open_s_log_window) self.subMenu3.add_command(label='Show Blockchain', command=self.show_my_block_chain) self.subMenu3.add_command(label='Engrave Message', command=self.engrave_message) def show_my_address(self): f = Tk() label = Label(f, text='My Address') label.pack() key_info = Text(f, width=70, height=10) my_address = self.km.my_address() key_info.insert(INSERT, my_address) key_info.pack() def show_input_dialog_for_key_loading(self): def load_my_keys(): # ファイル選択ダイアログの表示 f2 = Tk() f2.withdraw() fTyp = [('','*.pem')] iDir = os.path.abspath(os.path.dirname(__file__)) messagebox.showinfo('Load key pair','please choose your key file') f_name = filedialog.askopenfilename(filetypes = fTyp,initialdir = iDir) try: file = open(f_name) data = file.read() target = binascii.unhexlify(data) # TODO: 本来は鍵ペアのファイルが不正などの異常系処理を考えるべき self.km.import_key_pair(target, p_phrase.get()) except Exception as e: print(e) finally: # TODO: 所有コインの再確認処理を入れる必要あり file.close() f.destroy() f2.destroy() self.um = UTXM(self.km.my_address()) self.um.my_balance = 0 self.update_balance() f = Tk() label0 = Label(f, text='Please enter pass phrase for your key pair') frame1 = ttk.Frame(f) label1 = ttk.Label(frame1, text='Pass Phrase:') p_phrase = StringVar() entry1 = ttk.Entry(frame1, textvariable=p_phrase) button1 = ttk.Button(frame1, text='Load', command=load_my_keys) label0.grid(row=0,column=0,sticky=(N,E,S,W)) frame1.grid(row=1,column=0,sticky=(N,E,S,W)) label1.grid(row=2,column=0,sticky=E) entry1.grid(row=2,column=1,sticky=W) button1.grid(row=3,column=1,sticky=W) def update_block_chain(self): self.c_core.send_req_full_chain_to_my_core_node() def renew_my_keypairs(self): """ 利用する鍵ペアを更新する。 """ def save_my_pem(): self.km = KeyManager() my_pem = self.km.export_key_pair(p_phrase) my_pem_hex = binascii.hexlify(my_pem).decode('ascii') # とりあえずファイル名は固定 path = 'my_key_pair.pem' f1 = open(path,'a') f1.write(my_pem_hex) f1.close() f.destroy() self.um = UTXM(self.km.my_address()) self.um.my_balance = 0 self.update_balance() f = Tk() f.title('New Key Gene') label0 = Label(f, text='Please enter pass phrase for your new key pair') frame1 = ttk.Frame(f) label1 = ttk.Label(frame1, text='Pass Phrase:') p_phrase = StringVar() entry1 = ttk.Entry(frame1, textvariable=p_phrase) button1 = ttk.Button(frame1, text='Generate', command=save_my_pem) label0.grid(row=0,column=0,sticky=(N,E,S,W)) frame1.grid(row=1,column=0,sticky=(N,E,S,W)) label1.grid(row=2,column=0,sticky=E) entry1.grid(row=2,column=1,sticky=W) button1.grid(row=3,column=1,sticky=W) def send_instant_message(self): def send_message(): r_pkey = entry1.get() print('pubkey', r_pkey) new_message = {} aes_util = AESUtil() cipher_txt = aes_util.encrypt(entry2.get()) new_message['message_type'] = 'cipher_message' new_message['recipient'] = r_pkey new_message['sender'] = self.km.my_address() new_message['body'] = binascii.hexlify(base64.b64encode(cipher_txt)).decode('ascii') key = aes_util.get_aes_key() encrypted_key = self.rsa_util.encrypt_with_pubkey(key, r_pkey) print('encrypted_key: ', encrypted_key[0]) new_message['enc_key'] = binascii.hexlify(base64.b64encode(encrypted_key[0])).decode('ascii') msg_type = MSG_ENHANCED message_strings = json.dumps(new_message) self.c_core.send_message_to_my_core_node(msg_type, message_strings) f.destroy() f = Tk() f.title('New Message') label0 = Label(f, text='Please input recipient address and message') frame1 = ttk.Frame(f) label1 = ttk.Label(frame1, text='Recipient:') pkey = StringVar() entry1 = ttk.Entry(frame1, textvariable=pkey) label2 = ttk.Label(frame1, text='Message:') message = StringVar() entry2 = ttk.Entry(frame1, textvariable=message) button1 = ttk.Button(frame1, text='Send Message', command=send_message) label0.grid(row=0,column=0,sticky=(N,E,S,W)) frame1.grid(row=1,column=0,sticky=(N,E,S,W)) label1.grid(row=2,column=0,sticky=E) entry1.grid(row=2,column=1,sticky=W) label2.grid(row=3,column=0,sticky=E) entry2.grid(row=3,column=1,sticky=W) button1.grid(row=4,column=1,sticky=W) def open_r_log_window(self): """ 別ウィンドウでログ情報を表示する。これまでに受け取った自分宛のTransactionを時系列で並べる """ s_transactions = self.c_core.get_stored_transactions_from_bc() my_transactions = self.um.get_txs_to_my_address(s_transactions) informations = [] receive_date = None sender = None value = None reason = None description = None for t in my_transactions: result, t_type = self.um.is_sbc_transaction(t) receive_date = datetime.datetime.fromtimestamp(int(t['timestamp'])) if t_type == 'basic': reason = base64.b64decode(binascii.unhexlify(t['extra']['reason'])).decode('utf-8') description = base64.b64decode(binascii.unhexlify(t['extra']['description'])).decode('utf-8') for txout in t['outputs']: recipient = txout['recipient'] if recipient == self.km.my_address(): value = txout['value'] for txin in t['inputs']: t_in_txin = txin['transaction'] idx = txin['output_index'] sender = t_in_txin['outputs'][idx]['recipient'] if sender == self.km.my_address(): sender = 'Change to myself' else: reason = 'CoinbaseTransaction' description = 'CoinbaseTransaction' sender = self.km.my_address() for txout in t['outputs']: recipient = txout['recipient'] if recipient == self.km.my_address(): value = txout['value'] info = { 'date' : receive_date, 'From' : sender, 'Value' : value, 'reason' : reason, 'description' : description } informations.append(info) log = pprint.pformat(informations, indent=2) if log is not None: self.display_info('Log : Received Transaction', log) else: self.display_info('Warning', 'Currently you received NO Transaction to you...') def open_s_log_window(self): """ 別ウィンドウでログ情報を表示する。これまでに自分が送信したTransactionを時系列で並べる """ s_transactions = self.c_core.get_stored_transactions_from_bc() my_transactions = self.um.get_txs_from_my_address(s_transactions) informations = [] send_date = None recipient = None value = None reason = None description = None for t in my_transactions: result, t_type = self.um.is_sbc_transaction(t) send_date = datetime.datetime.fromtimestamp(int(t['timestamp'])) if t_type == 'basic': reason = base64.b64decode(binascii.unhexlify(t['extra']['reason'])).decode('utf-8') description = base64.b64decode(binascii.unhexlify(t['extra']['description'])).decode('utf-8') for txout in t['outputs']: recipient = txout['recipient'] if recipient == self.km.my_address(): recipient = 'Change to myself' value = txout['value'] info = { 'date' : send_date, 'To' : recipient, 'Value' : value, 'reason' : reason, 'description' : description } informations.append(info) log = pprint.pformat(informations, indent=2) if log is not None: self.display_info('Log : Sent Transaction', log) else: self.display_info('Warning', 'NO Transaction which was sent from you...') def show_my_block_chain(self): """ 自分が保持しているブロックチェーンの中身を確認する """ mychain = self.c_core.get_my_blockchain() if mychain is not None: mychain_str = pprint.pformat(mychain, indent=2) self.display_info('Current Blockchain', mychain_str) else: self.display_info('Warning', 'Currently Blockchain is empty...') def engrave_message(self): """ ブロックチェーンにTwitter風のメッセージを格納する """ def send_e_message(): # P2PによるブロードキャストとTransactionのハイブリッド new_message = {} msg_txt = entry.get().encode('utf-8') msg = EngravedTransaction( self.km.my_address(), 'Testman', binascii.hexlify(base64.b64encode(msg_txt)).decode('ascii') ) to_be_signed = json.dumps(msg.to_dict(), sort_keys=True) signed = self.km.compute_digital_signature(to_be_signed) new_tx = json.loads(to_be_signed) new_tx['signature'] = signed tx_strings = json.dumps(new_tx) self.c_core.send_message_to_my_core_node(MSG_NEW_TRANSACTION, tx_strings) new_tx2 = copy.deepcopy(new_tx) new_tx2['message_type'] = 'engraved' tx_strings2 = json.dumps(new_tx2) self.c_core.send_message_to_my_core_node(MSG_ENHANCED, tx_strings2) f.destroy() f = Tk() f.title('Engrave New Message') label0 = Label(f, text='Any idea?') frame1 = ttk.Frame(f) label = ttk.Label(frame1, text='Message:') entry = ttk.Entry(frame1, width=30) button1 = ttk.Button(frame1, text='Engrave this on Blockchain', command=send_e_message) label0.grid(row=0,column=0,sticky=(N,E,S,W)) frame1.grid(row=1,column=0,sticky=(N,E,S,W)) label.grid(row=2,column=0,sticky=E) entry.grid(row=2,column=1,sticky=W) button1.grid(row=3,column=1,sticky=W) def setupGUI(self): """ 画面に必要なパーツを並べる """ self.parent.bind('<Control-q>', self.quit) self.parent.title('SimpleBitcoin GUI') self.pack(fill=BOTH, expand=1) self.create_menu() lf = LabelFrame(self, text='Current Balance') lf.pack(side=TOP, fill='both', expand='yes', padx=7, pady=7) lf2 = LabelFrame(self, text='') lf2.pack(side=BOTTOM, fill='both', expand='yes', padx=7, pady=7) #所持コインの総額表示領域のラベル self.balance = Label(lf, textvariable=self.coin_balance, font='Helvetica 20') self.balance.pack() #受信者となる相手の公開鍵 self.label = Label(lf2, text='Recipient Address:') self.label.grid(row=0, pady=5) self.recipient_pubkey = Entry(lf2, bd=2) self.recipient_pubkey.grid(row=0, column=1, pady=5) # 送金額 self.label2 = Label(lf2, text='Amount to pay :') self.label2.grid(row=1, pady=5) self.amountBox = Entry(lf2, bd=2) self.amountBox.grid(row=1, column=1, pady=5, sticky='NSEW') # 手数料 self.label3 = Label(lf2, text='Fee (Optional) :') self.label3.grid(row=2, pady=5) self.feeBox = Entry(lf2, bd=2) self.feeBox.grid(row=2, column=1, pady=5, sticky='NSEW') # 送金理由を書く欄(主にURLとか) self.label4 = Label(lf2, text='reason (Optional) :') self.label4.grid(row=3, pady=5) self.reasonBox = Entry(lf2, bd=2) self.reasonBox.grid(row=3, column=1, pady=5, sticky='NSEW') # 通信欄(公開メッセージ) self.label5 = Label(lf2, text='message (Optional) :') self.label5.grid(row=4, pady=5) self.messageBox = Entry(lf2, bd=2) self.messageBox.grid(row=4, column=1, pady=5, sticky='NSEW') # 間隔の開け方がよくわからんので空文字で場所確保 self.label4 = Label(lf2, text='') self.label4.grid(row=5, pady=5) # 送金実行ボタン self.sendBtn = Button(lf2, text='\nSend Coin(s)\n', command=self.sendCoins) self.sendBtn.grid(row=6, column=1, sticky='NSEW') # 下部に表示するステータスバー stbar = Label(self.winfo_toplevel(), textvariable=self.status_message, bd=1, relief=SUNKEN, anchor=W) stbar.pack(side=BOTTOM, fill=X) # 送金実行ボタン押下時の処理実体 def sendCoins(self): sendAtp = self.amountBox.get() recipientKey = self.recipient_pubkey.get() sendFee = self.feeBox.get() reason = binascii.hexlify(base64.b64encode(self.reasonBox.get().encode('utf-8'))).decode('ascii') desc = binascii.hexlify(base64.b64encode(self.messageBox.get().encode('utf-8'))).decode('ascii') utxo_len = len(self.um.utxo_txs) if not sendAtp: messagebox.showwarning('Warning', 'Please enter the Amount to pay.') return elif len(recipientKey) <= 1: messagebox.showwarning('Warning', 'Please enter the Recipient Address.') return else: result = messagebox.askyesno('Confirmation', 'Sending {} SimpleBitcoins to :\n {}'.format(sendAtp, recipientKey)) if not sendFee: sendFee = 0 if not reason: reason = 'No information' if not desc: desc = 'No description' extra = { 'reason': reason, 'description': desc, } if result: if 0 < utxo_len: print('Sending {} SimpleBitcoins to reciever:\n {}'.format(sendAtp, recipientKey)) else: messagebox.showwarning('Short of Coin.', 'Not enough coin to be sent...') return utxo, idx = self.um.get_utxo_tx(0) t = Transaction( [TransactionInput(utxo, idx)], [TransactionOutput(recipientKey, int(sendAtp))], extra ) counter = 1 # TransactionInputが送信額を超えるまで繰り返して取得しTransactionとして完成させる if type(sendFee) is not str: sendFee = int(sendFee) while t.is_enough_inputs(sendFee) is not True: new_utxo, new_idx = self.um.get_utxo_tx(counter) t.inputs.append(TransactionInput(new_utxo, new_idx)) counter += 1 if counter > utxo_len: messagebox.showwarning('Short of Coin.', 'Not enough coin to be sent...') break # 正常なTransactionが生成できた時だけ秘密鍵で署名を実行する if t.is_enough_inputs(sendFee) is True: # まずお釣り用Transactionを作る change = t.compute_change(sendFee) t.outputs.append(TransactionOutput(self.km.my_address(), change)) to_be_signed = json.dumps(t.to_dict(), sort_keys=True) signed = self.km.compute_digital_signature(to_be_signed) new_tx = json.loads(to_be_signed) new_tx['signature'] = signed # TransactionをP2P Networkに送信 msg_type = MSG_NEW_TRANSACTION tx_strings = json.dumps(new_tx) self.c_core.send_message_to_my_core_node(msg_type, tx_strings) print('signed new_tx:', tx_strings) # 実験的にお釣り分の勘定のため新しく生成したTransactionをUTXOとして追加しておくが # 本来はブロックチェーンの更新に合わせて再計算した方が適切 self.um.put_utxo_tx(t.to_dict()) to_be_deleted = 0 del_list = [] while to_be_deleted < counter: del_tx = self.um.get_utxo_tx(to_be_deleted) del_list.append(del_tx) to_be_deleted += 1 for dx in del_list: self.um.remove_utxo_tx(dx) self.amountBox.delete(0,END) self.feeBox.delete(0,END) self.recipient_pubkey.delete(0,END) self.reasonBox.delete(0,END) self.messageBox.delete(0,END) self.update_balance()
def init_UI_static(self): ''' Initialize static UI elements ''' # initialize window title and grid layout self.master.title('Siemens PBX Parsing Tool') self.pack(fill=BOTH, expand=1) # style self.style = Style() self.style.theme_use('clam') # default theme for now # Data File self.frame_data = Frame(self) self.frame_data.pack(fill=X) self.lbl_data = Label(self.frame_data, text='Data Files:', width=12, relief=FLAT) self.lbl_data.pack(side=LEFT, ipadx=5, padx=5, ipady=5, pady=5) self.frame_data_btn = Frame(self) self.frame_data_btn.pack(fill=X) self.btn_rm_data = Button(self.frame_data_btn, text='Remove', command=self.rm_data) self.btn_rm_data.pack(side=RIGHT, padx=5) self.btn_add_data = Button(self.frame_data_btn, text='Add', command=self.set_data) self.btn_add_data.pack(side=RIGHT, padx=5) # Excel Workbook self.frame_xlsx = Frame(self) self.frame_xlsx.pack(fill=X, pady=(10, 0)) self.lbl_xlsx = Label(self.frame_xlsx, text='Workbook:', width=12, relief=FLAT) self.lbl_xlsx.pack(side=LEFT, ipadx=5, padx=5, ipady=5, pady=5) self.frame_xlsx_btn = Frame(self) self.frame_xlsx_btn.pack(fill=X) self.btn_load_wb = Button(self.frame_xlsx_btn, text='Load...', command=self.set_wb) self.btn_load_wb.pack(side=RIGHT, padx=5) self.btn_new_wb = Button(self.frame_xlsx_btn, text='New...', command=lambda: self.set_wb(True)) self.btn_new_wb.pack(side=RIGHT, padx=5) # Presets File self.frame_preset = Frame(self) self.frame_preset.pack(fill=X, pady=(10, 0)) self.lbl_preset = Label(self.frame_preset, text='Presets File:', width=12, relief=FLAT) self.lbl_preset.pack(side=LEFT, ipadx=5, padx=5, ipady=5, pady=5) self.frame_preset_btn = Frame(self) self.frame_preset_btn.pack(fill=BOTH) self.btn_load_preset = Button(self.frame_preset_btn, text='Load...', command=self.set_preset) self.btn_load_preset.pack(side=RIGHT, padx=5) self.btn_new_preset = Button(self.frame_preset_btn, text='New...', command=lambda: self.set_preset(True)) self.btn_new_preset.pack(side=RIGHT, padx=5) # Lower button grid self.button_grid = Frame(self, borderwidth=0) self.button_grid.pack(side=BOTTOM, fill=BOTH, expand=True) self.btn_quit = Button(self.button_grid, text='Quit', command=self.quit) self.btn_quit.pack(side=RIGHT, padx=5, pady=5, anchor=SE) self.btn_start = Button(self.button_grid, text='Parse', command=self.parse) self.btn_start.pack(side=RIGHT, padx=5, pady=5, anchor=SE)
class App_test(object): def __init__(self, master, fuc, query, next, pre, query_all_chapters, query_text): self.win = master self.win.title('shuyaya阅读_v2.0 by: 孤月') # self.win.iconbitmap('./ico/gui_text_proce.ico') # 指定界面图标 curWidth = self.win.winfo_width() curHeight = self.win.winfo_height() scnWidth, scnHeight = self.win.maxsize() tmpcnf = '1340x640+500+300' # % ((scnWidth - curWidth) / 2, (scnHeight - curHeight) / 2) self.win.geometry(tmpcnf) self.creat_res() self.set_position() self.list_box(query_all_chapters, query_text) # self.add_train_info() self.res_config(fuc, query, next, pre) self.train_message = {} self.gettime() # 系统时间 def creat_res(self): # self.v = IntVar() # 书籍查询 # self.v.set(True) self.temp = StringVar() # 书名/作者 录入 self.temp2 = StringVar() # 章节名录入 self.sys_time = StringVar() # 系统时间 self.E_startstation = Entry(self.win, textvariable=self.temp) # self.E_endstation = Entry(self.win, textvariable=self.temp2) self.La_startstation = Label(self.win, text="根据书名/作者搜索:") self.La_endstation = Label(self.win, text="书籍目录:") self.La_directory = Label(self.win, text="目录") self.La_text = Label(self.win, text="正文") self.La_sys_time = Label(self.win, textvariable=self.sys_time, fg='blue', font=("黑体", 20)) # 设置字体大小颜色 self.La_pic = Label(self.win, bg="#E6E6FA") self.La_anthor = Label(self.win, bg="#E6E6FA") self.La_type = Label(self.win, bg="#E6E6FA") self.La_update_time = Label(self.win, bg="#E6E6FA") self.La_latest_chapter = Label(self.win, bg="#E6E6FA") self.B_search = Button(self.win, text="搜索") self.B_buy_tick = Button(self.win, text="阅读") self.B_pre_chapter = Button(self.win, text="上一章") self.B_next_chapter = Button(self.win, text="下一章") # self.R_site = Radiobutton(self.win, text="书名查询", variable=self.v, value=True) # self.R_price = Radiobutton(self.win, text="章节查询", variable=self.v, value=False) self.init_data_Text = Text(self.win) # 原始数据录入框 self.S_move = Scrollbar(self.win) # 目录滚动条 self.S_text_move = Scrollbar(self.win) # 创建文本框滚动条 # 设置位置 def set_position(self): self.init_data_Text.place(x=430, y=40, width=870, height=550) self.E_startstation.place(x=10, y=50, width=145, height=30) self.E_startstation.insert(10, "星辰变") # self.E_endstation.place(x=10, y=140, width=145, height=30) # self.E_endstation.insert(10, "第一章 秦羽") self.La_startstation.place(x=10, y=10, width=130, height=30) self.La_endstation.place(x=10, y=100, width=60, height=30) self.La_sys_time.place(x=1150, y=600, width=160, height=30) self.La_pic.place(x=10, y=350, width=170, height=180) # 图片 self.La_anthor.place(x=10, y=545, width=170, height=30) self.La_type.place(x=10, y=575, width=170, height=30) self.La_update_time.place(x=10, y=605, width=170, height=30) self.La_latest_chapter.place(x=10, y=635, width=170, height=30) self.B_search.place(x=10, y=300, width=80, height=40) self.B_buy_tick.place(x=90, y=300, width=80, height=40) self.B_pre_chapter.place(x=950, y=600, width=80, height=40) self.B_next_chapter.place(x=1050, y=600, width=80, height=40) self.S_move.place(x=380, y=40, width=30, height=550) self.S_text_move.place(x=1300, y=40, width=30, height=550) # self.R_site.place(x=10, y=180, width=90, height=30) # self.R_price.place(x=100, y=180, width=90, height=30) self.La_directory.place(x=180, y=7, width=90, height=30) self.La_text.place(x=420, y=7, width=70, height=30) # 为按钮绑定事件 def res_config(self, fuc, query, next_, pre): self.B_search.config(command=fuc) # 搜索 self.B_buy_tick.config(command=query) # 阅读 self.B_pre_chapter.config(command=pre) # 上一章 self.B_next_chapter.config(command=next_) # 下一章 self.S_move.config(command=self.Ls_box_ct.yview) # 目录滚动条 self.Ls_box_ct.config(yscrollcommand=self.S_move.set) self.S_text_move.config(command=self.init_data_Text.yview) # 文本框滚动条 self.init_data_Text.config(yscrollcommand=self.S_text_move.set) # def printlist(self,event): # print(self.Ls_box.get(self.Ls_box.curselection())) def list_box(self, query_all_chapters, query_text): self.Ls_box = Listbox(self.win, selectmode=EXTENDED, fg='blue') self.Ls_box.place(x=10, y=140, width=170, height=150) self.Ls_box.bind( '<Double-Button-1>', query_all_chapters ) # 鼠标双击 更多事件请看http://www.cnblogs.com/hackpig/p/8195678.html self.Ls_box.insert(END, "获取排行榜") # 请输入书名&作者进行查询 self.Ls_box_ct = Listbox(self.win, selectmode=EXTENDED, fg='blue') self.Ls_box_ct.place(x=200, y=40, width=180, height=550) self.Ls_box_ct.bind('<Double-Button-1>', query_text) def add_train_info(self): lis_train = ["C" + str(x) for x in range(0, 2)] tuple_train = tuple(lis_train) self.tree = Treeview(self.win, columns=tuple_train, height=30, show="headings") self.tree.place(x=200, y=40, width=180, height=550) train_info = [' 书名 ', ' 作者 '] for i in range(0, len(lis_train)): self.tree.column( lis_train[i], width=len(train_info[i]) * 11, anchor='w') # must be n, ne, e, se, s, sw, w, nw, or center self.tree.heading(lis_train[i], text=train_info[i]) # 实时显示时钟 def gettime(self): # 获取当前时间 self.sys_time.set(time.strftime("%H:%M:%S")) # 每隔一秒调用函数自身获取时间 self.win.after(1000, self.gettime)
def initUI(self): self.master.title("Calculator", ) Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10') self.columnconfigure(0, pad=3) self.columnconfigure(1, pad=3) self.columnconfigure(2, pad=3) self.columnconfigure(3, pad=3) self.rowconfigure(0, pad=3) self.rowconfigure(1, pad=3) self.rowconfigure(2, pad=3) self.rowconfigure(3, pad=3) self.rowconfigure(4, pad=3) global expression expression = "" global label_text label_text = StringVar() label_text.set("Enter Here...") entry = Entry(self, textvariable=label_text) entry.grid(row=0, columnspan=4, sticky=W + E) entry.bind("<Button-1>", self.cycle_label_text) #entry.pack() cls = Button(self, text="Cls", command=self.clear) cls.grid(row=1, column=0) bck = Button(self, text="Back") bck.grid(row=1, column=1) lbl = Button(self) lbl.grid(row=1, column=2) clo = Button(self, text="Close", command=self.quit) clo.grid(row=1, column=3) sev = Button(self, text="7", command=lambda: self.press(7)) sev.grid(row=2, column=0) eig = Button(self, text="8", command=lambda: self.press(8)) eig.grid(row=2, column=1) nin = Button(self, text="9", command=lambda: self.press(9)) nin.grid(row=2, column=2) div = Button(self, text="/", command=lambda: self.press('/')) div.grid(row=2, column=3) fou = Button(self, text="4", command=lambda: self.press(4)) fou.grid(row=3, column=0) fiv = Button(self, text="5", command=lambda: self.press(5)) fiv.grid(row=3, column=1) six = Button(self, text="6", command=lambda: self.press(6)) six.grid(row=3, column=2) mul = Button(self, text="*", command=lambda: self.press("*")) mul.grid(row=3, column=3) one = Button(self, text="1", command=lambda: self.press(1)) one.grid(row=4, column=0) two = Button(self, text="2", command=lambda: self.press(2)) two.grid(row=4, column=1) thr = Button(self, text="3", command=lambda: self.press(3)) thr.grid(row=4, column=2) mns = Button(self, text="-", command=lambda: self.press("-")) mns.grid(row=4, column=3) zer = Button(self, text="0", command=lambda: self.press(0)) zer.grid(row=5, column=0) dot = Button(self, text=".", command=lambda: self.press(".")) dot.grid(row=5, column=1) equ = Button(self, text="=", command=lambda: self.press_equal("=")) equ.grid(row=5, column=2) pls = Button(self, text="+", command=lambda: self.press("+")) pls.grid(row=5, column=3) self.pack()
class LauncherApp(TkApp): PROGRESS_MIN = 0 PROGRESS_MAX = 100 def __init__(self): self.window_title = f"{PROJECT_NAME} - Launcher" self.progress = None self.progress_label = None self.start_bot_button = None self.update_bot_button = None self.bot_version_label = None self.launcher_version_label = None self.update_launcher_button = None self.export_logs_button = None self.processing = False super().__init__() def create_components(self): # bot update self.update_bot_button = Button(self.top_frame, command=self.update_bot_handler, text="Update Octobot", style='Bot.TButton') self.bot_version_label = Label(self.top_frame, text="", style='Bot.TLabel') self.update_bot_button.grid(row=1, column=2, padx=200, pady=5) self.bot_version_label.grid(row=1, column=1) self.update_bot_version() # launcher update self.update_launcher_button = Button(self.top_frame, command=self.update_launcher_handler, text="Update Launcher", style='Bot.TButton') self.launcher_version_label = Label(self.top_frame, text=f"Launcher version : {LAUNCHER_VERSION}", style='Bot.TLabel') self.update_launcher_button.grid(row=2, column=2, padx=200, pady=5) self.launcher_version_label.grid(row=2, column=1, ) # buttons self.start_bot_button = Button(self.top_frame, command=self.start_bot_handler, text="Start Octobot", style='Bot.TButton') self.start_bot_button.grid(row=3, column=1) # bottom self.progress = Progressbar(self.bottom_frame, orient="horizontal", length=200, mode="determinate", style='Bot.Horizontal.TProgressbar') self.progress.grid(row=1, column=1, padx=5, pady=5) self.progress_label = Label(self.bottom_frame, text=f"{self.PROGRESS_MIN}%", style='Bot.TLabel') self.progress_label.grid(row=1, column=2, padx=5) self.progress["value"] = self.PROGRESS_MIN self.progress["maximum"] = self.PROGRESS_MAX def inc_progress(self, inc_size, to_min=False, to_max=False): if to_max: self.progress["value"] = self.PROGRESS_MAX self.progress_label["text"] = f"{self.PROGRESS_MAX}%" elif to_min: self.progress["value"] = self.PROGRESS_MIN self.progress_label["text"] = f"{self.PROGRESS_MIN}%" else: self.progress["value"] += inc_size self.progress_label["text"] = f"{round(self.progress['value'], 1)}%" def update_bot_handler(self): if not self.processing: thread = Thread(target=self.update_bot, args=(self,)) thread.start() def update_launcher_handler(self): if not self.processing: launcher_process = subprocess.Popen([sys.executable, "--update_launcher"]) if launcher_process: self.hide() launcher_process.wait() new_launcher_process = subprocess.Popen([sys.executable]) if new_launcher_process: self.stop() def start_bot_handler(self): if not self.processing: bot_process = Launcher.execute_command_on_detached_bot() if bot_process: self.hide() bot_process.wait() self.stop() def update_bot_version(self): current_server_version = launcher_controller.Launcher.get_current_server_version() current_bot_version = launcher_controller.Launcher.get_current_bot_version() self.bot_version_label["text"] = f"Bot version : " \ f"{current_bot_version if current_bot_version else 'Not found'}" \ f" (Latest : " \ f"{current_server_version if current_server_version else 'Not found'})" @staticmethod def update_bot(app=None): if app: app.processing = True launcher_controller.Launcher(app) if app: app.processing = False sleep(1) app.update_bot_version() def show_alert(self, text, strings=("OK",), title="Alert", bitmap=DIALOG_ICON, default=0): return Dialog(self.window, text=text, title=title, bitmap=bitmap, default=default, strings=strings) @staticmethod def export_logs(): pass @staticmethod def close_callback(): os._exit(0) def start_app(self): self.window.mainloop() def hide(self): self.window.withdraw() def stop(self): self.window.quit()
""" Button with pictograms use the mouse and press the button creates second command window, could be to to with PhotoImage """ from tkinter import PhotoImage, Tk from tkinter.ttk import Style, Button, Frame, Label s = Style() s.theme_use('default') root = Tk() # using alternative cross reference 'im1' image1 = PhotoImage('im1', file='../images/close.gif') image2 = PhotoImage(file='../images/close_active.gif') image3 = PhotoImage(file='../images/close_pressed.gif') fr = Frame() fr.pack() lab = Label(fr, text="Dont't forget to click and hover") lab.pack(padx=4, pady=10) # using alternative cross reference 'im1' but = Button(fr, text='test', compound='right', image=('im1', 'pressed', image2, 'active', image3)) but.image = ('im1', 'pressed', image2, 'active', image3) but.pack(padx=4, pady=10) root.mainloop()
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("../Images/Logo of Digit Recognition.ico") 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) self.img = tk.PhotoImage(file="../Images/button.png") self.Button1 = Button(self, text="Predict", width=30, command=self.Predict, image=self.img) self.Button1.grid(row=80, column=802) self.img2 = tk.PhotoImage(file="../Images/button2.png") self.Button2 = Button(self, text="Clear Screen", width=30, command=self.deleteAll, image=self.img2) self.Button2.grid(row=120, column=802) 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:") 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) self.label_chosen_variable = Label(self, text=chosen_option) self.label_chosen_variable.grid(row=270, column=802) self.img3 = PhotoImage(file='../Images/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)
def __init__(self, master, pwd, mailbox=''): Toplevel.__init__(self, master, class_="CheckMails") self.title(_("Login information")) self.resizable(False, False) self.mailbox = mailbox self.name = '' self.pwd = pwd self.name_entry = Entry(self, justify='center', width=32) self.server_entry = Entry(self, justify='center', width=32) self.login_entry = Entry(self, justify='center', width=32) self.password_entry = Entry(self, show='*', justify='center', width=32) self.folder_entry = Entry(self, justify='center', width=32) if mailbox: self.name_entry.insert(0, mailbox) server, login, password, folder = decrypt(mailbox, self.pwd) if server is None: self.destroy() master.del_mailbox(mailbox) return self.server_entry.insert(0, server) self.login_entry.insert(0, login) self.password_entry.insert(0, password) self.folder_entry.insert(0, folder) else: self.name_entry.insert(0, "Mailbox name") self.server_entry.insert(0, "IMAP.mailbox.com") self.login_entry.insert(0, "*****@*****.**") self.folder_entry.insert(0, "inbox") self.name_entry.bind("<1>", self.on_click) self.server_entry.bind("<1>", self.on_click) self.login_entry.bind("<1>", self.on_click) self.password_entry.bind("<1>", self.on_click) self.folder_entry.bind("<1>", self.on_click) Label(self, text=_("Mailbox name")).grid(row=0, column=0, sticky="e", pady=(10, 4), padx=(10, 1)) Label(self, text=_("IMAP server")).grid(row=1, column=0, sticky="e", pady=4, padx=(10, 1)) Label(self, text=_("Login")).grid(row=2, column=0, sticky="e", pady=4, padx=(10, 1)) Label(self, text=_("Password")).grid(row=3, column=0, sticky="e", pady=4, padx=(10, 1)) Label(self, text=_("Folder to check")).grid(row=4, column=0, sticky="e", pady=4, padx=(10, 1)) self.name_entry.grid(row=0, column=1, sticky="w", pady=4, padx=(1, 10)) self.server_entry.grid(row=1, column=1, sticky="w", pady=4, padx=(1, 10)) self.login_entry.grid(row=2, column=1, sticky="w", pady=4, padx=(1, 10)) self.password_entry.grid(row=3, column=1, sticky="w", pady=4, padx=(1, 10)) self.folder_entry.grid(row=4, column=1, sticky="w", pady=4, padx=(1, 10)) frame = Frame(self) frame.grid(row=5, columnspan=2, pady=(0, 6)) Button(frame, text="Ok", command=self.save).grid(row=0, column=0, padx=(10, 4), pady=4) Button(frame, text=_("Cancel"), command=self.destroy).grid(row=0, column=1, pady=4, padx=(10, 4)) self.name_entry.bind("<Key-Return>", self.save) self.server_entry.bind("<Key-Return>", self.save) self.login_entry.bind("<Key-Return>", self.save) self.password_entry.bind("<Key-Return>", self.save) self.folder_entry.bind("<Key-Return>", self.save) self.name_entry.focus_set() self.wait_visibility() self.grab_set()
class Main(Frame): def __init__(self): super().__init__() # parent frame geometry w = 600 # width h = 400 # height x = self.master.winfo_screenwidth() # screen offset X y = self.master.winfo_screenheight() # screen offset Y x = int((x - w) / 2) # center horizontal y = int((y - h) / 2) # center vertical self.master.geometry('{}x{}+{}+{}'.format(w, h, x, y)) # this is the list containing all data files to be parsed self.files_to_parse = [] # initialize child UI elements self.init_UI_static() self.init_UI_dynamic() self.set_parse() def __str__(self): return 'Tkinter GUI' def init_UI_static(self): ''' Initialize static UI elements ''' # initialize window title and grid layout self.master.title('Siemens PBX Parsing Tool') self.pack(fill=BOTH, expand=1) # style self.style = Style() self.style.theme_use('clam') # default theme for now # Data File self.frame_data = Frame(self) self.frame_data.pack(fill=X) self.lbl_data = Label(self.frame_data, text='Data Files:', width=12, relief=FLAT) self.lbl_data.pack(side=LEFT, ipadx=5, padx=5, ipady=5, pady=5) self.frame_data_btn = Frame(self) self.frame_data_btn.pack(fill=X) self.btn_rm_data = Button(self.frame_data_btn, text='Remove', command=self.rm_data) self.btn_rm_data.pack(side=RIGHT, padx=5) self.btn_add_data = Button(self.frame_data_btn, text='Add', command=self.set_data) self.btn_add_data.pack(side=RIGHT, padx=5) # Excel Workbook self.frame_xlsx = Frame(self) self.frame_xlsx.pack(fill=X, pady=(10, 0)) self.lbl_xlsx = Label(self.frame_xlsx, text='Workbook:', width=12, relief=FLAT) self.lbl_xlsx.pack(side=LEFT, ipadx=5, padx=5, ipady=5, pady=5) self.frame_xlsx_btn = Frame(self) self.frame_xlsx_btn.pack(fill=X) self.btn_load_wb = Button(self.frame_xlsx_btn, text='Load...', command=self.set_wb) self.btn_load_wb.pack(side=RIGHT, padx=5) self.btn_new_wb = Button(self.frame_xlsx_btn, text='New...', command=lambda: self.set_wb(True)) self.btn_new_wb.pack(side=RIGHT, padx=5) # Presets File self.frame_preset = Frame(self) self.frame_preset.pack(fill=X, pady=(10, 0)) self.lbl_preset = Label(self.frame_preset, text='Presets File:', width=12, relief=FLAT) self.lbl_preset.pack(side=LEFT, ipadx=5, padx=5, ipady=5, pady=5) self.frame_preset_btn = Frame(self) self.frame_preset_btn.pack(fill=BOTH) self.btn_load_preset = Button(self.frame_preset_btn, text='Load...', command=self.set_preset) self.btn_load_preset.pack(side=RIGHT, padx=5) self.btn_new_preset = Button(self.frame_preset_btn, text='New...', command=lambda: self.set_preset(True)) self.btn_new_preset.pack(side=RIGHT, padx=5) # Lower button grid self.button_grid = Frame(self, borderwidth=0) self.button_grid.pack(side=BOTTOM, fill=BOTH, expand=True) self.btn_quit = Button(self.button_grid, text='Quit', command=self.quit) self.btn_quit.pack(side=RIGHT, padx=5, pady=5, anchor=SE) self.btn_start = Button(self.button_grid, text='Parse', command=self.parse) self.btn_start.pack(side=RIGHT, padx=5, pady=5, anchor=SE) def init_UI_dynamic(self): # initial dynamic UI states self.wb_file = None self.wb_files = StringVar() self.preset_file = settings.DEFAULT_PPATH self.preset_files = StringVar() self.preset_files.set('{}'.format(self.preset_file)) self.status = StringVar() update(self, 'Ready') print('Running') # update data file display self.display_data = Listbox(self.frame_data, relief=SUNKEN, background='#FFF') self.display_data.pack(side=TOP, fill=X, padx=5, pady=(10, 5), expand=True) # update status display display_status = Label(self.button_grid, textvariable=self.status) display_status.pack(side=LEFT, fill=X, padx=5, pady=5, anchor=SW) # update excel file display display_xlsx = Label(self.frame_xlsx, textvariable=self.wb_files, relief=SUNKEN, background='#FFF') display_xlsx.pack(fill=X, padx=5, expand=True) # update preset file display display_preset = Label(self.frame_preset, textvariable=self.preset_files, relief=SUNKEN, background='#FFF') display_preset.pack(fill=X, padx=5, expand=True) def parse(self): ''' Execute the parser ''' for f in self.files_to_parse: parser.RawFile(f, self.wb_file, self) def set_parse(self): if self.files_to_parse and self.wb_file and self.preset_file: self.btn_start.config(state='normal') else: self.btn_start.config(state='disabled') def set_data(self): ftypes = [('Text files', '*.txt')] f = askopenfilename(filetypes=ftypes) # push item to listbox self.display_data.insert(END, f) # push item to list self.files_to_parse.append(f) print(self.files_to_parse) # update parse button self.set_parse() def rm_data(self): # remove item from list self.files_to_parse.remove(self.display_data.get(ACTIVE)) # remove item from listbox self.display_data.delete(ACTIVE) # update parse button self.set_parse() def set_wb(self, new=False): ftypes = [('Excel workbooks', '*.xlsx'), ('Excel workbooks (legacy)', '*.xls')] if new: # prompt user for file name while True: # make sure file name includes at least one non-whitespace character filename = askstring( title='Create a new Excel workbook', prompt= 'Enter a name for the new workbook. (Exclude the file extension)' ) try: if not re.search(r'\S', filename): messagebox.showinfo( 'Invalid name', 'Please enter a non-blank file name.') else: filename += '.xlsx' break except TypeError: # escape if user hits 'cancel' return False # choose a directory and check for duplicate files while True: filedir = askdirectory( title='Choose a directory to save "{}"'.format(filename)) # escape if user hits 'cancel' if not filedir: return False filepath = os.path.join(filedir, filename) # confirm file overwrite if the file exists if os.path.exists(filepath): ow = messagebox.askquestion( 'File already exists', '{} already exists in this directory. Do you want to overwrite this file?' .format(filename)) # overwrite the file if the user clicks 'yes' if ow == 'yes': break else: break # save the new workbook new_wb = Workbook() new_wb.save(filepath) else: filepath = askopenfilename(filetypes=ftypes) # update data labels self.wb_file = filepath self.wb_files.set('{}'.format(self.wb_file)) self.set_parse() def set_preset(self, new=False): if new: f = askstring( title='Create a new preset file', prompt= 'Enter a name for the new preset file. (Exclude the file extension)' ) self.preset_file = savedata.Presets.new_pfile(f) else: ftypes = [('Python files', '*.py')] self.preset_file = askopenfilename(filetypes=ftypes) savedata.Presets.change_pfile(self.preset_file) self.preset_files.set('{}'.format(self.preset_file)) self.set_parse()
def save(event=None): name = name_entry.get().strip() if not mailbox: # new mailbox i = self.b_add.grid_info()['row'] self.b_add.grid_configure(row=i + 1) c = Checkbutton(self.frame) c.state(('selected',)) c.grid(row=i, column=0, pady=4, padx=(4, 0)) l = Label(self.frame, text=name) l.grid(row=i, column=1, padx=4, pady=4) b_edit = Button(self.frame, image=self.im_edit, width=1, command=lambda m=name: self.mailbox_info(m)) b_edit.grid(row=i, column=2, padx=4, pady=4) b_del = Button(self.frame, image=self.im_del, width=1, command=lambda m=name: self.del_mailbox(m)) b_del.grid(row=i, column=3, padx=4, pady=4) self.mailboxes[name] = [c, l, b_edit, b_del] elif name != mailbox: # change name of mailbox os.remove(os.path.join(LOCAL_PATH, mailbox)) c, l, b_edit, b_del = self.mailboxes[mailbox] del(self.mailboxes[mailbox]) l.configure(text=name) b_edit.configure(command=lambda m=name: self.mailbox_info(m)) b_del.configure(command=lambda m=name: self.del_mailbox(m)) self.mailboxes[name] = [c, l, b_edit, b_del] encrypt(name, self.pwd, server_entry.get().strip(), login_entry.get().strip(), password_entry.get().strip(), folder_entry.get().strip()) top.destroy()
class RNASeqFrame(PipelineFrame): def __init__(self, pipepanel, pipeline_name, *args, **kwargs): PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs) self.info = None eframe = self.eframe = LabelFrame(self, text="Options") #,fg=textLightColor,bg=baseColor) eframe.grid(row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5) label = Label(eframe, text="Pipeline") #,fg=textLightColor,bg=baseColor) label.grid(row=3, column=0, sticky=W, padx=10, pady=5) PipelineLabels = [ "Quality Control Analysis", "Differential Expression Analysis", "Fusion Detection", "Variant Calling" ] Pipelines = [ "initialqcrnaseq", "rnaseq", "rnaseqfusion", "rnaseqvargerm" ] self.label2pipeline = {k: v for k, v in zip(PipelineLabels, Pipelines)} PipelineLabel = self.PipelineLabel = StringVar() self.Pipeline = StringVar() PipelineLabel.set(PipelineLabels[0]) om = OptionMenu(eframe, PipelineLabel, *PipelineLabels, command=self.option_controller) om.config() #bg = widgetBgColor,fg=widgetFgColor) om["menu"].config() #bg = widgetBgColor,fg=widgetFgColor) #om.pack(side=LEFT,padx=20,pady=5) om.grid(row=3, column=1, sticky=W, padx=10, pady=5) rReadlens = [ 'Read Length is 50', 'Read Length is 75', 'Read Length is 100', 'Read Length is 125', 'Read Length is 150', 'Read Length is 250' ] self.rReadlen = rReadlen = StringVar() rReadlen.set(rReadlens[2]) self.om2 = OptionMenu(eframe, rReadlen, *rReadlens, command=self.option_controller) #self.om2.grid(row=4,column=1,sticky=W,padx=10,pady=5) rStrands = [ '0, Reads are Unstranded', '1, Reads are from Sense Strand', '2, Reads are from Anti-Sense Strand' ] self.rStrand = rStrand = StringVar() rStrand.set(rStrands[0]) self.om3 = OptionMenu(eframe, rStrand, *rStrands, command=self.option_controller) #self.om3.grid(row=5,column=1,sticky=W,padx=10,pady=5) rDegs = [ "yes, Report Differentially Expressed Genes", "no, Do not Report Differentially Expressed Genes" ] self.rDeg = rDeg = StringVar() rDeg.set(rDegs[0]) self.om4 = OptionMenu(eframe, rDeg, *rDegs, command=self.option_controller) self.om4.grid(row=6, column=1, sticky=W, padx=10, pady=5) # Show Groups Only (For initialqcrnaseq) self.om_groups = LabelFrame(eframe, text="Sample Information") self.groups_button = Button(self.om_groups, text="Set Groups", command=self.popup_groups) self.groups_button.grid(row=5, column=5, padx=10, pady=5) ##################### #Sample Threshold ##################### self.sampleLF = sampleLF = LabelFrame( eframe, text="Low Abundance Gene Thresholds") self.rMincount = rMincount = StringVar() rMincount.set("0.5") self.rMinsamples = rMinsamples = StringVar() rMinsamples.set("2") #rMincount.trace('w', lambda a,b,c,x="rmincount": makejson(x)) #Filter out genes < [5] read counts in < [2] samples # rminsamplesL = Label(sampleLF, text="Include genes with >=") # in") # rmincountE = Entry(sampleLF, bd =2, width=3, textvariable=rMincount) # rmincountL = Label(sampleLF, text="CPM in >=") # rminsamplesE = Entry(sampleLF, bd =2, width=3, textvariable=rMinsamples) # rminsamplesR = Label(sampleLF, text="samples") # # rminsamplesL.grid(row=9,column=1,sticky=W,padx=10,pady=5) # rmincountE.grid(row=9,column=2,sticky=W,padx=0,pady=5) # rmincountL.grid(row=9,column=3,sticky=W,padx=5,pady=5) # rminsamplesE.grid(row=9,column=4,sticky=W,padx=0,pady=5) # rminsamplesR.grid(row=9,column=5,sticky=W,padx=10,pady=5) # #rMinsamples.trace('w', lambda a,b,c,x="rmincount": makejson(x)) sampleLF.grid(row=6, column=0, columnspan=4, sticky=W, padx=20, pady=10) ##################### self.add_info(eframe) self.option_controller() def option_controller(self, *args, **kwargs): PipelineFrame.option_controller(self) self.Pipeline.set(self.label2pipeline[self.PipelineLabel.get()]) print(self.Pipeline.get()) if self.Pipeline.get() == 'initialqcrnaseq': self.om4.grid_forget() self.sampleLF.grid_forget() self.info.grid_forget() self.om_groups.grid(row=10, column=0, columnspan=6, sticky=W, padx=20, pady=10) elif self.Pipeline.get() == 'rnaseq': self.om4.grid(row=6, column=1, sticky=W, padx=10, pady=5) self.sampleLF.grid(row=8, column=0, columnspan=4, sticky=W, padx=20, pady=10) self.info.grid(row=10, column=0, columnspan=6, sticky=W, padx=20, pady=10) self.om_groups.grid_forget() else: self.om4.grid_forget() self.sampleLF.grid_forget() self.info.grid_forget() self.om_groups.grid_forget() def makejson_wrapper(self, *args, **kwargs): self.makejson(*args, **kwargs) def add_info(self, parent): if not self.info: self.info = LabelFrame(parent, text="Sample Information") self.groups_button = Button(self.info, text="Set Groups", command=self.popup_groups) self.contrasts_button = Button(self.info, text="Set Contrasts", command=self.popup_contrasts) self.groups_button.grid(row=5, column=5, padx=10, pady=5) self.contrasts_button.grid(row=5, column=6, padx=10, pady=5) def popup_groups(self): self.popup_window("Groups Information", "groups.tab") def popup_contrasts(self): self.popup_window("Contrasts Information", "contrasts.tab") def popup_window(self, text, filename): top = Toplevel() info = LabelFrame(top, text=text) #"Group Information") info_text = Text( info, width=50, height=8, #bg=projectBgColor, #fg=projectFgColor, font=("nimbus mono bold", "11")) def savefunc(): self.writepaste(filename, info_text) def loadfunc(): self.readpaste(filename, info_text) info_save_button = Button(info, text="Save", command=savefunc) info_load_button = Button(info, text="Load", command=loadfunc) #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 ) #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 ) info_load_button.grid(row=5, column=5, padx=10, pady=5) info_save_button.grid(row=5, column=6, padx=10, pady=5) info_text.grid(row=1, rowspan=3, column=1, columnspan=7, padx=5, pady=5) info.grid(row=7, column=0, columnspan=6, sticky=W, padx=20, pady=10) top.focus_force() def makejson(self, *args): #print(args[0]) caller = args[0] #global PD #global UnitsBak #global RGbak D = dict() try: F = open(self.workpath.get() + "/samples", "r") f = F.read().split("\n") F.close() for line in f: L = line.split() a = L.pop(0) D[a] = L samples = D except: samples = {"na": "na"} D = dict() try: F = open(self.workpath.get() + "/pairs", "r") f = F.read().split() F.close() for i in range(0, len(f), 2): # a=f[i].split(".")[0] # b=f[i+1].split(".")[0] a = f[i] b = f[i + 1] D[a + "+" + b] = [a, b] pairs = D except: pairs = {"na": "na"} D = dict() try: F = open(self.workpath.get() + "/contrasts.tab", "r") # f=F.read().split('\n') # F.close() # D["rsamps"]=f[0].split() # D["rgroups"]=f[1].split() # D["rcontrasts"]=f[2].split() # D["rlabels"]=f[3].split() f = F.readlines() F.close() ## sampl=[] ## grp=[] cont = [] cont_cpm_cutoff = [] cont_mincount = [] ## lbl=[] ## contrasts.tab can have 2,3 or 4 columns # col 1 and 2 are group1 and group2 respectively # col 3 is CPM cutoff value ... if not provided 0.5 will be used # col 4 is either min number of sample per group that need to satisfy the cpm cutoff criteria or fraction of samples that need # to satisfy the criteria... can be integer >=1 ... or fraction >=0.5 and <1 for x in f: xsplit = x.split() if len(xsplit) == 4: cont.append(xsplit[0]) cont.append(xsplit[1]) cont_cpm_cutoff.append(xsplit[2]) cont_mincount.append(xsplit[3]) elif len(xsplit) == 3: cont.append(xsplit[0]) cont.append(xsplit[1]) cont_cpm_cutoff.append(xsplit[2]) cont_mincount.append("0.5") elif len(xsplit) == 2: cont.append(xsplit[0]) cont.append(xsplit[1]) cont_cpm_cutoff.append("0.5") cont_mincount.append("0.5") D["rcontrasts"] = cont D["rcontrasts_cpm_cutoff"] = cont_cpm_cutoff D["rcontrasts_min_counts"] = cont_mincount # contrasts["rcontrasts"]=cont contrasts = D except: contrasts = {"rcontrasts": "na"} ## contrasts={"rsamps":"na","rgroups":"na","rcontrasts":"na","rlabels":"na"} ##------ D = dict() try: F = open(self.workpath.get() + "/groups.tab", "r") f = F.readlines() F.close() sampl = [] grp = [] # cont=[] lbl = [] for x in f: # if len(x.split()) == 4 or len(x.split()) == 3: if len(x.split()) == 3: sampl.append(x.split()[0]) grp.append(x.split()[1]) lbl.append(x.split()[2]) D["rsamps"] = sampl D["rgroups"] = grp D["rlabels"] = lbl # D["rcontrasts"]="na" # contrasts=D groups = D except: # contrasts={"rsamps":"na","rgroups":"na","rcontrasts":"na","rlabels":"na"} groups = {"rsamps": "na", "rgroups": "na", "rlabels": "na"} ##------ D = dict() FT = filetype #.get() # p = Popen("ls "+workpath.get()+"/*."+FT, shell=True, stdin=PIPE, stdout=PIPE, stderr=DEVNULL, close_fds=True) p = Popen("find " + self.workpath.get() + " -maxdepth 1 -type l -printf '%f\n' ", shell=True, stdin=PIPE, stdout=PIPE, stderr=DEVNULL, close_fds=True) a = p.stdout.read().decode(encoding='UTF-8').split("\n") RG = dict() b = a.pop() # tkinter.messagebox.showerror("",a) # if freezeunits.get()=="no": for i in a: key = re.sub(".realign", "", i.split("/")[-1]) key = re.sub(".bai", "", key) key = re.sub(".bam", "", key) key = re.sub(".sam", "", key) key = re.sub(".recal", "", key) key = re.sub(".dedup", "", key) key = re.sub(".sorted", "", key) key = re.sub(".fin", "", key) key = re.sub("\.R[12]", "", key) key = re.sub("_R[12]", "", key) key = re.sub(".fastq", "", key) key = re.sub(".gz", "", key) # key=re.sub("[\._](R[12]\.)*"+FT+"$","",i.split("/")[-1]) # key=re.sub(".R[12]."+FT+"$","",i.split("/")[-1]) # key=re.sub("([._]R[12][._])*([fin|sorted|dedup|recal|realign])*\.{0}$".format(FT),"",i.split("/")[-1]) D[key] = key RG[key] = { 'rgsm': key, 'rglb': 'na', 'rgpu': 'na', 'rgpl': 'ILLUMINA', 'rgcn': 'na' } units = D UnitsBak = D try: F = open(self.workpath.get() + "/rg.tab", "r") f = F.read().splitlines() F.close() for theLine in f: if not re.match("^ID", theLine): (rgid, rgsm, rglb, rgpl, rgpu, rgcn) = theLine.split("\t") RG[rgid] = { 'rgsm': rgsm, 'rglb': rglb, 'rgpu': rgpu, 'rgpl': rgpl, 'rgcn': rgcn } except: pass RGbak = RG # else: # units=UnitsBak # RG=RGbak # PD = dict() smparams = [] for i in range(len(self.parameters)): if cp[i].var.get() == "1": smparams.append(parameters[i]) AD = eval( open(join(PIPELINER_HOME, self.annotation.get() + ".json"), "r").read()) SD = AD['references']['rnaseq']['STARDIR'] # tkinter.messagebox.showinfo("initLock","SD={0}".format(SD)) gi = self.global_info PD = { 'project': { 'pfamily': gi.pfamily.get(), 'units': units, 'samples': samples, 'pairs': pairs, 'id': gi.eprojectid.get(), 'pi': gi.epi.get(), 'pipehome': gi.pipehome.get(), 'organism': gi.eorganism.get(), 'analyst': gi.eanalyst.get(), 'poc': gi.epoc.get(), 'pipeline': self.Pipeline.get(), 'version': "4.0", 'annotation': gi.annotation.get(), 'datapath': self.datapath.get(), 'targetspath': self.targetspath.get(), 'nends': self.nends, 'filetype': filetype, 'binset': "standard-bin", 'username': gi.euser.get(), 'flowcellid': gi.eflowcell.get(), 'platform': gi.eplatform.get(), 'custom': customRules, 'efiletype': efiletype, 'workpath': self.workpath.get(), 'batchsize': batchsize, "smparams": smparams, "rgid": RG, "cluster": "cluster_medium.json", "description": gi.description.get('1.0', END), "technique": gi.technique.get(), "TRIM": "yes", "groups": groups, "contrasts": contrasts, "SJDBOVERHANG": self.rReadlen.get().split(" ")[3], "STRANDED": self.rStrand.get().split(",")[0], "DEG": self.rDeg.get().split(",")[0].lower(), "STARSTRANDCOL": "{0}".format(int(self.rStrand.get().split(",")[0]) + 2), "MINSAMPLES": self.rMinsamples.get(), "MINCOUNTGENES": self.rMincount.get(), "MINCOUNTJUNCTIONS": self.rMincount.get(), "MINCOUNTGENEJUNCTIONS": self.rMincount.get(), "STARDIR": SD + self.rReadlen.get().split(" ")[3], "PICARDSTRAND": [ "NONE", "FIRST_READ_TRANSCRIPTION_STRAND", "SECOND_READ_TRANSCRIPTION_STRAND" ][int(self.rStrand.get().split(",")[0])] } } J = json.dumps(PD, sort_keys=True, indent=4, ensure_ascii=True) gi.jsonconf.delete("1.0", END) gi.jsonconf.insert(INSERT, J) self.saveproject(gi.jsonconf.get("1.0", END))
def setupGUI(self): """ 画面に必要なパーツを並べる """ self.parent.bind('<Control-q>', self.quit) self.parent.title('SimpleBitcoin GUI') self.pack(fill=BOTH, expand=1) self.create_menu() lf = LabelFrame(self, text='Current Balance') lf.pack(side=TOP, fill='both', expand='yes', padx=7, pady=7) lf2 = LabelFrame(self, text='') lf2.pack(side=BOTTOM, fill='both', expand='yes', padx=7, pady=7) #所持コインの総額表示領域のラベル self.balance = Label(lf, textvariable=self.coin_balance, font='Helvetica 20') self.balance.pack() #受信者となる相手の公開鍵 self.label = Label(lf2, text='Recipient Address:') self.label.grid(row=0, pady=5) self.recipient_pubkey = Entry(lf2, bd=2) self.recipient_pubkey.grid(row=0, column=1, pady=5) # 送金額 self.label2 = Label(lf2, text='Amount to pay :') self.label2.grid(row=1, pady=5) self.amountBox = Entry(lf2, bd=2) self.amountBox.grid(row=1, column=1, pady=5, sticky='NSEW') # 手数料 self.label3 = Label(lf2, text='Fee (Optional) :') self.label3.grid(row=2, pady=5) self.feeBox = Entry(lf2, bd=2) self.feeBox.grid(row=2, column=1, pady=5, sticky='NSEW') # 送金理由を書く欄(主にURLとか) self.label4 = Label(lf2, text='reason (Optional) :') self.label4.grid(row=3, pady=5) self.reasonBox = Entry(lf2, bd=2) self.reasonBox.grid(row=3, column=1, pady=5, sticky='NSEW') # 通信欄(公開メッセージ) self.label5 = Label(lf2, text='message (Optional) :') self.label5.grid(row=4, pady=5) self.messageBox = Entry(lf2, bd=2) self.messageBox.grid(row=4, column=1, pady=5, sticky='NSEW') # 間隔の開け方がよくわからんので空文字で場所確保 self.label4 = Label(lf2, text='') self.label4.grid(row=5, pady=5) # 送金実行ボタン self.sendBtn = Button(lf2, text='\nSend Coin(s)\n', command=self.sendCoins) self.sendBtn.grid(row=6, column=1, sticky='NSEW') # 下部に表示するステータスバー stbar = Label(self.winfo_toplevel(), textvariable=self.status_message, bd=1, relief=SUNKEN, anchor=W) stbar.pack(side=BOTTOM, fill=X)
class Merge(Frame): """Merge GEDCOM widget""" def __init__(self, master, **kwargs): super().__init__(master, **kwargs) warning = Label( self, font=("a", 7), wraplength=300, justify="center", text= _("Warning: This tool should only be used to merge GEDCOM files from this software. " "If you use other GEDCOM files, the result is not guaranteed."), ) self.files_to_merge = FilesToMerge(self) self.btn_add_file = Button(self, text=_("Add files"), command=self.add_files) buttons = Frame(self, borderwidth=20) self.btn_quit = Button(buttons, text=_("Quit"), command=self.quit) self.btn_save = Button(buttons, text=_("Merge"), command=self.save) warning.pack() self.files_to_merge.pack() self.btn_add_file.pack() self.btn_quit.pack(side="left", padx=(0, 40)) self.btn_save.pack(side="right", padx=(40, 0)) buttons.pack(side="bottom") def add_files(self): """open file explorer to pick a file""" for filename in filedialog.askopenfilenames( title=_("Open"), defaultextension=".ged", filetypes=(("GEDCOM", ".ged"), (_("All files"), "*.*")), ): self.files_to_merge.add_file(filename) def save(self): """merge GEDCOM files""" if not self.files_to_merge.files: messagebox.showinfo(_("Error"), message=_("Please add GEDCOM files")) return filename = filedialog.asksaveasfilename( title=_("Save as"), defaultextension=".ged", filetypes=(("GEDCOM", ".ged"), (_("All files"), "*.*")), ) tree = Tree() indi_counter = 0 fam_counter = 0 # read the GEDCOM data for file in self.files_to_merge.files.values(): ged = Gedcom(file, tree) # add informations about individuals for num in ged.indi: fid = ged.indi[num].fid if fid not in tree.indi: indi_counter += 1 tree.indi[fid] = Indi(tree=tree, num=indi_counter) tree.indi[fid].tree = tree tree.indi[fid].fid = ged.indi[num].fid tree.indi[fid].fams_fid |= ged.indi[num].fams_fid tree.indi[fid].famc_fid |= ged.indi[num].famc_fid tree.indi[fid].name = ged.indi[num].name tree.indi[fid].birthnames = ged.indi[num].birthnames tree.indi[fid].nicknames = ged.indi[num].nicknames tree.indi[fid].aka = ged.indi[num].aka tree.indi[fid].married = ged.indi[num].married tree.indi[fid].gender = ged.indi[num].gender tree.indi[fid].facts = ged.indi[num].facts tree.indi[fid].notes = ged.indi[num].notes tree.indi[fid].sources = ged.indi[num].sources tree.indi[fid].memories = ged.indi[num].memories tree.indi[fid].baptism = ged.indi[num].baptism tree.indi[fid].confirmation = ged.indi[num].confirmation tree.indi[fid].endowment = ged.indi[num].endowment if not (tree.indi[fid].sealing_child and tree.indi[fid].sealing_child.famc): tree.indi[fid].sealing_child = ged.indi[num].sealing_child # add informations about families for num in ged.fam: husb, wife = (ged.fam[num].husb_fid, ged.fam[num].wife_fid) if (husb, wife) not in tree.fam: fam_counter += 1 tree.fam[(husb, wife)] = Fam(husb, wife, tree, fam_counter) tree.fam[(husb, wife)].tree = tree tree.fam[(husb, wife)].chil_fid |= ged.fam[num].chil_fid tree.fam[(husb, wife)].fid = ged.fam[num].fid tree.fam[(husb, wife)].facts = ged.fam[num].facts tree.fam[(husb, wife)].notes = ged.fam[num].notes tree.fam[(husb, wife)].sources = ged.fam[num].sources tree.fam[(husb, wife)].sealing_spouse = ged.fam[num].sealing_spouse # merge notes by text tree.notes = sorted(tree.notes, key=lambda x: x.text) for i, n in enumerate(tree.notes): if i == 0: n.num = 1 continue if n.text == tree.notes[i - 1].text: n.num = tree.notes[i - 1].num else: n.num = tree.notes[i - 1].num + 1 # compute number for family relationships and print GEDCOM file tree.reset_num() with open(filename, "w", encoding="utf-8") as file: tree.print(file) messagebox.showinfo(_("Info"), message=_("Files successfully merged")) def quit(self): """prevent exception on quit during download""" super().quit() os._exit(1)
def init_ui(self): self.master.title("Louis") Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10') self.NUM_TRANSFORMS = 5 layer_options = [ "None", "FC1", "GRU", "FC2", ] transform_options = [ "None", "ablate", "oscillate", "threshold", "invert", ] self.gui_elements = [] button = Button(self, text="Update", command=self.run) button.grid(column=0, row=self.NUM_TRANSFORMS) Label(self, text="layer").grid(row=0, column=1) Label(self, text="transform").grid(row=0, column=2) Label(self, text="units/value").grid(row=0, column=3) Label(self, text="midi").grid(row=0, column=4) Label(self, text="lfo_freq").grid(row=0, column=5) Label(self, text="min").grid(row=0, column=6) Label(self, text="max").grid(row=0, column=7) for i in range(self.NUM_TRANSFORMS): var_dict = {} var_dict["layer"] = StringVar() var_dict["transform"] = StringVar() var_dict["unit_value"] = StringVar() var_dict["unit_value"].set("0.5") var_dict["unit_midi"] = StringVar() var_dict["param"] = [] for j in range(2): param_dict = {} param_dict["param_value"] = StringVar() param_dict["param_value"].set("0.5") param_dict["param_midi"] = StringVar() param_dict["param_min"] = StringVar() param_dict["param_max"] = StringVar() param_dict["param_lfo"] = StringVar() param_dict["param_label"] = Label(self, text="NA") var_dict["param"].append(param_dict) self.gui_elements.append(var_dict) r = (i * 3) + 1 layer_menu = OptionMenu(self, var_dict["layer"], *layer_options, command=self.option_changed) layer_menu.config(width=10) layer_menu.grid(row=r, column=1) transform_menu = OptionMenu(self, var_dict["transform"], *transform_options, command=self.option_changed) transform_menu.config(width=10) transform_menu.grid(row=r, column=2) ENTRY_WIDTH = 8 unit_value = Entry(self, textvariable=var_dict["unit_value"], width=ENTRY_WIDTH) unit_value.grid(row=r, column=3) unit_midi = Entry(self, textvariable=var_dict["unit_midi"], width=ENTRY_WIDTH) unit_midi.grid(row=r, column=4) for j in range(2): label = var_dict["param"][j]["param_label"] label.grid(row=r + (j + 1), columnspan=2, column=1) param_value = Entry( self, textvariable=var_dict["param"][j]["param_value"], width=ENTRY_WIDTH) param_value.grid(row=r + (j + 1), column=3) param_midi = Entry( self, textvariable=var_dict["param"][j]["param_midi"], width=ENTRY_WIDTH) param_midi.grid(row=r + (j + 1), column=4) param_lfo = Entry( self, textvariable=var_dict["param"][j]["param_lfo"], width=ENTRY_WIDTH) param_lfo.grid(row=r + (j + 1), column=5) param_min = Entry( self, textvariable=var_dict["param"][j]["param_min"], width=ENTRY_WIDTH) param_min.grid(row=r + (j + 1), column=6) param_max = Entry( self, textvariable=var_dict["param"][j]["param_max"], width=ENTRY_WIDTH) param_max.grid(row=r + (j + 1), column=7) self.pack()
def __init__(self, tab_control, username, user_controller, expense_tab): """Initializes the preferences tab, where the user can customise the application, with all visual elements""" # create preference tab with title 'Preferences' self.preferences_tab = ttk.Frame(tab_control) tab_control.add(self.preferences_tab, text='Preferences') self.expense_tab = expense_tab self.username = username self.user_controller = user_controller # Category list is saved as list variable and as StringVar instance: # The list represents the custom categories of the user and is loaded from the database, # the StringVar is the TK representation and is the object containing the values for the Listbox self.category_list = self.user_controller.get_categories(self.username) self.category_var = StringVar(value=self.category_list) # Previously set budget is loaded from the database new_category = StringVar() b, p = self.user_controller.get_budget(self.username) budget = StringVar(value=b) chosen_period = StringVar(value=p) Label(self.preferences_tab, text="Your categories:", font='Helvetica 16 bold').grid(row=0, column=0, padx=15, pady=15, sticky='w') y_scroll = Scrollbar(self.preferences_tab, orient='vertical') y_scroll.grid(row=1, column=0, pady=15, padx=(0, 15), sticky='nse') listbox = Listbox(self.preferences_tab, listvar=self.category_var, yscrollcommand=y_scroll.set, bd=0, height=15) listbox.grid(row=1, column=0, padx=(15, 0), pady=15, sticky='w') y_scroll['command'] = listbox.yview Button(self.preferences_tab, text='Remove', command=lambda: self.remove_category(listbox), style='W.TButton')\ .grid(row=1, column=1, padx=15, pady=15, sticky='s') Label(self.preferences_tab, text='Add category:').grid(row=2, column=0, padx=15, sticky='w') Entry(self.preferences_tab, textvariable=new_category).grid(row=3, column=0, padx=15, sticky='ew') Button(self.preferences_tab, text='Add', command=lambda: self.add_category(new_category)).grid(row=3, column=1) Label(self.preferences_tab, text="Set yourself a budget!", font='Helvetica 16 bold')\ .grid(row=6, column=0, padx=(15, 0), pady=20, sticky='w') Entry(self.preferences_tab, textvariable=budget).grid(row=7, column=0, padx=(15, 0), sticky='w') Label(self.preferences_tab, text='€').grid(row=7, column=0, sticky='e') OptionMenu(self.preferences_tab, chosen_period, p, *period_list).grid(row=7, column=1) Button(self.preferences_tab, text='Set budget', command=lambda: self.set_budget(budget, chosen_period))\ .grid(row=7, column=2)
def __init__(self, pipepanel, pipeline_name, *args, **kwargs): PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs) self.info = None eframe = self.eframe = LabelFrame(self, text="Options") #,fg=textLightColor,bg=baseColor) eframe.grid(row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5) label = Label(eframe, text="Pipeline") #,fg=textLightColor,bg=baseColor) label.grid(row=3, column=0, sticky=W, padx=10, pady=5) PipelineLabels = [ "Quality Control Analysis", "Differential Expression Analysis", "Fusion Detection", "Variant Calling" ] Pipelines = [ "initialqcrnaseq", "rnaseq", "rnaseqfusion", "rnaseqvargerm" ] self.label2pipeline = {k: v for k, v in zip(PipelineLabels, Pipelines)} PipelineLabel = self.PipelineLabel = StringVar() self.Pipeline = StringVar() PipelineLabel.set(PipelineLabels[0]) om = OptionMenu(eframe, PipelineLabel, *PipelineLabels, command=self.option_controller) om.config() #bg = widgetBgColor,fg=widgetFgColor) om["menu"].config() #bg = widgetBgColor,fg=widgetFgColor) #om.pack(side=LEFT,padx=20,pady=5) om.grid(row=3, column=1, sticky=W, padx=10, pady=5) rReadlens = [ 'Read Length is 50', 'Read Length is 75', 'Read Length is 100', 'Read Length is 125', 'Read Length is 150', 'Read Length is 250' ] self.rReadlen = rReadlen = StringVar() rReadlen.set(rReadlens[2]) self.om2 = OptionMenu(eframe, rReadlen, *rReadlens, command=self.option_controller) #self.om2.grid(row=4,column=1,sticky=W,padx=10,pady=5) rStrands = [ '0, Reads are Unstranded', '1, Reads are from Sense Strand', '2, Reads are from Anti-Sense Strand' ] self.rStrand = rStrand = StringVar() rStrand.set(rStrands[0]) self.om3 = OptionMenu(eframe, rStrand, *rStrands, command=self.option_controller) #self.om3.grid(row=5,column=1,sticky=W,padx=10,pady=5) rDegs = [ "yes, Report Differentially Expressed Genes", "no, Do not Report Differentially Expressed Genes" ] self.rDeg = rDeg = StringVar() rDeg.set(rDegs[0]) self.om4 = OptionMenu(eframe, rDeg, *rDegs, command=self.option_controller) self.om4.grid(row=6, column=1, sticky=W, padx=10, pady=5) # Show Groups Only (For initialqcrnaseq) self.om_groups = LabelFrame(eframe, text="Sample Information") self.groups_button = Button(self.om_groups, text="Set Groups", command=self.popup_groups) self.groups_button.grid(row=5, column=5, padx=10, pady=5) ##################### #Sample Threshold ##################### self.sampleLF = sampleLF = LabelFrame( eframe, text="Low Abundance Gene Thresholds") self.rMincount = rMincount = StringVar() rMincount.set("0.5") self.rMinsamples = rMinsamples = StringVar() rMinsamples.set("2") #rMincount.trace('w', lambda a,b,c,x="rmincount": makejson(x)) #Filter out genes < [5] read counts in < [2] samples # rminsamplesL = Label(sampleLF, text="Include genes with >=") # in") # rmincountE = Entry(sampleLF, bd =2, width=3, textvariable=rMincount) # rmincountL = Label(sampleLF, text="CPM in >=") # rminsamplesE = Entry(sampleLF, bd =2, width=3, textvariable=rMinsamples) # rminsamplesR = Label(sampleLF, text="samples") # # rminsamplesL.grid(row=9,column=1,sticky=W,padx=10,pady=5) # rmincountE.grid(row=9,column=2,sticky=W,padx=0,pady=5) # rmincountL.grid(row=9,column=3,sticky=W,padx=5,pady=5) # rminsamplesE.grid(row=9,column=4,sticky=W,padx=0,pady=5) # rminsamplesR.grid(row=9,column=5,sticky=W,padx=10,pady=5) # #rMinsamples.trace('w', lambda a,b,c,x="rmincount": makejson(x)) sampleLF.grid(row=6, column=0, columnspan=4, sticky=W, padx=20, pady=10) ##################### self.add_info(eframe) self.option_controller()
def __init__(self): super().__init__() self.master.title("Income calculator app") self.pack(fill=BOTH, expand=True) # label frame0 = Frame(self) frame0.pack(fill=X) title = Label(frame0, text='Welcome to the app', font=("Times New Roman", 20)) title.pack() # frame 1 frame1a = Frame(self) frame1a.pack(fill=X, padx=10, pady=10) name_label = Label(frame1a, text="Employee name :", width=15) name_label.pack(side=LEFT, padx=5, pady=5) name = Entry(frame1a) name.pack(fill=X, padx=5, expand=True) frame1b = Frame(self) frame1b.pack(fill=X, padx=10, pady=10) destination_label = Label(frame1b, text="Destination :", width=15) destination_label.pack(side=LEFT, padx=5, pady=5) # destination = Entry(frame1b) # destination.pack(fill=X, padx=5, expand=True) data = pd.read_csv("country_currency.csv") data.dropna(subset=['Country'], inplace=True) destination_select = StringVar(frame1b) destination = AutocompleteCombobox( frame1b, textvariable=destination_select, width=20, completevalues=data['Country'].to_list()) destination.pack() # frame 2 frame2 = Frame(self) frame2.pack(fill=X) netIncome_label = Label(frame2, text='Net income (per year)', width=20) netIncome_label.pack(side=LEFT, padx=5, pady=5) netIncome = Entry(frame2) netIncome.pack(fill=X, padx=5, expand=True) #frame 3 frame3 = Frame(self) frame3.pack(pady=10) maritalStatus_label = Label(frame3, text='Marital status ', width=15) maritalStatus_label.pack(side=LEFT, padx=5, pady=5) maritalStatus_select = StringVar(frame3) maritalStatus_select.set(maritalStatusList[0]) maritalStatus = OptionMenu(frame3, maritalStatus_select, *maritalStatusList) maritalStatus.pack(side=LEFT, padx=10) nKids_label = Label(frame3, text='Number of kids :', width=20) nKids_select = IntVar(frame3) nKids_select.set(nKids_list[0]) nKids_entry = OptionMenu(frame3, nKids_select, *nKids_list) nKids_label.pack(side=LEFT) nKids_entry.pack(side=LEFT) def get_info(): try: df_row = data[data['Country'] == destination_select.get()] currency_code = str(df_row['Currency code'].values[0]) currency_name = str(df_row['Currency'].values[0]) except: messagebox.showwarning('Warning', 'Please select a destination') currency_code = 'EUR' currecy_name = 'Euros' country2_select.set(currency_code) currency.set(currency_name) #frame 3 frame3a = Frame(self) frame3a.pack(pady=5) info_button = Button(frame3a, text='Get info', command=get_info) info_button.pack(side=TOP) forex_label = Label(frame3a, text='Currency conversion From ', width=15) forex_label.pack(side=LEFT, padx=5, pady=5) country1_select = StringVar(frame3a) country1_select.set(currecy_list[0]) country1 = OptionMenu(frame3a, country1_select, *currecy_list) country1.pack(side=LEFT, padx=10) forex_label2 = Label(frame3a, text=' To ', width=5) country2_select = StringVar(frame3a) currency = StringVar(frame3a) country2_select.set('EUR') currency.set('Euros') country2 = Text(frame3a, height=1, width=10) country2.insert(END, country2_select.get()) forex_label2.pack(side=LEFT) country2.pack(side=LEFT) forex_display = Text(frame3a, height=1, width=10) c = CurrencyRates() forex_display.insert( END, c.get_rate(country1_select.get(), country2_select.get())) forex_display.pack(side=RIGHT, padx=10) forex_conversion = StringVar() forex_conversion.set('1.0') def callback(*args): forex_display.delete(1.0, "end") country2.delete(1.0, "end") try: forex_conversion.set( c.get_rate(country1_select.get(), country2_select.get())) forex_display.insert(END, forex_conversion.get()) country2.insert(END, country2_select.get()) except Exception as exception_error: messagebox.showwarning('Warning', exception_error) forex_conversion.set('1.0') forex_display.insert(END, '0') country2_select.trace("w", callback) country1_select.trace("w", callback) #frame 4 frame4 = Frame(self) frame4.pack(pady=10) radioInput = IntVar(self) radioInput.set(1) R1 = Radiobutton(frame4, text="Yearly", variable=radioInput, value=1) R2 = Radiobutton(frame4, text="Montly", variable=radioInput, value=2) R3 = Radiobutton(frame4, text="Daily", variable=radioInput, value=3) period_label = Label(frame4, text='Calculating for period :') period_label.pack(side=LEFT) R1.pack(side=LEFT, pady=10) R2.pack(side=LEFT, pady=10) R3.pack(side=RIGHT, pady=10) now = datetime.now() # current date and time def get_string(): income = float('0' + netIncome.get()) status = str(maritalStatus_select.get()) output_string = "Income calculation \t {} \n\n".format( now.strftime("%d/%m/%Y, %H:%M:%S")) output_string += "Employee name :{} \n\n".format(name.get()) output_string += "Destination :{} \n".format( destination_select.get()) output_string += "Currency :{} - {} \n".format( country2_select.get(), currency.get()) output_string += "\nNet yearly income = {} {} ".format( income, country1_select.get()) output_string += "\n\nCalcualting for " + str( period[radioInput.get() - 1]) if radioInput.get() == 2: income = round(income / 12, 2) elif radioInput.get() == 3: income = round(income / 365, 2) output_string += "\nNet income = {} {} \nMarital status = {} ".format( income, country1_select.get(), status) output_string += "\nNumber of kids = " + str(nKids_select.get()) try: tax_rate = get_tax(country=destination_select.get()) social_sec_em, social_sec_com = get_social_security( country=destination_select.get()) except: messagebox.showwarning( 'Warning', 'Tax / social security information NOT found') tax_rate = 0 social_sec_em, social_sec_com = 0, 0 output_string += "\n\nTax rate : {} %".format(tax_rate) output_string += "\nSocial security rates:" output_string += "\n employee : {} %".format(social_sec_em) output_string += "\n company : {} %".format(social_sec_com) output_string += "\n\n Tax amount : {}".format( round(income * tax_rate / 100, 2)) output_string += "\n Employee social security amount : {}".format( round(income * social_sec_em / 100, 2)) output_string += "\n Company social security amount : {}".format( round(income * social_sec_com / 100, 2)) total = float( get_total(income=income, rate1=tax_rate, rate2=social_sec_em, rate3=social_sec_com)) output_string += "\n\nTotal : {} {}".format( total, country1_select.get()) output_string += '\n conversion = {}'.format( forex_conversion.get()) total *= float(forex_conversion.get()) output_string += "\n after conversion {} {} ".format( round(total, 2), country2_select.get()) return output_string def write_pdf(): pdf = FPDF() pdf.add_page() pdf.set_margins(30, 50, 25) pdf.set_font("Arial", size=15) output_string = get_string().split('\n') for s in output_string: pdf.cell(200, 10, txt=s, ln=1) pdf.output(name.get() + ' ' + str(now.strftime("%d_%m_%Y")) + '_info.pdf') def write_txt(): with open( name.get() + ' ' + str(now.strftime("%d_%m_%Y")) + '_info.txt', 'w') as sfile: sfile.write(get_string()) def string_display(): output_display.delete(1.0, END) output_display.insert(END, get_string()) frame5 = Frame(self, borderwidth=1) frame5.pack(fill=BOTH, expand=True, padx=5, pady=5) output_display = Text(frame5, height=15) scroll_y = Scrollbar(frame5, orient="vertical", command=output_display.yview) scroll_y.pack(side="right", expand=True, fill="y", padx=2, pady=2) output_display.pack(side='left', fill=X, padx=2, pady=2) output_display.configure(yscrollcommand=scroll_y.set) frame_final = Frame(self, relief=RAISED, borderwidth=1) frame_final.pack(fill=X, padx=10, pady=5) submit_button = Button(frame_final, text='Submit', command=string_display) submit_button.pack(side=LEFT) file_type_label = Label(frame_final, text='Choose file type:') file_type_label.pack() file_save_type = StringVar() file_save_type.set(save_list[0]) file_save = OptionMenu(frame_final, file_save_type, *save_list) def save_to_file(): if file_save_type.get() == 'txt': write_txt() messagebox.showinfo('Saved!', 'Saved as text file') elif file_save_type.get() == 'pdf': write_pdf() messagebox.showinfo('Saved!', 'Saved as pdf file') else: messagebox.showwarning('Warning', 'Please select text file or pdf') save_button = Button(frame_final, text='Save to file', command=save_to_file) save_button.pack(side=RIGHT) file_save.pack(side=RIGHT)
def makeFrameWidget(self): ''' makes frame widget ''' #make regular frame stuff -- label and tier self.frames_canvas = Canvas(self.canvas_frame, width=self.canvas_width, height=self.canvas_height, background='gray', highlightthickness=0) frames_label = Canvas(self.frame, width=self.label_width, height=self.canvas_height, highlightthickness=0, background='gray') frames_label.create_text(self.label_width, 0, anchor='ne', justify='center', text='frames: ', width=self.label_width, activefill='blue') # make subframe to go on top of label canvas sbframe = Frame(frames_label) #put new widgets onto subframe offset = self.app.Data.getFileLevel('offset') if offset != None: self.frame_shift.set(offset) # for audio alignment go_btn = Button(sbframe, text='Offset', command=self.shiftFrames, takefocus=0) # minmax = len(self.app.Audio.sfile)*1000 txtbox = Spinbox(sbframe, textvariable=self.frame_shift, width=7, from_=-10000000, to=10000000) txtbox.bind('<Escape>', lambda ev: sbframe.focus()) txtbox.bind('<Return>', lambda ev: self.shiftFrames()) go_btn.grid(row=0, column=0, sticky='e') txtbox.grid(row=0, column=1, sticky='e') # put subframe on canvas window = frames_label.create_window(self.label_width * .3, self.canvas_height / 3, anchor='nw', window=sbframe) # ensure position of subframe gets updated frames_label.bind( '<Configure>', lambda e: frames_label.itemconfig(window, width=e.width)) sbframe.bind( '<Configure>', lambda e: frames_label.configure( scrollregion=frames_label.bbox("all"))) self.TkWidgets.append({ 'name': self.frameTierName, 'frames': self.frames_canvas, 'frames-label': frames_label }) self.frames_canvas.bind("<Button-1>", self.getClickedFrame)
def layout_components(self): self.pack(fill=tk.BOTH, expand=False, padx=PADX, pady=PADY) error_font = font.Font(family="Ariel", size=8) # Variables self.username = tk.StringVar() self.username.set("") self.password = tk.StringVar() self.password.set("") # Username Row user_Frame = Frame(self) user_Frame.pack(fill=tk.X) user_Label = Label(user_Frame, text="Username:"******"<FocusOut>", self.enable_sign_in) self.user_Entry.pack(fill=tk.X, padx=PADX, pady=PADY, expand=True) # Password Row pass_Frame = Frame(self) pass_Frame.pack(fill=tk.X) pass_Label = Label(pass_Frame, text="Password:"******"*") self.pass_Entry.bind("<FocusOut>", self.enable_sign_in) self.pass_Entry.pack(fill=tk.X, padx=PADX, pady=PADY, expand=True) # Error Row err_Frame = Frame(self) err_Frame.pack(fill=tk.X) self.err_Label = Label(err_Frame, text="", foreground="red", font=error_font) self.err_Label.pack(side=tk.LEFT, anchor="center", expand=True, padx=PADX, pady=PADY) # Button Row button_Frame = Frame(self) button_Frame.pack(fill=tk.X) # Cancel Button cncl_Button = Button(button_Frame, text="Cancel", command=self.cancel) cncl_Button.pack(side=tk.RIGHT, padx=PADX, pady=PADY, expand=False) # Sign in Button self.sgnn_Button = Button(button_Frame, text="Sign in", state="disabled", command=self._sign_in) self.sgnn_Button.pack(side=tk.RIGHT, padx=PADX, pady=PADY, expand=False) # Register Row register_Frame = Frame(self) register_Frame.pack(fill=tk.X) register_Button = Button(register_Frame, text="Register", command=self._show_register) register_Button.pack(side=tk.RIGHT, padx=PADX, pady=PADY, expand=False) register_Label = Label(register_Frame, text="Not a Member of ExchangeGram?") register_Label.pack(side=tk.RIGHT, padx=PADX, pady=PADY)
def reset(this) -> None: font_family = ConfigLoader.get("font-family") font_color = ConfigLoader.get("font-color") std_font_size = 12 tkinter.Label(this, text="Regisztráció", fg=font_color, bg=this["bg"], font=(font_family, 26)).grid(row=0, column=0, columnspan=2, sticky="NESW") tkinter.Label(this, text="Felhasználónév", fg=font_color, bg=this["bg"], font=(font_family, std_font_size)).grid(row=1, column=0, sticky="E") tkinter.Label(this, text="Jelszó", fg=font_color, bg=this["bg"], font=(font_family, std_font_size)).grid(row=2, column=0, sticky="E") tkinter.Label(this, text="Jelszó újra", fg=font_color, bg=this["bg"], font=(font_family, std_font_size)).grid(row=3, column=0, sticky="E") tkinter.Label(this, text="Email", fg=font_color, bg=this["bg"], font=(font_family, std_font_size)).grid(row=4, column=0, sticky="E") Button(this, command=this.get_date, text="Születési dátum").grid(row=5, column=0, sticky="E") this.uname_entry = Entry(this) this.pwd_entry = Entry(this, show="*") this.apwd_entry = Entry(this, show="*") this.email_entry = Entry(this) this.birthdate_entry = Entry(this) this.uname_entry.grid(row=1, column=1, sticky="W") this.pwd_entry.grid(row=2, column=1, sticky="W") this.apwd_entry.grid(row=3, column=1, sticky="W") this.email_entry.grid(row=4, column=1, sticky="W") this.birthdate_entry.grid(row=5, column=1, sticky="W") this.birthdate_entry.config(state="disabled") Button(this, command=this.go_to_login, text="Bejelentkezés").grid(row=7, column=0, sticky="E") Button(this, command=this.regist, text="Regisztráció").grid(row=7, column=1, sticky="W")
class Manager(Toplevel): """Mailbox Manager.""" def __init__(self, master, pwd): """Create the mailbox manager dialog.""" Toplevel.__init__(self, master, class_="CheckMails") self.title(_("Mailbox Manager")) self.minsize(200, 10) self.pwd = pwd self.resizable(False, False) self.protocol("WM_DELETE_WINDOW", self.quit) self.im_add = PhotoImage(master=self, file=ADD) self.im_del = PhotoImage(master=self, file=DEL) self.im_edit = PhotoImage(master=self, file=EDIT) self.mailboxes = {} active = CONFIG.get("Mailboxes", "active").split(", ") inactive = CONFIG.get("Mailboxes", "inactive").split(", ") while "" in active: active.remove("") while "" in inactive: inactive.remove("") active.sort() inactive.sort() self.frame = Frame(self) self.columnconfigure(0, weight=1) self.frame.columnconfigure(1, weight=1) self.frame.grid(row=0, column=0, padx=10, pady=10, sticky="eswn") i = -1 for i, box in enumerate(active): c = Checkbutton(self.frame) c.state(('selected',)) c.grid(row=i, column=0, pady=4, padx=(4, 0)) l = Label(self.frame, text=box) l.grid(row=i, column=1, padx=4, pady=4) b_edit = Button(self.frame, image=self.im_edit, width=1, command=lambda m=box: self.mailbox_info(m)) b_edit.grid(row=i, column=2, padx=4, pady=4) b_del = Button(self.frame, image=self.im_del, width=1, command=lambda m=box: self.del_mailbox(m)) b_del.grid(row=i, column=3, padx=4, pady=4) self.mailboxes[box] = [c, l, b_edit, b_del] for box in inactive: i += 1 c = Checkbutton(self.frame) c.grid(row=i, column=0, pady=4, padx=(4, 0)) l = Label(self.frame, text=box) l.grid(row=i, column=1, padx=4, pady=4) b_edit = Button(self.frame, image=self.im_edit, width=1, command=lambda m=box: self.mailbox_info(m)) b_edit.grid(row=i, column=2, padx=4, pady=4) b_del = Button(self.frame, image=self.im_del, width=1, command=lambda m=box: self.del_mailbox(m)) b_del.grid(row=i, column=3, padx=4, pady=4) self.mailboxes[box] = [c, l, b_edit, b_del] self.b_add = Button(self.frame, image=self.im_add, command=self.mailbox_info, width=1) self.b_add.grid(row=i + 1, column=0, columnspan=4, pady=4, padx=4, sticky='w') def quit(self): """Save configuration and destroy the dialog.""" active = [] inactive = [] for box, (c, l, b1, b2) in self.mailboxes.items(): if "selected" in c.state(): active.append(box) else: inactive.append(box) CONFIG.set("Mailboxes", "active", ", ".join(active)) CONFIG.set("Mailboxes", "inactive", ", ".join(inactive)) save_config() self.destroy() def del_mailbox(self, mailbox): """Delete the mailbox.""" try: os.remove(os.path.join(LOCAL_PATH, mailbox)) except FileNotFoundError: pass c, l, b_edit, b_del = self.mailboxes[mailbox] del(self.mailboxes[mailbox]) c.grid_forget() l.grid_forget() b_edit.grid_forget() b_del.grid_forget() def mailbox_info(self, mailbox=""): """GUI to add or modify a mailbox login information.""" def on_click(event): event.widget.focus_set() event.widget.selection_range(0, 'end') event.widget.unbind('<1>') return "break" def save(event=None): name = name_entry.get().strip() if not mailbox: # new mailbox i = self.b_add.grid_info()['row'] self.b_add.grid_configure(row=i + 1) c = Checkbutton(self.frame) c.state(('selected',)) c.grid(row=i, column=0, pady=4, padx=(4, 0)) l = Label(self.frame, text=name) l.grid(row=i, column=1, padx=4, pady=4) b_edit = Button(self.frame, image=self.im_edit, width=1, command=lambda m=name: self.mailbox_info(m)) b_edit.grid(row=i, column=2, padx=4, pady=4) b_del = Button(self.frame, image=self.im_del, width=1, command=lambda m=name: self.del_mailbox(m)) b_del.grid(row=i, column=3, padx=4, pady=4) self.mailboxes[name] = [c, l, b_edit, b_del] elif name != mailbox: # change name of mailbox os.remove(os.path.join(LOCAL_PATH, mailbox)) c, l, b_edit, b_del = self.mailboxes[mailbox] del(self.mailboxes[mailbox]) l.configure(text=name) b_edit.configure(command=lambda m=name: self.mailbox_info(m)) b_del.configure(command=lambda m=name: self.del_mailbox(m)) self.mailboxes[name] = [c, l, b_edit, b_del] encrypt(name, self.pwd, server_entry.get().strip(), login_entry.get().strip(), password_entry.get().strip(), folder_entry.get().strip()) top.destroy() top = Toplevel(self, class_="CheckMails") top.title(_("Login information")) top.transient(self) top.resizable(False, False) name_entry = Entry(top, justify='center', width=32) server_entry = Entry(top, justify='center', width=32) login_entry = Entry(top, justify='center', width=32) password_entry = Entry(top, show='*', justify='center', width=32) folder_entry = Entry(top, justify='center', width=32) if mailbox: name_entry.insert(0, mailbox) server, login, password, folder = decrypt(mailbox, self.pwd) if server is None: top.destroy() self.del_mailbox(mailbox) return server_entry.insert(0, server) login_entry.insert(0, login) password_entry.insert(0, password) folder_entry.insert(0, folder) else: name_entry.insert(0, "Mailbox name") server_entry.insert(0, "IMAP.mailbox.com") login_entry.insert(0, "*****@*****.**") folder_entry.insert(0, "inbox") name_entry.bind("<1>", on_click) server_entry.bind("<1>", on_click) login_entry.bind("<1>", on_click) password_entry.bind("<1>", on_click) folder_entry.bind("<1>", on_click) Label(top, text=_("Mailbox name")).grid(row=0, column=0, sticky="e", pady=(10, 4), padx=(10, 1)) Label(top, text=_("IMAP server")).grid(row=1, column=0, sticky="e", pady=4, padx=(10, 1)) Label(top, text=_("Login")).grid(row=2, column=0, sticky="e", pady=4, padx=(10, 1)) Label(top, text=_("Password")).grid(row=3, column=0, sticky="e", pady=4, padx=(10, 1)) Label(top, text=_("Folder to check")).grid(row=4, column=0, sticky="e", pady=4, padx=(10, 1)) name_entry.grid(row=0, column=1, sticky="w", pady=4, padx=(1, 10)) server_entry.grid(row=1, column=1, sticky="w", pady=4, padx=(1, 10)) login_entry.grid(row=2, column=1, sticky="w", pady=4, padx=(1, 10)) password_entry.grid(row=3, column=1, sticky="w", pady=4, padx=(1, 10)) folder_entry.grid(row=4, column=1, sticky="w", pady=4, padx=(1, 10)) frame = Frame(top) frame.grid(row=5, columnspan=2, pady=(0, 6)) Button(frame, text="Ok", command=save).grid(row=0, column=0, padx=(10, 4), pady=4) Button(frame, text=_("Cancel"), command=top.destroy).grid(row=0, column=1, pady=4, padx=(10, 4)) top.grab_set() name_entry.bind("<Key-Return>", save) server_entry.bind("<Key-Return>", save) login_entry.bind("<Key-Return>", save) password_entry.bind("<Key-Return>", save) folder_entry.bind("<Key-Return>", save) name_entry.focus_set()
class Download(Frame): """Main widget""" def __init__(self, master, **kwargs): super().__init__(master, borderwidth=20, **kwargs) self.fs = None self.tree = None self.logfile = None # User information self.info_tree = False self.start_time = None info = Frame(self, borderwidth=10) self.info_label = Label( info, wraplength=350, borderwidth=20, justify="center", font=("a", 10, "bold"), ) self.info_indis = Label(info) self.info_fams = Label(info) self.info_sources = Label(info) self.info_notes = Label(info) self.time = Label(info) self.info_label.grid(row=0, column=0, columnspan=2) self.info_indis.grid(row=1, column=0) self.info_fams.grid(row=1, column=1) self.info_sources.grid(row=2, column=0) self.info_notes.grid(row=2, column=1) self.time.grid(row=3, column=0, columnspan=2) self.form = Frame(self) self.sign_in = SignIn(self.form) self.options = None self.title = Label(self, text=_("Sign In to FamilySearch"), font=("a", 12, "bold")) buttons = Frame(self) self.btn_quit = Button(buttons, text=_("Quit"), command=Thread(target=self.quit).start) self.btn_valid = Button(buttons, text=_("Sign In"), command=self.command_in_thread(self.login)) self.title.pack() self.sign_in.pack() self.form.pack() self.btn_quit.pack(side="left", padx=(0, 40)) self.btn_valid.pack(side="right", padx=(40, 0)) info.pack() buttons.pack(side="bottom") self.pack() self.update_needed = False def info(self, text): """dislay informations""" self.info_label.config(text=text) def save(self): """save the GEDCOM file""" filename = filedialog.asksaveasfilename( title=_("Save as"), defaultextension=".ged", filetypes=(("GEDCOM", ".ged"), (_("All files"), "*.*")), ) if not filename: return with open(filename, "w", encoding="utf-8") as file: self.tree.print(file) def login(self): """log in FamilySearch""" global _ username = self.sign_in.username.get() password = self.sign_in.password.get() if not (username and password): messagebox.showinfo(message=_( "Please enter your FamilySearch username and password.")) return self.btn_valid.config(state="disabled") self.info(_("Login to FamilySearch...")) self.logfile = open("download.log", "w", encoding="utf-8") self.fs = Session( self.sign_in.username.get(), self.sign_in.password.get(), verbose=True, logfile=self.logfile, timeout=1, ) if not self.fs.logged: messagebox.showinfo( _("Error"), message=_("The username or password was incorrect")) self.btn_valid.config(state="normal") self.info("") return self.tree = Tree(self.fs) _ = self.fs._ self.title.config(text=_("Options")) cache.delete("lang") cache.add("lang", self.fs.lang) cache.delete("username") cache.add("username", username) url = "/service/tree/tree-data/reservations/person/%s/ordinances" % self.fs.fid lds_account = self.fs.get_url(url, {}).get("status") == "OK" self.options = Options(self.form, lds_account) self.info("") self.sign_in.destroy() self.options.pack() self.master.change_lang() self.btn_valid.config( command=self.command_in_thread(self.download), state="normal", text=_("Download"), ) self.options.start_indis.add_indi(self.fs.fid) self.update_needed = False def quit(self): """prevent exception during download""" self.update_needed = False if self.logfile: self.logfile.close() super().quit() os._exit(1) def download(self): """download family tree""" todo = [ self.options.start_indis.indis[key] for key in sorted(self.options.start_indis.indis) ] for fid in todo: if not re.match(r"[A-Z0-9]{4}-[A-Z0-9]{3}", fid): messagebox.showinfo(_("Error"), message=_("Invalid FamilySearch ID: ") + fid) return self.start_time = time.time() self.options.destroy() self.form.destroy() self.title.config(text="FamilySearch to GEDCOM") self.btn_valid.config(state="disabled") self.info(_("Downloading starting individuals...")) self.info_tree = True self.tree.add_indis(todo) todo = set(todo) done = set() for i in range(self.options.ancestors.get()): if not todo: break done |= todo self.info( _("Downloading %s. of generations of ancestors...") % (i + 1)) todo = self.tree.add_parents(todo) - done todo = set(self.tree.indi.keys()) done = set() for i in range(self.options.descendants.get()): if not todo: break done |= todo self.info( _("Downloading %s. of generations of descendants...") % (i + 1)) todo = self.tree.add_children(todo) - done if self.options.spouses.get(): self.info(_("Downloading spouses and marriage information...")) todo = set(self.tree.indi.keys()) self.tree.add_spouses(todo) ordi = self.options.ordinances.get() cont = self.options.contributors.get() async def download_stuff(loop): futures = set() for fid, indi in self.tree.indi.items(): futures.add(loop.run_in_executor(None, indi.get_notes)) if ordi: futures.add( loop.run_in_executor(None, self.tree.add_ordinances, fid)) if cont: futures.add( loop.run_in_executor(None, indi.get_contributors)) for fam in self.tree.fam.values(): futures.add(loop.run_in_executor(None, fam.get_notes)) if cont: futures.add( loop.run_in_executor(None, fam.get_contributors)) for future in futures: await future loop = asyncio.get_event_loop() self.info( _("Downloading notes") + ((("," if cont else _(" and")) + _(" ordinances")) if ordi else "") + (_(" and contributors") if cont else "") + "...") loop.run_until_complete(download_stuff(loop)) self.tree.reset_num() self.btn_valid.config(command=self.save, state="normal", text=_("Save")) self.info(text=_("Success ! Click below to save your GEDCOM file")) self.update_info_tree() self.update_needed = False def command_in_thread(self, func): """command to update widget in a new Thread""" def res(): self.update_needed = True Thread(target=self.update_gui).start() Thread(target=func).start() return res def update_info_tree(self): """update informations""" if self.info_tree and self.start_time and self.tree: self.info_indis.config(text=_("Individuals: %s") % len(self.tree.indi)) self.info_fams.config(text=_("Families: %s") % len(self.tree.fam)) self.info_sources.config(text=_("Sources: %s") % len(self.tree.sources)) self.info_notes.config(text=_("Notes: %s") % len(self.tree.notes)) t = round(time.time() - self.start_time) minutes = t // 60 seconds = t % 60 self.time.config(text=_("Elapsed time: %s:%s") % (minutes, str(seconds).zfill(2))) def update_gui(self): """update widget""" while self.update_needed: self.update_info_tree() self.master.update() time.sleep(0.1)
def __init__(self, master): fr = Frame(master) master.title('Button Test') fr.grid(column=0, row=0, sticky=('nsew')) ## uncomment following 4 lines if you are running tkinter 8.5 # im1 = = Image.open('../images/butImage.png') ## # im2 = Image.open('../images/butImageTrans.png') ## # self.buttonPhoto = ImageTk.PhotoImage(im1) ## # buttonPhotoTrans = ImageTk.PhotoImage(im2) ## ## comment out following 2 lines if you are running tkinter 8.5 self.buttonPhoto = PhotoImage(file='../images/butImage.png') ## buttonPhotoTrans = PhotoImage(file='../images/butImageTrans.png') ## ''' we are using both a local and a variable prefixed with self ''' but = Button(master, image=self.buttonPhoto) #but.image = self.buttonPhoto - not needed because using self but.grid(column=0, row=0, sticky=('ew'), padx=10, pady=10) myButton = Button(master, compound='center', text='Click on Me!', style='new.TButton', image=buttonPhotoTrans) myButton.image = buttonPhotoTrans # keep a reference as local variable! myButton.grid(column=0, row=1, sticky=('ew'), padx=10, pady=10) myButton2 = Button(master, compound='center', text='Really long now - Click on Me!', style='new.TButton', image=buttonPhotoTrans) myButton2.image = buttonPhotoTrans # keep a reference as local variable! myButton2.grid(column=0, row=2, sticky=('ew'), padx=10, pady=10)
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