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) Pipelines=["InitialChIPseqQC", "ChIPseq" ] Pipeline = self.Pipeline = StringVar() Pipeline.set(Pipelines[0]) om = OptionMenu(eframe, Pipeline, *Pipelines, 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=20,pady=5) readtypes = ['Single', 'Paired'] self.readtype = readtype = StringVar() readtype.set(readtypes[0]) readtype_menu = OptionMenu(eframe, readtype, *readtypes) readtype_menu.grid(row=3, column=3, sticky=E, pady=5) readtype_label = Label(eframe, text="-end ") readtype_label.grid( row=3, column=4, stick=W, pady=5) self.add_info(eframe) self.option_controller() self.peakinfo_fn = 'peakcall.tab' self.contrast_fn = 'contrast.tab'
def initUI(self): self.parent.title("Pi computation") self.pack(fill=BOTH, expand=True) self.grid_columnconfigure(4, weight=1) self.grid_rowconfigure(3, weight=1) lbl1 = Label(self, text="Digits:") lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10) self.ent1 = Entry(self, width=10) self.ent1.insert(END, "4000") self.ent1.grid(row=0, column=1, sticky=W) lbl2 = Label(self, text="Accuracy:") lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10) self.ent2 = Entry(self, width=10) self.ent2.insert(END, "100") self.ent2.grid(row=0, column=3, sticky=W) self.startBtn = Button(self, text="Start", command=self.onStart) self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W) self.pbar = Progressbar(self, mode='indeterminate') self.pbar.grid(row=1, column=1, columnspan=3, sticky=W+E) self.txt = scrolledtext.ScrolledText(self) self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5, columnspan=5, sticky=E+W+S+N)
def _addNeueMahlzeitFrame(self): self.fr_neue_mz = Frame(self.fr_mahlzeit) self.fr_neue_mz.grid_rowconfigure(2, weight=1) self.fr_neue_mz.grid(row=0, column=1, sticky="WSNE") lbl_name = Label(self.fr_neue_mz, text="Name:") lbl_name.grid(row=0, column=0, sticky="NW") self.en_name = Entry(self.fr_neue_mz) self.en_name.grid(row=0, column=1, columnspan=2, sticky="WNE") lbl_zutat = Label(self.fr_neue_mz, text="Zutaten:") lbl_zutat.grid(row=1, column=0, sticky="NW") self.lb_zutat = Listbox(self.fr_neue_mz) sb_zutat = Scrollbar(self.lb_zutat, orient=VERTICAL) self.lb_zutat.configure(yscrollcommand=sb_zutat.set) sb_zutat.configure(command=self.lb_zutat.yview) sb_zutat.pack(side="right", fill="both") self.lb_zutat.grid(row=2, column=0, columnspan=3, sticky="NWSE") self.var_zutat = StringVar(self.fr_neue_mz) self.opt_zutat = OptionMenu(self.fr_neue_mz, self.var_zutat, "Auswahl") self.opt_zutat.grid(row=3, column=0) self.en_menge = Entry(self.fr_neue_mz) self.en_menge.grid(row=3, column=1) self.btn_mahlzeit_hinzu = Button(self.fr_neue_mz, text="Hinzu") self.btn_mahlzeit_hinzu.grid(row=3, column=2, sticky="E")
def __init__(self, parent, title, imageFile, body): super(DialogAbout, self).__init__(parent) self.parent = parent parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.transient(self.parent) self.title(title) frame = Frame(self) image = PhotoImage(file=imageFile) aboutImage = Label(frame, image=image) aboutBody = Label(frame, text=body, wraplength=500) okButton = Button(frame, text=_("OK"), command=self.ok) okButton.focus_set() aboutImage.grid(row=0, column=0, sticky=NW, pady=20, padx=16) aboutBody.grid(row=0, column=1, columnspan=2, sticky=EW, pady=3, padx=0) okButton.grid(row=1, column=2, sticky=EW, pady=3) frame.grid(row=0, column=0, sticky=(N,S,E,W)) frame.columnconfigure(1, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) self.geometry("+{0}+{1}".format(dialogX+200,dialogY+200)) self.bind("<Alt-u>", lambda *ignore: okButton.focus_set()) self.bind("<Return>", self.ok) self.bind("<Escape>", self.close) self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self)
def __init__(self, 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 __init__(self, pipepanel, pipeline_name, *args, **kwargs) : PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs) self.pairs = 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 = ['Initial QC', 'Germline', 'Somatic Tumor-Normal', 'Somatic Tumor-Only'] Pipelines=["initialqcgenomeseq", "wgslow", 'wgs-somatic', 'wgs-somatic-tumoronly'] self.label2pipeline = { k:v for k,v in zip(PipelineLabels, Pipelines)} PipelineLabel = self.PipelineLabel = StringVar() Pipeline = self.Pipeline = StringVar() PipelineLabel.set(PipelineLabels[0]) #om = OptionMenu(eframe, Pipeline, *Pipelines, command=self.option_controller) 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)
def __init__(self, master, ordinances=False, **kwargs): super(Options, self).__init__(master, **kwargs) self.ancestors = IntVar() self.ancestors.set(4) self.descendants = IntVar() self.spouses = IntVar() self.ordinances = IntVar() self.contributors = IntVar() self.start_indis = StartIndis(self) self.fid = StringVar() btn = Frame(self) entry_fid = EntryWithMenu(btn, textvariable=self.fid, width=16) entry_fid.bind('<Key>', self.enter) label_ancestors = Label(self, text=_('Number of generations to ascend')) entry_ancestors = EntryWithMenu(self, textvariable=self.ancestors, width=5) label_descendants = Label(self, text=_('Number of generations to descend')) entry_descendants = EntryWithMenu(self, textvariable=self.descendants, width=5) btn_add_indi = Button(btn, text=_('Add a FamilySearch ID'), command=self.add_indi) btn_spouses = Checkbutton(self, text='\t' + _('Add spouses and couples information'), variable=self.spouses) btn_ordinances = Checkbutton(self, text='\t' + _('Add Temple information'), variable=self.ordinances) btn_contributors = Checkbutton(self, text='\t' + _('Add list of contributors in notes'), variable=self.contributors) self.start_indis.grid(row=0, column=0, columnspan=3) entry_fid.grid(row=0, column=0, sticky='w') btn_add_indi.grid(row=0, column=1, sticky='w') btn.grid(row=1, column=0, columnspan=2, sticky='w') entry_ancestors.grid(row=2, column=0, sticky='w') label_ancestors.grid(row=2, column=1, sticky='w') entry_descendants.grid(row=3, column=0, sticky='w') label_descendants.grid(row=3, column=1, sticky='w') btn_spouses.grid(row=4, column=0, columnspan=2, sticky='w') if ordinances: btn_ordinances.grid(row=5, column=0, columnspan=3, sticky='w') btn_contributors.grid(row=6, column=0, columnspan=3, sticky='w') entry_ancestors.focus_set()
def initUI(self): self.parent.title("Windows") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(6, weight=1) self.rowconfigure(5, pad=7) lbl = Label(self, text="BookManager") lbl.grid(sticky=W, pady=4, padx=5) self.area = Text(self) #WHITE TEXT BOX self.area.grid(row=1, column=0, columnspan=3, rowspan=4, padx=5, sticky=E+W+S+N) abtn = Button(self, text="add", command=self.press_add) abtn.grid(row=1, column=3) srcbtn = Button(self, text="search", command=self.press_search) srcbtn.grid(row=2, column=3, pady=3) rbtn = Button(self, text="remove", command=self.press_remove) rbtn.grid(row=3, column=3, pady=3) sbtn = Button(self, text="show all", command=self.press_show) sbtn.grid(row=4, column=3, pady=3)
def create_widgets(self): ''' Creates widgets of this object. ''' yScrollbar = Scrollbar(self, orient=VERTICAL) yScrollbar.grid(row=2, column=3, sticky=N+S) canvas = StyledCanvas(self, height=HEIGHT_WITHOUT_CHECKBOXES, yscrollcommand=yScrollbar.set) self.canvas = canvas canvas.grid(row=2, column=0, columnspan=3, sticky=N+E+W) self._config_columns(self) canvas.columnconfigure(0, weight=1) if self.add_headers: non_discr_lbl = Label(self, text='Non-\ndiscretionary') non_discr_lbl.grid(row=0, column=1, padx=3, pady=1) weakly_disp_lbl = Label(self, text='Weakly\ndisposable') weakly_disp_lbl.grid(row=0, column=2, padx=3, pady=1) sep = Separator(self) sep.grid(row=1, column=0, columnspan=3, sticky=E+W, pady=10, padx=3) self.frame_with_boxes = Frame(canvas) self._config_columns(self.frame_with_boxes) self.frame_with_boxes.grid(sticky=N+S+W+E, pady=15, padx=3) canvas.create_window(0, 0, window=self.frame_with_boxes, anchor=N+W) canvas.update_idletasks() canvas['scrollregion'] = (0, 0, 0, HEIGHT_WITHOUT_CHECKBOXES) yScrollbar['command'] = canvas.yview MouseWheel(self).add_scrolling(canvas, yscrollbar=yScrollbar)
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()
def initUI(self): self.parent.title("Windows") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(3, weight=1) self.rowconfigure(5, pad=7) lbl = Label(self, text="Windows") lbl.grid(sticky=W, pady=4, padx=5) area = Text(self) area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N) abtn = Button(self, text="Activate") abtn.grid(row=1, column=3) cbtn = Button(self, text="Close") cbtn.grid(row=2, column=3, pady=4) hbtn = Button(self, text="Help") hbtn.grid(row=5, column=0, padx=5) obtn = Button(self, text="OK") obtn.grid(row=5, column=3)
def 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 __init__(self, parent, url=None, buttonSEC=False, buttonRSS=False): super(DialogURL, self).__init__(parent) self.parent = parent parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.accepted = False self.url = None self.transient(self.parent) self.title("Enter URL") self.urlVar = StringVar() self.urlVar.set(url if url is not None else "http://") frame = Frame(self) urlLabel = Label(frame, text=_("URL:"), underline=0) urlEntry = Entry(frame, textvariable=self.urlVar, width=60) urlEntry.focus_set() okButton = Button(frame, text=_("OK"), command=self.ok) cancelButton = Button(frame, text=_("Cancel"), command=self.close) if buttonSEC: usSecButton = Button(frame, text=_("SEC search"), command=self.usSec) usSecButton.grid(row=1, column=1, sticky=W, pady=3) ToolTip(usSecButton, text=_("Opens US SEC Edgar Company Search (in web browser)\n\n" "(1) Find the company in web browser,\n" "(2) Click 'documents' button for desired filing,\n" "(3) Find 'data files' panel, instance document row, 'document' column,\n" "(4) On instance document file name, right-click browser menu: 'copy shortcut',\n" "(5) Come back to this dialog window,\n" "(6) Ctrl-v (paste) shortcut into above URL text box,\n" "(7) Click ok button to load instance document"), wraplength=480) if buttonRSS: rssButton = Button(frame, text=_("SEC RSS"), command=self.rssFeed) rssButton.grid(row=1, column=1, pady=3) ToolTip(rssButton, text=_("Opens current US SEC Edgar RSS feed"), wraplength=480) urlLabel.grid(row=0, column=0, sticky=W, pady=3, padx=3) urlEntry.grid(row=0, column=1, columnspan=3, sticky=EW, pady=3, padx=3) okButton.grid(row=1, column=2, sticky=E, pady=3) ToolTip(okButton, text=_("Opens above URL from web cache, downloading to cache if necessary"), wraplength=240) cancelButton.grid(row=1, column=3, sticky=EW, pady=3, padx=3) ToolTip(cancelButton, text=_("Cancel operation")) frame.grid(row=0, column=0, sticky=(N,S,E,W)) frame.columnconfigure(1, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100)) self.bind("<Alt-u>", lambda *ignore: urlEntry.focus_set()) self.bind("<Return>", self.ok) self.bind("<Escape>", self.close) self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self)
class ConfirmFrame(MessageFrame): def __init__(self, master, config): super(ConfirmFrame, self).__init__(master, config) if config.full_screen: self._make_full(master) self.master.grid_rowconfigure(0, weight=1) self.master.grid_rowconfigure(1, weight=1) self.master.grid_columnconfigure(0, weight=1) self.master.grid_columnconfigure(1, weight=1) self._result = False self._frame_lbl = Label( self.master, text='', anchor='center', font=self._config.item_font ) self._frame_lbl.grid(row=0, column=0, columnspan=2, sticky='snew') self._prev_btn = Button( self.master, text='Cancel', command=self._prev_cmd ) self._prev_btn.grid(row=1, column=0, sticky='snew') self._next_btn = Button( self.master, text='OK', command=self._next_cmd ) self._next_btn.grid(row=1, column=1, sticky='snew') def show(master, config, msg, ok_text, cancel_text): new_window = Toplevel(master) dlg = ConfirmFrame(new_window, config) dlg._frame_lbl['text'] = msg dlg._prev_btn['text'] = cancel_text dlg._next_btn['text'] = ok_text dlg.wait_window(new_window) return dlg._result def _prev_cmd(self): self._result = False self._master.destroy() def _next_cmd(self): self._result = True self._master.destroy()
def make_entry(self, label_text, var): '''Return (entry, label), . entry - gridded labeled Entry for text entry. label - Label widget, returned for testing. ''' label = Label(self.top, text=label_text) label.grid(row=self.row, column=0, sticky="nw") entry = Entry(self.top, textvariable=var, exportselection=0) entry.grid(row=self.row, column=1, sticky="nwe") self.row = self.row + 1 return entry, label
def add_field(self, widget, multiline=False, **kw): label_sticky = [tkinter.EW] widget_sticky = [tkinter.EW] if multiline: label_sticky.append(tkinter.N) widget_sticky.append(tkinter.NS) label = Label(self.master, **kw) label.grid(column=self.column + 0, sticky=label_sticky) row = grid_row(label) if multiline: self.master.rowconfigure(row, weight=1) widget.grid(row=row, column=self.column + 1, sticky=widget_sticky)
class CopilotInnerFrame(CopilotBaseFrame): def __init__(self, master, config): super(CopilotInnerFrame, self).__init__(master, config) if config.full_screen: self._make_full(master) self.master.grid_rowconfigure(1, weight=1) self.master.grid_columnconfigure(1, weight=1) self._create_header() self._sb = Scrollbar(self._master, orient=VERTICAL) self._sb.grid(row=1, column=3, sticky='nse') self._next_hidden = False def _cmd_back(self): self._master.destroy() def _create_header(self): self.back_btn = Button( self._master, text='< Back', command=self._cmd_back ) self.back_btn.grid(row=0, column=0, sticky='w') self._frame_lbl = Label( self.master, text='', anchor='center', font=self._config.item_font ) self._frame_lbl.grid(row=0, column=1, sticky='ew') self._next_btn = Button( self.master, text='Next >' ) self._next_btn.grid(row=0, column=2, sticky='e') def _hide_next(self): if not self._next_hidden: self._next_btn.grid_remove() self._next_hidden = True def _show_next(self): if self._next_hidden: self._next_btn.grid(row=0, column=2, sticky='e') self._next_hidden = False
def init_ui(self): self.parent.title("Papers") self.style = Style() self.style.theme_use("clam") frame = Frame(self, relief=RAISED, borderwidth=1) frame.grid(row=0, column=0) label = Label(frame, text="Change Wallpaper") label.grid(row=0, column=0) button = Button(frame, text="Change", command=self.change) button.grid(row=1, column=0) label = Label(frame, text="Fetch Wallpapers") label.grid(row=2, column=0) button = Button(frame, text="Fetch", command=self.fetch) button.grid(row=3, column=0)
def create_status_bar(self, master): statbar = Frame(master, padding = '3 3 3 3') statbar.grid(column=0, row=2, sticky=(EW, S)) Label(statbar, text='RDFS File:', padding='0 3 0 3').grid(row=0, column=0, sticky=SE) rdfsFileNameLbl = Label(statbar, textvariable=self.rdfsFileName, background='#bbb', relief=SUNKEN, padding='3 3 3 3') rdfsFileNameLbl.grid(column=1, row=0, sticky=(EW)) Label(statbar, text='Template file:', padding='0 3 0 3').grid(row=1, column=0, sticky=SE) templateFileNameLbl = Label(statbar, textvariable=self.templateFileName, background='#bbb', relief=SUNKEN, padding='3 3 3 3') templateFileNameLbl.grid(column=1, row=1, sticky=(EW)) statbar.columnconfigure(1, weight=1) for child in statbar.winfo_children(): child.grid_configure(padx=3, pady=3)
def average_normals( self ): """ Applies Gouraud normalization to the module """ # Set up updater top = Toplevel() pb = Progressbar(top,orient ="horizontal",length = 200, mode ="determinate") pb['maximum'] = len(self.__elements__) pb['value'] = 10 pb.grid(row=0,column=0) tx = Label(top) tx.grid(row=1,column=0) top.update_idletasks() top.lift() t0 = time.time() # run the loop, if we're visible and phong shading if not self.invisible == 'gouroud': try: buf = np.array([0,0,0,1]) for i,polygon in enumerate(self.__elements__): if not ispoly(polygon): continue polygon._onorms = np.array([polygon.normals.astype(float)+buf for i in range(len(polygon.coordinates))]) # Update the user as to what's going on if i % 50 == 0 and i > 0: pb['value'] = i tmp = i/len(self.__elements__) estimation = int(tmp*(time.time()-t0) * (1-tmp)/tmp) tx.configure(text=str(int(100*i/len(self.__elements__)))+"%"+' Estimated time: '+str(estimation)+'s' ) top.update_idletasks() for c,coordinate in enumerate(polygon.coordinates): for j,opolygon in enumerate(self.__elements__): if i == j or not ispoly(opolygon): continue for k,ocoordinate in enumerate(opolygon.coordinates): if all(coordinate == ocoordinate): # same vertex, finally polygon._onorms[c] += (opolygon.normals+buf) polygon._onorms /= polygon._onorms[:,3,None] for polygon in self.__elements__: if ispoly(polygon): polygon.normals = polygon._onorms del polygon._onorms except IndexError as ie: pass top.destroy() if self.invisible == 'gouroud': self.invisible = False return self # for chaining
def __init__(self, master, **kwargs): super(SignIn, self).__init__(master, **kwargs) self.username = StringVar() self.password = StringVar() label_username = Label(self, text=_('Username:'******'Password:'******'●', textvariable=self.password, width=30) label_username.grid(row=0, column=0, pady=15, padx=(0, 5)) entry_username.grid(row=0, column=1) label_password.grid(row=1, column=0, padx=(0, 5)) entry_password.grid(row=1, column=1) entry_username.focus_set() entry_username.bind('<Key>', self.enter) entry_password.bind('<Key>', self.enter)
def make_frame(self,labeltext=None): '''Return (frame, label). frame - gridded labeled Frame for option or other buttons. label - Label widget, returned for testing. ''' if labeltext: label = Label(self.top, text=labeltext) label.grid(row=self.row, column=0, sticky="nw") else: label = '' frame = Frame(self.top) frame.grid(row=self.row, column=1, columnspan=1, sticky="nwe") self.row = self.row + 1 return frame, label
def __make_widgets(self): widgets = {} for index, editor_field in enumerate(self.editor_fields): label = Label(self, width=50, padding=5, text=editor_field.title()) combo = Combobox(self, width=100) widgets[editor_field] = {} widgets[editor_field]['label'] = label widgets[editor_field]['widget'] = combo label.grid(row=index, column=0) combo.grid(row=index, column=1) index += 1 label = Label(self, width=50, padding=5, text="Pictures") button = Button(self, text="...", command=self.__load_pictures) label.grid(row=index, column=0) button.grid(row=index, column=1) return widgets
def create_rdfs_frame(self, master:Notebook): rdfsframe = Frame(master, padding = '3 3 3 3', width=600, height=400) Label(rdfsframe, text='RDFS Name:', padding='3 3 3 3').grid(row=0, column=0, padx=3, pady=3) rdfsNameLbl = Label(rdfsframe, textvariable=self.rdfsName, background='#bbb', relief=SUNKEN, padding='3 0 3 3') rdfsNameLbl.grid(row=0, column=1, columnspan=3, sticky=EW, padx=3, pady=6) self.classtree.heading(column='#0', text='ClassTree') ysb = Scrollbar(rdfsframe, orient='vertical', command=self.classtree.yview) xsb = Scrollbar(rdfsframe, orient='horizontal', command=self.classtree.xview) self.classtree.configure(yscrollcommand=ysb.set) self.classtree.configure(xscrollcommand=xsb.set) self.classtree.bind('<<TreeviewSelect>>', self.update_classinfo) self.classtree.grid(row=1, column=0, columnspan=2, in_=rdfsframe, sticky=NSEW) self.classtree.lift(rdfsframe) self.classtree.tag_configure('include', foreground='black') self.classtree.tag_configure('notinclude', foreground='gray') ysb.grid(row=1, column=2, sticky=(NS)) xsb.grid(row=2, column=0, columnspan=2, sticky=(EW)) classinfoframe = Frame(rdfsframe, width=300, height=400) classinfoframe.grid(row=1, column=3, padx=3, pady=3, sticky=(NSEW)) Label(classinfoframe, text='Class Name:', font='bold', padding='3 3 3 3').grid(row=1, column=0, sticky=NW) classNameLbl = Label(classinfoframe, textvariable=self.className, background='#bbb', relief=SUNKEN, padding='3 3 3 3', font='bold', width=25) classNameLbl.grid(row=1, column=1, sticky=EW) Label(classinfoframe, text='Description:', font='bold', padding='3 3 3 3').grid(row=2, column=0, sticky=NW) self.classDescrTxt.grid(row=2, column=1, in_=classinfoframe, sticky=EW) self.classDescrTxt.lift(classinfoframe) include_chk = Checkbutton(classinfoframe, text='include this class', variable=self.includeclass, command=self.include_class) include_chk.grid(row=3, column=1, sticky=E) Label(classinfoframe, text='Properties:', font='bold', padding='3 3 3 3').grid(row=5, column=0, sticky=NW) self.propertiesframe.grid(in_ = classinfoframe, row=5, column=1, sticky=(N+E+S+W)) self.propertiesframe.lift(classinfoframe) classinfoframe.rowconfigure(5, weight=1) classinfoframe.columnconfigure(1, weight=1) rdfsframe.columnconfigure(1, weight=1) rdfsframe.columnconfigure(3, weight=3) rdfsframe.rowconfigure(1, weight=1) master.add(rdfsframe, text='RDFS')
def createRow(self,rowNumber): isopach_L = Label(self.innerFrame, text=str(rowNumber+1), width=2) isopach_L.grid(column=0, row=rowNumber+2, padx=(0,5), pady=5) thicknessVar = tkinter.StringVar() thicknessM_E = Entry(self.innerFrame,width=self.entryWidth,textvariable=thicknessVar, justify="right") thicknessM_E.grid(column=1, row=rowNumber+2, pady=5) areaVar = tkinter.StringVar() sqrtAreaKM_E = Entry(self.innerFrame,width=self.entryWidth,textvariable=areaVar, justify="right") sqrtAreaKM_E.grid(column=2, row=rowNumber+2, pady=5) includeVar = tkinter.IntVar() includeCB = tkinter.Checkbutton(self.innerFrame,variable=includeVar, selectimage=self.tickImage) includeCB.grid(column=3,row=rowNumber+2,pady=5) includeCB.invoke() includeCB.bind("<Leave>",self.calculationTimeEstimationFunction) return (isopach_L,None),(thicknessM_E,thicknessVar),(sqrtAreaKM_E,areaVar),(includeCB,includeVar)
def __init__(self, pipepanel, pipeline_name, *args, **kwargs) : PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs) self.pairs = 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) Pipelines=["initialqcgenomeseq","wgslow"] Pipeline = self.Pipeline = StringVar() Pipeline.set(Pipelines[0]) om = OptionMenu(eframe, Pipeline, *Pipelines, 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)
def create_widgets(self): super().create_widgets() frame = self.frame pathlabel = Label(frame, anchor='w', justify='left', text='Help File Path: Enter URL or browse for file') self.pathvar = StringVar(self, self.filepath) self.path = Entry(frame, textvariable=self.pathvar, width=40) browse = Button(frame, text='Browse', width=8, command=self.browse_file) self.path_error = Label(frame, text=' ', foreground='red', font=self.error_font) pathlabel.grid(column=0, row=10, columnspan=3, padx=5, pady=[10,0], sticky=W) self.path.grid(column=0, row=11, columnspan=2, padx=5, sticky=W+E, pady=[10,0]) browse.grid(column=2, row=11, padx=5, sticky=W+S) self.path_error.grid(column=0, row=12, columnspan=3, padx=5, sticky=W+E)
def add_category(self, category_name): ''' Adds a given category to this object. If the given category already exists, it won't be added again. Category names are assumed to be unique. Args: category_name (str): name of the category to add. ''' if category_name not in self.category_objects.keys(): categories = self.params.get_set_of_parameters(self.category_type) if category_name not in categories: categories.add(category_name) self.params.update_parameter(self.category_type, ';'.join(categories)) self.nb_entries += 1 row_index = self.nb_entries self.options[category_name] = [IntVar(), IntVar(), row_index] box = Label(self.frame_with_boxes, text=category_name, justify=LEFT, wraplength=MIN_COLUMN_WIDTH_NAME - 10) box.grid(row=row_index, column=0, sticky=W, padx=7, pady=5) btn = [] for count in range(2): check_btn = Checkbutton(self.frame_with_boxes, variable= self.options[category_name][count]) check_btn.config(command=(lambda count=count: self.on_select_box(box, count))) btn.append(check_btn) btn[count].grid(row=row_index, column=count + 1, pady=5) self.category_objects[category_name] = (box, btn[0], btn[1]) nd_categories = self.params.get_set_of_parameters( 'NON_DISCRETIONARY_CATEGORIES') if category_name in nd_categories: btn[0].invoke() wd_categories = self.params.get_set_of_parameters( 'WEAKLY_DISPOSAL_CATEGORIES') if category_name in wd_categories: btn[1].invoke() self.update_scroll_region()
class Progression(Frame): """Class to display the progress in filling the puzzle.""" def __init__(self, master, number, **kwargs): kwargs.setdefault('width', 34) kwargs.setdefault('height', 34) kwargs.setdefault('style', 'case.TFrame') Frame.__init__(self, master, **kwargs) self.grid_propagate(False) self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.number = number self._nb = 0 self.label_number = Label(self, style='case.TLabel', text=str(number), font='Arial 16') self.label_nb = Label(self, style='case.TLabel', text='0', font='Arial 9') self.label_number.grid(row=0, column=0, sticky='e', padx=0) self.label_nb.grid(row=0, column=1, sticky='n') @property def nb(self): return self._nb @nb.setter def nb(self, value): self._nb = value self.label_nb.configure(text=str(self._nb)) if self._nb < 9: self.configure(style='case.TFrame') self.label_number.configure(style='case.TLabel') self.label_nb.configure(style='case.TLabel') elif self._nb == 9: self.configure(style='case_init.TFrame') self.label_number.configure(style='case_init.TLabel') self.label_nb.configure(style='case_init.TLabel') else: self.configure(style='erreur.TFrame') self.label_number.configure(style='erreur.TLabel') self.label_nb.configure(style='erreur.TLabel')
def show_about(self): about = Toplevel(self.master) about.title('About {}'.format(self.version[:-5])) about.focus() about.resizable(0, 0) logo_lbl = Label(about, image=self.logo) logo_lbl.image = self.logo logo_lbl.grid(row=0, column=0, padx='7 11', pady=13, sticky='n') about_frame = Frame(about, padding='0 10 10 10') about_frame.grid(row=0, column=1) Label(about_frame, text=self.version).grid(sticky='w') Label(about_frame, text='Developer: Joel W. Dafoe').grid(pady='6', sticky='w') link = Link(about_frame, text='http://cyberdatx.com', foreground='blue', cursor='hand2') link.grid(sticky='w') link.bind('<Button-1>', lambda e: webbrowser.open('http://cyberdatx.com')) Label(about_frame, text=self.description, wraplength=292).grid(columnspan=2, pady=6, sticky='w') cls_btn = Button(about_frame, text='OK', command=about.destroy) cls_btn.grid(column=1, sticky='e') cls_btn.focus() about.bind('<Return>', lambda e: cls_btn.invoke())
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("") self.style = Style() self.style.theme_use("clam") self.pack(fill=BOTH, expand=1) self.labelU = Label(self, text="U:") self.labelP = Label(self, text="P:") self.entryUsername = Entry(self) self.entryUsername.config(relief='flat') self.entryUsername.focus_set() self.entryUsername.bind('<Return>', lambda event: self.entryPassword.focus_set()) self.entryPassword = Entry(self) self.entryPassword.config(relief='flat', show='•') self.entryPassword.bind( '<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton = Button( self, text="Login", command=lambda: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton.bind( '<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton.config(width=6) self.quitbutton = Button(self, text="Quit", command=lambda: self.quit()) self.quitbutton.config(width=6) self.mailIconRed = PhotoImage(file="mail.gif") self.labelRed = Label(self, image=self.mailIconRed) self.mailIconGray = PhotoImage(file="mail2.gif") self.labelGray = Label(self, image=self.mailIconGray) self.labelKarma = Label(self, text='•') self.labelU.grid(row=0, column=0) self.entryUsername.grid(row=0, column=1) self.labelP.grid(row=1, column=0) self.entryPassword.grid(row=1, column=1, pady=4) self.newbutton.grid(row=2, column=1) self.quitbutton.grid(row=3, column=1, pady=4) ''' sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() w=150 h=112 x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y-50)) ''' def login(self, username, password): #print('U: ' + username) self.username = username if username == '': #print('Please enter a username') self.entryUsername.focus_set() elif password == '': #print('Please enter a password') self.entryPassword.set_focus() if username != '' and password != '': #print('Attempting login for ' + username) try: self.USERAGENT = username + ' scans his inbox for new mail.' self.r = praw.Reddit(self.USERAGENT) #self.r.config._ssl_url = None self.r.login(username, password) #print('You have logged in as ' + username) self.labelU.grid_forget() self.labelP.grid_forget() self.entryUsername.grid_forget() self.entryPassword.grid_forget() self.newbutton.grid_forget() self.quitbutton.grid_forget() self.usernamelabel = Label(self, text=username) self.usernamelabel.grid(row=0, column=0, pady=10, padx=30) self.quitbutton.grid(row=1, column=0) self.labelKarma.grid(row=3, column=0) self.playedSound = 'false' self.loop() except praw.errors.InvalidUserPass: pass #print('Invalid username or password') def loop(self): while True: try: #print('Starting new search') hasmail = 'false' for msg in self.r.get_unread(limit=None): hasmail = 'true' if hasmail == 'true': #print("You've got mail!") if self.playedSound == 'false': winsound.PlaySound('pop.wav', winsound.SND_FILENAME) self.playedSound = 'true' self.labelGray.grid_forget() self.labelRed.grid(row=2, column=0) if hasmail == 'false': self.playedSound = 'false' #print('No mail!') self.labelRed.grid_forget() self.labelGray.grid(row=2, column=0) self.user = self.r.get_redditor(self.username) lkarma = str(self.user.link_karma) ckarma = str(self.user.comment_karma) lkarma = self.karmaRound(lkarma) ckarma = self.karmaRound(ckarma) karmastring = lkarma + ' • ' + ckarma self.labelKarma.config(text=karmastring) time.sleep(10) except Exception: time.sleep(10) def karmaRound(self, karma): if len(karma) > 4 and len(karma) < 7: tstring = karma[:-3] tstring2 = karma[-3:] karma = tstring + '.' + tstring2[:2] + 'K' return karma if len(karma) > 6: tstring = karma[:-6] tstring2 = karma[-6:] karma = tstring + '.' + tstring2[:2] + 'M' return karma else: return karma
class Query(Toplevel): """Base class for getting verified answer from a user. For this base class, accept any non-blank string. """ def __init__(self, parent, title, message, *, text0='', used_names={}, _htest=False, _utest=False): """Create modal popup, return when destroyed. Additional subclass init must be done before this unless _utest=True is passed to suppress wait_window(). title - string, title of popup dialog message - string, informational message to display text0 - initial value for entry used_names - names already in use _htest - bool, change box location when running htest _utest - bool, leave window hidden and not modal """ self.parent = parent # Needed for Font call. self.message = message self.text0 = text0 self.used_names = used_names Toplevel.__init__(self, parent) self.withdraw() # Hide while configuring, especially geometry. self.title(title) self.transient(parent) if not _utest: # Otherwise fail when directly run unittest. self.grab_set() _setup_dialog(self) if self._windowingsystem == 'aqua': self.bind("<Command-.>", self.cancel) self.bind('<Key-Escape>', self.cancel) self.protocol("WM_DELETE_WINDOW", self.cancel) self.bind('<Key-Return>', self.ok) self.bind("<KP_Enter>", self.ok) self.create_widgets() self.update_idletasks() # Need here for winfo_reqwidth below. self.geometry( # Center dialog over parent (or below htest box). "+%d+%d" % (parent.winfo_rootx() + (parent.winfo_width() / 2 - self.winfo_reqwidth() / 2), parent.winfo_rooty() + ((parent.winfo_height() / 2 - self.winfo_reqheight() / 2) if not _htest else 150))) self.resizable(height=False, width=False) if not _utest: self.deiconify() # Unhide now that geometry set. self.entry.focus_set() self.wait_window() def create_widgets(self, ok_text='OK'): # Do not replace. """Create entry (rows, extras, buttons. Entry stuff on rows 0-2, spanning cols 0-2. Buttons on row 99, cols 1, 2. """ # Bind to self the widgets needed for entry_ok or unittest. self.frame = frame = Frame(self, padding=10) frame.grid(column=0, row=0, sticky='news') frame.grid_columnconfigure(0, weight=1) entrylabel = Label(frame, anchor='w', justify='left', text=self.message) self.entryvar = StringVar(self, self.text0) self.entry = Entry(frame, width=30, textvariable=self.entryvar) self.error_font = Font(name='TkCaptionFont', exists=True, root=self.parent) self.entry_error = Label(frame, text=' ', foreground='red', font=self.error_font) # Display or blank error by setting ['text'] =. entrylabel.grid(column=0, row=0, columnspan=3, padx=5, sticky=W) self.entry.grid(column=0, row=1, columnspan=3, padx=5, sticky=W + E, pady=[10, 0]) self.entry_error.grid(column=0, row=2, columnspan=3, padx=5, sticky=W + E) self.create_extra() self.button_ok = Button(frame, text=ok_text, default='active', command=self.ok) self.button_cancel = Button(frame, text='Cancel', command=self.cancel) self.button_ok.grid(column=1, row=99, padx=5) self.button_cancel.grid(column=2, row=99, padx=5) def create_extra(self): pass # Override to add widgets. def showerror(self, message, widget=None): #self.bell(displayof=self) (widget or self.entry_error)['text'] = 'ERROR: ' + message def entry_ok(self): # Example: usually replace. "Return non-blank entry or None." entry = self.entry.get().strip() if not entry: self.showerror('blank line.') return None return entry def ok(self, event=None): # Do not replace. '''If entry is valid, bind it to 'result' and destroy tk widget. Otherwise leave dialog open for user to correct entry or cancel. ''' self.entry_error['text'] = '' entry = self.entry_ok() if entry is not None: self.result = entry self.destroy() else: # [Ok] moves focus. (<Return> does not.) Move it back. self.entry.focus_set() def cancel(self, event=None): # Do not replace. "Set dialog result to None and destroy tk widget." self.result = None self.destroy() def destroy(self): self.grab_release() super().destroy()
highlightcolor='blue', yscrollcommand=scroll.set, fg='white', width=30, height=25, font='lucida 12 italic', borderwidth=5, relief=RAISED, highlightbackground='#6394C8') #selectbackground='blue', songbox.pack(fill=Y, ipady=40) scroll.config(command=songbox.yview) #---------------listbox ------------------ #button container back_label = Label(fm2, text='', font='lucida 10 italic') back_label.grid(row=0, column=4, ipady=8) back_btn = Button(fm2, text='<<', font='lucida 10 bold', bd=5, relief=RAISED, command=back_song) back_btn.grid(row=1, column=4, padx=10) play_label = Label(fm2, text='', font='lucida 10 italic') play_label.grid(row=0, column=5, ipady=8) play_btn = Button(fm2, text='play', font='lucida 10 bold', bd=5, relief=RAISED,
class Example(Frame): # This is the URL to the defualt icon that will appear before any item is selected. defaultIconURL = "https://support.runescape.com/hc/article_attachments/360002434025/App_Icon-Circle.png" def __init__(self): super().__init__() self.initUI() def initUI(self): # Set the window title. self.master.title("OSRS Item Lookup") # Call the methods to center the window on screen & create grid within frame self.centerWindow() self.makeGrid() # Create all of the Label & Entry widgets contained within the frame self.nameLabel = Label(self, text="Name: ") self.name = Entry(self) self.descLabel = Label(self, text="Description: ") self.description = Entry(self) self.priceLabel = Label(self, text="Price: ") self.price = Entry(self) self.idLabel = Label(self, text="Item ID: ") self.itemID = Entry(self) # Setting the default icon image self.iconImg = self.getImage(self.defaultIconURL) self.icon = Label(self, image=self.iconImg) self.icon.image = self.iconImg # Creating the Button to fetch data via API. self.getData = Button(self, text="Get Data", command=lambda: self.getItem(self.itemID.get())) # Creating the frame that will contain MatPlotLib fig self.plotFrame = Frame(self) # Placing all of the widgets within the grid self.nameLabel.grid(row=0, columnspan=1, sticky='nsew') self.name.grid(row=0, column=1, columnspan=14, sticky='nsew') self.descLabel.grid(row=1, columnspan=1, sticky='nsew') self.description.grid(row=1, column=1, columnspan=14, sticky='nsew') self.icon.grid(row=0, column=15, rowspan=3, columnspan=5) self.priceLabel.grid(row=2, columnspan=1, sticky='nsew') self.price.grid(row=2, column=1, columnspan=14, sticky='nsew') self.idLabel.grid(row=19, columnspan=1, sticky='nsew') self.itemID.grid(row=19, column=1, columnspan=9, sticky='nsew') self.getData.grid(row=19, column=10, columnspan=10, sticky='nsew') self.plotFrame.grid(row=3, rowspan=16, columnspan=20, sticky='nsew') # Set the frame to expand and fill as the window is resized. self.pack(fill=BOTH, expand=1) # This method will create a plot based on data fed in as a dictionary. def plot(self, data): # Destory all the children in the plotFrame widget, this allows for the # plot to update whenver a new item is selected. for widget in self.plotFrame.winfo_children(): widget.destroy() # Place X & Y values into their own respective lists x = list(data.keys()) y = list(data.values()) # This is the starting day for the time data recieved from the server. # The time values in the server are represented as milliseconds from Jan. # 1, 1970. The following converts all of those times in milliseconds to a datetime. day = datetime.date(1970, 1, 1) x[:] = [ day + timedelta(days=(int(item) / ((1000 * 60 * 60 * 24)))) for item in x ] # Create and size the figure to the plotframe size. f = Figure(figsize=(self.plotFrame.winfo_width() / 100, self.plotFrame.winfo_height() / 100), dpi=100) # Add 1 subplot on a 1 x 1 grid. a = f.add_subplot(111) # Format x_axis date f.autofmt_xdate() # Plot date and price values a.plot(x, y) # Create canvas for figure to reside on, set parent to plot frame, then # Draw the canvas and pack it in plotFrame. self.canvas = FigureCanvasTkAgg(f, self.plotFrame) self.canvas.draw() self.canvas.get_tk_widget().pack(fill=BOTH, expand=1) # This method interfaces with the OSRS API and retrieves data, updates data # in GUI. def getItem(self, itemIDNum): # Create new instance of Item with provided ID number. newItem = osrs_api.Item(itemIDNum) # Clear out the entry widgets if anything is any them. self.name.delete(0, END) self.description.delete(0, END) self.price.delete(0, END) # Insert the name, description and price of item in entry widgets. self.name.insert(0, newItem.getName()) self.description.insert(0, newItem.getDescription()) self.price.insert(0, newItem.getCurrentPrice()) # Get the items icon url and set the icon to the new items image. self.iconImg2 = self.getImage(newItem.getLargeIconURL()) self.icon.configure(image=self.iconImg2) self.icon.image = self.iconImg2 # Call the plot method with the new items daily price data self.plot(newItem.getGraphData()['daily']) def centerWindow(self): sw = self.master.winfo_screenwidth() sh = self.master.winfo_screenheight() w = sw / 2 h = 0.75 * sh x = (sw - w) / 2 y = (sh - h) / 2 self.master.geometry('%dx%d+%d+%d' % (w, h, x, y)) def makeGrid(self): for x in range(0, 20): self.columnconfigure(x, weight=1) for i in range(0, 20): self.rowconfigure(i, weight=1, minsize=20) def getImage(self, URL): imageRequest = requests.get(URL) return ImageTk.PhotoImage( Image.open(BytesIO(imageRequest.content)).resize((97, 97)))
class PropertiesFrame(Frame): def __init__(self, main): super(PropertiesFrame, self).__init__(main.screen) self.main = main self.title = Label(self, text=main.lang.get_translate("properties_title", "Properties"), font=('Arial', '16')) self.columnconfigure(0, weight=1) self.columnconfigure(1, weight=10) self.title.grid(row=0, column=0, columnspan=2) Separator(self, orient=HORIZONTAL).grid(row=1, column=0, columnspan=2, sticky="EW") self.properties_widgets = {} self.current_obj = None def show_properties(self, object_): for i in self.properties_widgets.values(): for widget in i: if isinstance(widget, list): widget[0].grid_forget() else: widget.grid_forget() self.current_obj = object_ nb = 0 for k, v in object_.properties(): label = Label(self, text=self.main.lang.get_translate("properties_"+k, k.replace("_", " ").title()+": "), font=("Arial", "14")) label.grid(row=2+nb, column=0, sticky="EW", padx=10, pady=10) if k == "type_": other = Label(self, text=v, font=("Arial", "14")) other.grid(row=2+nb, column=1, sticky="EW", padx=50, pady=10) elif k == "material": other = Combobox(self, values=BLOCK_MATERIALS) other.current(BLOCK_MATERIALS.index(v)) other.grid(row=2+nb, column=1, sticky="EW", padx=50, pady=10) elif k == "itemgroup": list_ = [i.name.upper().replace(" ", "_")+"_GROUP" for i in self.main.project.objects["itemgroups"]] + \ ITEMGROUP other = Combobox(self, values=list_) other.current(list_.index(v)) other.grid(row=2+nb, column=1, sticky="EW", padx=50, pady=10) elif k == "icon": list_ = [i.name.upper().replace(" ", "_") for i in self.main.project.objects["blocks"]] + ICON_BLOCKS other = Combobox(self, values=list_) other.current(list_.index(v)) other.grid(row=2+nb, column=1, sticky="EW", padx=50, pady=10) elif k in ("search", "loot"): var = IntVar() other = [Checkbutton(self, variable=var), var] if v: other[0].invoke() other[0].grid(row=2+nb, column=1, sticky="EW", padx=50, pady=10) elif k == "script": other = Text(self) other.insert("1.0", v) other.grid(row=2+nb, column=1, sticky="EW", padx=50, pady=10) else: other = Entry(self) other.insert(0, v) other.grid(row=2+nb, column=1, sticky="EW", padx=50, pady=10) nb += 1 self.properties_widgets[k] = [label, other] s = Style() s.configure('test.TButton', font=('Arial', 14)) btn = Button(self, text=self.main.lang.get_translate("properties_validate", "Validate"), command=self.set_properties, style="test.TButton") btn.grid(row=2+nb, column=0, sticky="EW", padx=50, pady=20, columnspan=2) self.properties_widgets['BTN_VALIDATE'] = [btn] def set_properties(self): change = self.current_obj.change(self.properties_widgets, self.main) if change: self.main.project.edit_objects()
# Create main window root = themed_tk.ThemedTk() root.set_theme("scidpurple") root.title("Product Manager") # root.geometry("640x480+10+10") # root.rowconfigure(0, weight=1) root.columnconfigure(0, weight=1) entry_frame = LabelFrame(root, text="Enter Product Details") # Product Name product_name_var = tk.StringVar() product_name_label = Label(entry_frame, text="Product Name: ") product_name_label.grid(row=0, column=0, sticky="w", padx=10) product_name_entry = Entry(entry_frame, textvariable=product_name_var) product_name_entry.grid(row=0, column=1) # Product ID product_id_var = tk.StringVar() product_id_label = Label(entry_frame, text="Product ID: ") product_id_label.grid(row=1, column=0, sticky="w", padx=10) product_id_entry = Entry(entry_frame, textvariable=product_id_var) product_id_entry.grid(row=1, column=1) # Customer customer_var = tk.StringVar() customer_label = Label(entry_frame, text="Customer: ") customer_label.grid(row=0, column=2, sticky="w", padx=10) customer_entry = Entry(entry_frame, textvariable=customer_var)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("") #self.style = Style() #self.style.theme_use("clam") #self.pack(fill=BOTH, expand = 1) self.labelU = Label(self, text="U:") self.labelP = Label(self, text="P:") self.mailrecipient = 'GoldenSights' self.entryUsername = Entry(self) self.entryUsername.focus_set() self.entryUsername.bind('<Return>', lambda event: self.entryPassword.focus_set()) self.entryPassword = Entry(self) self.entryPassword.config(show='•') self.entryPassword.bind( '<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton = Button( self, text="Login", command=lambda: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton.bind( '<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton.config(width=6) self.quitbutton = Button(self, text="Quit", command=lambda: self.quit()) self.quitbutton.config(width=6) self.labelU.grid(row=0, column=0, padx=0) self.entryUsername.grid(row=0, column=1) self.labelP.grid(row=1, column=0) self.entryPassword.grid(row=1, column=1, pady=4) self.newbutton.grid(row=2, column=1) self.quitbutton.grid(row=3, column=1, pady=4) self.labelErrorPointer = Label(self, text="◀") self.indicatorGreen = PhotoImage(file="indicatorGreen.gif") self.indicatorRed = PhotoImage(file="indicatorRed.gif") self.indicatorBlue = PhotoImage(file="indicatorBlue.gif") self.indicatorBlack = PhotoImage(file="indicatorBlack.gif") sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() w = 400 h = 480 x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y - 50)) def login(self, username, password): print('U: ' + username) self.username = username if username == '' or not all( char in string.ascii_letters + string.digits + '_-' for char in username): print('Please enter a username') self.entryUsername.focus_set() self.labelErrorPointer.grid(row=0, column=2) elif password == '': print('Please enter a password') self.entryPassword.focus_set() self.labelErrorPointer.grid(row=1, column=2) else: self.labelErrorPointer.grid_forget() print('Attempting login for ' + username) try: self.USERAGENT = username + ' practices Tkinter+PRAW mixing with utility by /u/GoldenSights.' self.r = praw.Reddit(self.USERAGENT) #self.r.login(username, password) print('Success') self.labelU.grid_forget() self.labelP.grid_forget() self.entryUsername.grid_forget() self.entryPassword.grid_forget() self.newbutton.grid_forget() self.quitbutton.grid_forget() self.usernamelabel = Label(self, text=username + ', Sending to /u/' + self.mailrecipient) self.usernamelabel.grid(row=0, column=0, columnspan=8) self.quitbutton.grid(row=900, column=0) self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] self.optionDiscuss = "Discussion Flair + Crossposting" self.optionRegister = "Register a new Candidate" self.prevmode = self.optionDiscuss self.curmode = self.optionDiscuss self.optionvar = tkinter.StringVar(self) self.optionvar.trace("w", self.permaloop) self.optionvar.set(self.optionDiscuss) self.option = OptionMenu(self, self.optionvar, self.optionDiscuss, self.optionRegister, "three", "four") self.newbutton.unbind("<Return>") self.entryUsername.unbind("<Return>") self.entryPassword.unbind("<Return>") self.option.grid(row=1, column=0, columnspan=8, pady=8) self.updategui(True) except praw.errors.InvalidUserPass: pass print('Invalid username or password') self.entryPassword.delete(0, 200) self.labelErrorPointer.grid(row=1, column=2) def permaloop(self, *args): self.curmode = self.optionvar.get() print('Was: ' + self.prevmode + ' | Now: ' + self.curmode) if self.curmode != self.prevmode: self.prevmode = self.curmode self.updategui(True) def updategui(self, *args): if args[0] == True: print('Cleaning GUI') for item in self.labellist: item.grid_forget() for item in self.entrylist: item.grid_forget() for item in self.verifylist: item.grid_forget() for item in self.misclist: item.grid_forget() self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] if self.curmode == self.optionDiscuss: self.newrowindex = 4 self.labelPermalink = Label(self, text="Thread Permalink:") self.entryPermalink = Entry(self) self.rowconfigure(2, weight=2) self.labelPermalink.grid(row=2, column=0) self.entryPermalink.grid(row=2, column=1) self.labelcrossposting = Label(self, text="Crosspost to:") self.labelcrossposting.grid(row=3, column=0, columnspan=2, sticky="w") for m in range(5): self.redditlabel = Label(self, text="/r/") self.redditlabel.grid(row=self.newrowindex, column=0, sticky="e") self.labellist.append(self.redditlabel) self.redditentry = Entry(self) self.redditentry.grid(row=self.newrowindex, column=1) self.entrylist.append(self.redditentry) self.newrowindex += 1 self.morerowbutton = Button( self, text="+row", command=lambda: self.morerows('/r/', 0, 1, 20)) self.morerowbutton.grid(row=898, column=0, columnspan=2) self.verifybutton = Button( self, text="Verify", command=lambda: self.updategui(False)) self.verifybutton.grid(row=899, column=0, columnspan=2) self.newrowindex += 2 self.misclist.append(self.labelPermalink) self.misclist.append(self.labelcrossposting) self.misclist.append(self.entryPermalink) self.misclist.append(self.morerowbutton) self.misclist.append(self.verifybutton) if self.curmode == self.optionRegister: self.newrowindex = 6 self.labelCanUsername = Label( self, text="Candidate's Username: /u/") self.entryCanUsername = Entry(self) self.labelCanRealname = Label(self, text="Candidate's Realname:") self.entryCanRealname = Entry(self) self.labelCanFlair = Label(self, text="Candidate's Flair:") self.entryCanFlair = Entry(self) self.entryMo = Spinbox( self, width=9, values=('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')) self.entryDa = Spinbox(self, width=2, from_=1, to=31) self.entryYr = Spinbox(self, width=4, from_=2014, to=2500) self.labelHH = Label(self, text="Schedule time UTC:") self.entryHH = Spinbox(self, from_=0, to=23, width=2) self.entryMM = Spinbox(self, from_=0, to=59, width=2) self.entryYr.delete(0, 'end') self.entryYr.insert(0, 2014) self.morerowbutton = Button( self, text="+question", command=lambda: self.morerows('Q:', 0, 1, 25)) self.morerowbutton.grid(row=898, column=0, columnspan=8) self.verifybutton = Button( self, text="Verify", command=lambda: self.updategui(False)) self.verifybutton.grid(row=899, column=0, columnspan=8) self.misclist.append(self.labelCanUsername) self.misclist.append(self.labelCanRealname) self.misclist.append(self.entryCanUsername) self.misclist.append(self.entryCanRealname) self.misclist.append(self.labelHH) self.misclist.append(self.entryHH) self.misclist.append(self.entryMM) self.misclist.append(self.entryMo) self.misclist.append(self.entryDa) self.misclist.append(self.entryYr) self.labelCanUsername.grid(row=2, column=0, sticky="e") self.labelCanRealname.grid(row=3, column=0, sticky="e") self.entryCanUsername.grid(row=2, column=1, columnspan=3) self.entryCanRealname.grid(row=3, column=1, columnspan=3) self.entryMo.grid(row=4, column=1, sticky="e") self.entryDa.grid(row=4, column=2) self.entryYr.grid(row=4, column=3) self.labelHH.grid(row=4, column=0, sticky="se", pady=5) self.entryHH.grid(row=5, column=1, sticky="e") self.entryMM.grid(row=5, column=2, sticky="w") else: if self.curmode == self.optionDiscuss: verifies = [] i = self.entryPermalink.get() if len(i) == 6: pid = i else: if 'www.reddit.com/r/' in i and '/comments/' in i: pid = i.split('/comments/')[1].split('/')[0] if 'http://redd.it/' in i: pid = i.split('redd.it/')[1] for flag in self.verifylist: flag.grid_forget() self.verifylist.remove(flag) try: print('Fetching Submission ' + pid) self.r.get_info(thing_id="t3_" + pid).title + 'Check' self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=2, column=2) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: print( 'Failed. Make sure to include the http://. Copy and paste straight from your browser for best result' ) self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2, column=2) self.verifylist.append(self.redditlabel) verifies.append(False) for entry in self.entrylist: i = entry.get() if i != '': print('Fetching /r/' + i) if all(char in string.ascii_letters + string.digits + '_-' for char in i): try: sub = self.r.get_subreddit(i, fetch=True) self.redditlabel = Label( self, image=self.indicatorGreen) self.redditlabel.grid( row=entry.grid_info()['row'], column=2) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: self.redditlabel = Label( self, image=self.indicatorRed) self.redditlabel.grid( row=entry.grid_info()['row'], column=2) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') time.sleep(2) else: self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=entry.grid_info()['row'], column=2) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') print(verifies) if self.curmode == self.optionRegister: verifies = [] u = self.entryCanUsername.get() print('Fetching /u/' + u) if not all(char in string.ascii_letters + string.digits + '_-' for char in u): self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2, column=4) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tBad characterage') else: try: u = self.r.get_redditor(u) print(u) self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=2, column=4) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2, column=4) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') try: print('Checking Time') t = self.entryMo.get() + ' ' + self.entryDa.get( ) + ' ' + self.entryYr.get() + ' ' + self.entryHH.get( ) + ':' + self.entryMM.get() plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M") plandate = datetime.datetime.utcfromtimestamp( plandate.timestamp()) print('\t' + str(plandate.timestamp())) self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=5, column=3) self.verifylist.append(self.redditlabel) verifies.append(True) except: print('\tFailed') self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=5, column=3) self.verifylist.append(self.redditlabel) verifies.append(False) print(verifies) def morerows(self, label, columnm, columnn, limit, *args): self.redditlabel = Label(self, text=label) self.redditlabel.grid(row=self.newrowindex, column=columnm, sticky="e") self.labellist.append(self.redditlabel) self.redditentry = Entry(self) self.redditentry.grid(row=self.newrowindex, column=columnn, columnspan=8) self.entrylist.append(self.redditentry) self.newrowindex += 1 if self.newrowindex >= limit: self.morerowbutton.grid_forget() print(self.newrowindex)
class Download(Frame): def __init__(self, master, **kwargs): super(Download, self).__init__(master, borderwidth=20, **kwargs) self.fs = None self.tree = None self.logfile = None # User informations 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): self.info_label.config(text=text) def save(self): 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): 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) lds_account = self.fs.get_url( '/platform/tree/persons/%s/ordinances.json' % self.fs.get_userid()) != 'error' 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.get_userid()) self.update_needed = False def quit(self): self.update_needed = False if self.logfile: self.logfile.close() super(Download, self).quit() # prevent exception during download os._exit(1) def download(self): 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(_('Download 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( _('Download ') + str(i + 1) + _('th generation of ancestors...')) 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( _('Download ') + str(i + 1) + _('th generation of descendants...')) todo = self.tree.add_children(todo) - done if self.options.spouses.get(): self.info(_('Download 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( _('Download 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): def res(): self.update_needed = True Thread(target=self.update_gui).start() Thread(target=func).start() return res def update_info_tree(self): 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, '00%s'[len(str(seconds)):] % seconds)) def update_gui(self): while self.update_needed: self.update_info_tree() self.master.update() time.sleep(0.1)
class SolutionTabFrame(Frame): ''' This class is responsible for displaying solution on the screen. It extends Frame class. Attributes: parent (Tk object that can contain Frame): parent that can contain Frame, MUST implement method change_solution_tab_name(str). data_from_file_lbl (Label): label that contains file name with data if specified. solution_tab (SolutionFrameWithText): notebook with tabs describing solution. model_solutions (list of Solution): list with one or more solutions that have been generated after running algorithm. param_strs (list of str): list with strings that should appear before printing every solution from model_solutions. ranks (list of list of int): list of ranks corresponding to every solution from model_solutions, ranks are generated by peel-the-onion algorithm. categorical (str): name of the categorical variable used in categorical analysis. progress_bar (Progressbar): progress bar to show how solution is loaded or saved to file. status_lbl (Label): label for displaying solution status. solution_format_var (IntVar): IntVar object that tracks which file format is chosen for solution. ''' def __init__(self, parent, *args, **kw): super().__init__(parent, *args, **kw) self.parent = parent self.data_from_file_lbl = None self.solution_tab = None self.model_solutions = None self.param_strs = None self.ranks = None self.params = None self.categorical = None self.run_date = None self.total_seconds = 0 self.progress_bar = None self.status_lbl = None self.solution_format_var = IntVar() self.create_widgets() 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('*.csv', 2, frame_for_btns, 1) 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 _create_file_format_btn(self, btn_text, var_value, parent, column): ''' Creates and grids Radiobutton used for choosing solution file format. Args: btn_text (str): text displayed next to the Radiobutton. var_value (int): value of the IntVar associated with this Radiobutton. parent (Tk object): parent of this Radiobutton. column (int): column index where this Radiobutton should be gridded. ''' sol_format_btn = Radiobutton(parent, text=btn_text, variable=self.solution_format_var, value=var_value) sol_format_btn.grid(row=2, column=column, sticky=W + N, padx=2) def on_save_solution(self): ''' Saves solution to file. This method is called when save solution button is pressed. If there is a solution, this method will ask user to provide a file name where solution should be stored. If a valid name is provided, solution is saved to that file. Allowed file format is .xlsx. If the user checked 'csv' as solution output format, then the user will be asked to choose a directory where all csv files will be written. ''' if self.model_solutions is not None: assert (self.param_strs is not None) if self.solution_format_var.get() == 1: #xlsx file_name = self.ask_file_name_to_save( self.solution_format_var.get()) dir_name = '' else: #csv dir_name = askdirectory() file_name = '' if file_name or dir_name: print(file_name) self.status_lbl.config(text='Saving solution to file...') if file_name.endswith('.xlsx'): work_book = XlsxWorkbook() else: # all not supported formats will be written to csv assert (dir_name) work_book = TxtWriter(dir_name) writer = FileWriter(self.params, work_book, self.run_date, self.total_seconds, ranks=self.ranks, categorical=self.categorical) nb_models = len(self.model_solutions) # +1 for parameters sheet, it is stored separately nb_sheets = len(writer.worksheets) + 1 progress_recorder = GuiProgress(self.progress_bar, nb_models, nb_sheets) try: for count, sol in enumerate(self.model_solutions): writer.write_data(sol, self.param_strs[count], progress_recorder) work_book.save(file_name) except ValueError: # can happen if maximum number of rows is exceeded self.status_lbl.config( text='File is too large for xlsx format,' ' it will be saved to csv instead') work_book = TxtWriter(os.path.splitext(file_name)[0]) writer = FileWriter(self.params, work_book, self.run_date, self.total_seconds, ranks=self.ranks, categorical=self.categorical) progress_recorder.set_position(0) for count, sol in enumerate(self.model_solutions): writer.write_data(sol, self.param_strs[count], progress_recorder) work_book.save(file_name) progress_recorder.set_position(100) self.parent.change_solution_tab_name('Solution') self.status_lbl.config(text='Solution saved') def ask_file_name_to_save(self, ext_code): ''' Calls asksaveasfilename dialogue to ask the user where file should be saved. If file without extension is entered, default extension will be used (.xlsx). This method is used to mock this object for unit tests. Args: ext_code (int): code for file extension 1 - xlsx. ''' if ext_code == 1: filetype = SOLUTION_XLSX_FILE return asksaveasfilename(filetypes=filetype, defaultextension='.xlsx') def show_solution(self, solutions, params, param_strs, run_date, total_seconds, ranks=None, categorical=None): ''' Displays solution on the screen. Args: solutions (list of Solution): list of solutions (might contain just one solution) that have been generated after running algorithm. params (Parameters): object with parameters that will be written to file on the Parameters page. param_strs (list of str): list with strings that should appear before printing every solution from model_solutions. ranks (list of list of int): list of ranks corresponding to every solution from model_solutions, ranks are generated by peel-the-onion algorithm. categorical (str): name of the categorical variable used in categorical analysis. ''' self.status_lbl.config(text='') self.model_solutions = solutions self.param_strs = param_strs self.ranks = ranks self.params = params self.categorical = categorical self.run_date = run_date self.total_seconds = total_seconds self.status_lbl.config(text='Loading solution...') self.solution_tab.show_solution(solutions, params, param_strs, run_date, total_seconds, ranks, categorical) self.parent.change_solution_tab_name('Solution*') self.status_lbl.config(text='Solution loaded') def update_data_file_name(self, new_data_file_name): ''' Updates label with data file name. Args: new_data_file_name (str): new value of the data file name ''' self.data_from_file_lbl.config(text=TEXT_FOR_FILE_LBL + new_data_file_name)
class Form(Toplevel): def __init__(self, master, event, new=False): Toplevel.__init__(self, master) self.minsize(410, 402) if master.winfo_ismapped(): self.transient(master) self.protocol('WM_DELETE_WINDOW', self.cancel) self._only_nb = self.register(only_nb) self.event = event if new: self.title(_('New Event')) else: self.title(_('Edit Event')) self._new = new self._task = BooleanVar(self, bool(event['Task'])) self._whole_day = BooleanVar(self, event['WholeDay']) # --- style style = Style(self) active_bg = style.lookup('TEntry', 'selectbackground', ('focus', )) self.alarms = [] notebook = Notebook(self) notebook.pack(fill='both', expand=True) Button(self, text=_('Ok'), command=self.ok).pack(pady=(10, 6), padx=4) # --- event settings frame_event = Frame(notebook) notebook.add(frame_event, text=_('Event'), sticky='eswn', padding=4) frame_event.columnconfigure(1, weight=1) frame_event.rowconfigure(5, weight=1) self.img_moins = PhotoImage(master=self, file=IM_DEL) self.img_bell = PhotoImage(master=self, file=IM_BELL) Label(frame_event, text=_('Summary')).grid(row=0, column=0, padx=4, pady=6, sticky='e') Label(frame_event, text=_('Place')).grid(row=1, column=0, padx=4, pady=6, sticky='e') Label(frame_event, text=_('Start')).grid(row=2, column=0, padx=4, pady=6, sticky='e') self._end_label = Label(frame_event, text=_('End')) self._end_label.grid(row=3, column=0, padx=4, pady=6, sticky='e') frame_task = Frame(frame_event) frame_task.grid(row=4, column=1, padx=4, pady=6, sticky='w') Label(frame_event, text=_('Description')).grid(row=5, column=0, padx=4, pady=6, sticky='e') Label(frame_event, text=_('Category')).grid(row=6, column=0, padx=4, pady=6, sticky='e') Button(frame_event, image=self.img_bell, command=self.add_reminder, padding=0).grid(row=7, column=0, padx=4, pady=6, sticky='en') self.summary = Entry(frame_event, width=35) self.summary.insert(0, self.event['Summary']) self.summary.grid(row=0, column=1, padx=4, pady=6, sticky='ew') self.place = Entry(frame_event, width=35) self.place.insert(0, self.event['Place']) self.place.grid(row=1, column=1, padx=4, pady=6, sticky='ew') frame_start = Frame(frame_event) frame_start.grid(row=2, column=1, padx=4, pady=6, sticky='w') frame_end = Frame(frame_event) frame_end.grid(row=3, column=1, padx=4, pady=6, sticky='w') txt_frame = Frame(frame_event, style='txt.TFrame', border=1, relief='sunken') self.desc = Text(txt_frame, width=35, height=4, highlightthickness=0, relief='flat', selectbackground=active_bg) self.desc.insert('1.0', self.event['Description']) self.desc.pack(fill='both', expand=True) txt_frame.grid(row=5, column=1, padx=4, pady=6, sticky='ewsn') cats = list(CONFIG.options('Categories')) width = max([len(cat) for cat in cats]) self.category = Combobox(frame_event, width=width + 2, values=cats, state='readonly') self.category.set(event['Category']) self.category.grid(row=6, column=1, padx=4, pady=6, sticky='w') self.frame_alarms = Frame(frame_event) self.frame_alarms.grid(row=7, column=1, sticky='w') # --- *--- task Checkbutton(frame_task, text=_('Task'), command=self._change_label, variable=self._task).pack(side='left') self.task_progress = Combobox(frame_task, state='readonly', width=9, values=(_('Pending'), _('In Progress'), _('Completed'), _('Cancelled'))) self.task_progress.pack(side='left', padx=(8, 4)) self.in_progress = Combobox( frame_task, state='readonly', width=5, values=['{}%'.format(i) for i in range(0, 110, 10)]) self.in_progress.pack(side='left', padx=4) if not event['Task']: self.task_progress.set(_('Pending')) self.in_progress.set('0%') elif '%' in event['Task']: self.task_progress.set(_('In Progress')) self.in_progress.set(event['Task']) else: self.task_progress.set(_(event['Task'])) self.in_progress.set('0%') # calendar settings prop = { op: CONFIG.get('Calendar', op) for op in CONFIG.options('Calendar') } prop['font'] = "Liberation\ Sans 9" prop.update(selectforeground='white', selectbackground=active_bg) locale = CONFIG.get('General', 'locale') # --- *--- start date self.start_date = self.event['Start'] self.start_entry = DateEntry(frame_start, locale=locale, width=10, justify='center', year=self.start_date.year, month=self.start_date.month, day=self.start_date.day, **prop) self.start_hour = Combobox(frame_start, width=3, justify='center', state='readonly', exportselection=False, values=['%02d' % i for i in range(24)]) self.start_hour.set('%02d' % self.start_date.hour) self.start_min = Combobox(frame_start, width=3, justify='center', state='readonly', exportselection=False, values=['%02d' % i for i in range(0, 60, 5)]) self.start_min.set('%02d' % self.start_date.minute) self.start_entry.pack(side='left', padx=(0, 18)) self.start_hour.pack(side='left', padx=(4, 0)) self.start_date = self.start_date.date() Label(frame_start, text=':').pack(side='left') self.start_min.pack(side='left', padx=(0, 4)) Checkbutton(frame_start, text=_("whole day"), variable=self._whole_day, command=self._toggle_whole_day).pack(side='left', padx=4) # --- *--- end date self.end_date = self.event['End'] self.end_entry = DateEntry(frame_end, justify='center', locale=locale, width=10, year=self.end_date.year, month=self.end_date.month, day=self.end_date.day, **prop) self.end_hour = Combobox(frame_end, width=3, justify='center', state='readonly', exportselection=False, values=['%02d' % i for i in range(24)]) self.end_hour.set('%02d' % self.end_date.hour) self.end_min = Combobox(frame_end, width=3, justify='center', state='readonly', exportselection=False, values=['%02d' % i for i in range(0, 60, 5)]) self.end_min.set('%02d' % self.end_date.minute) self.end_entry.pack(side='left', padx=(0, 18)) self.end_hour.pack(side='left', padx=(4, 0)) Label(frame_end, text=':').pack(side='left') self.end_min.pack(side='left', padx=(0, 4)) self.end_date = self.end_date.date() for date in self.event['Reminders'].values(): self.add_reminder(date) self._toggle_whole_day() # --- repetition settings frame_rep = Frame(notebook) notebook.add(frame_rep, text=_('Repetition'), padding=4, sticky='eswn') frame_rep.columnconfigure(0, weight=1) frame_rep.columnconfigure(1, weight=1) frame_rep.rowconfigure(1, weight=1) self._repeat = BooleanVar(self, bool(self.event['Repeat'])) repeat = { 'Frequency': 'year', 'Limit': 'always', 'NbTimes': 1, 'EndDate': (datetime.now() + timedelta(days=1)).date(), 'WeekDays': [self.start_date.isocalendar()[2] - 1] } repeat.update(self.event['Repeat']) self._repeat_freq = StringVar(self, repeat['Frequency']) Checkbutton(frame_rep, text=_('Repeat event'), variable=self._repeat, command=self._toggle_rep).grid(row=0, column=0, columnspan=2, padx=4, pady=6, sticky='w') # --- *--- Frequency frame_freq = LabelFrame(frame_rep, text=_('Frequency')) frame_freq.grid(row=1, column=0, sticky='eswn', padx=(0, 3)) self._lfreq = Label(frame_freq, text=_('Every:')) self._lfreq.grid(row=0, column=0, padx=4, pady=2, sticky='e') self._freqs = [] for i, val in enumerate(['Year', 'Month', 'Week']): r = Radiobutton(frame_freq, text=_(val), variable=self._repeat_freq, value=val.lower(), command=self._toggle_wd) r.grid(row=i, column=1, padx=4, pady=2, sticky='nw') self._freqs.append(r) frame_days = Frame(frame_freq) frame_days.grid(row=2, column=2, padx=4, pady=2, sticky='nw') self._week_days = [] days = get_day_names("wide", locale=locale) days = [days[i] for i in range(7)] for day in days: ch = Checkbutton(frame_days, text=day) ch.pack(anchor='w') self._week_days.append(ch) for d in repeat['WeekDays']: self._week_days[int(d)].state(('selected', )) # --- *--- Limit frame_lim = LabelFrame(frame_rep, text=_('Limit')) frame_lim.grid(row=1, column=1, sticky='eswn', padx=(3, 0)) frame_lim.grid(row=1, column=1, sticky='eswn', padx=(3, 0)) self._repeat_lim = StringVar(self, repeat['Limit']) # always r1 = Radiobutton(frame_lim, text=_('Always'), value='always', variable=self._repeat_lim, command=self._toggle_lim) r1.grid(row=0, column=0, sticky='w') # until r2 = Radiobutton(frame_lim, text=_('Until'), value='until', variable=self._repeat_lim, command=self._toggle_lim) r2.grid(row=1, column=0, sticky='w') until_date = repeat['EndDate'] self.until_entry = DateEntry(frame_lim, width=10, justify='center', locale=locale, year=until_date.year, month=until_date.month, day=until_date.day, **prop) self.until_entry.grid(row=1, column=1, columnspan=2, sticky='w', padx=(4, 10), pady=2) # after r3 = Radiobutton(frame_lim, text=_('After'), value='after', variable=self._repeat_lim, command=self._toggle_lim) r3.grid(row=2, column=0, sticky='w') frame_after = Frame(frame_lim, style='txt.TFrame', relief='sunken', border=1) self.s_after = Spinbox(frame_after, from_=0, to=100, width=3, justify='center', relief='flat', highlightthickness=0, validate='key', validatecommand=(self._only_nb, '%P'), disabledbackground='white') self.s_after.pack() self.s_after.delete(0, 'end') self.s_after.insert(0, str(repeat['NbTimes'])) frame_after.grid(row=2, column=1, padx=4, pady=2, sticky='w') self._llim = Label(frame_lim, text=_('times')) self._llim.grid(row=2, column=2, padx=0, pady=2, sticky='w') self._rb_lim = [r1, r2, r3] self._toggle_rep() self._change_label() # --- bindings self.bind('<Configure>') self.task_progress.bind('<<ComboboxSelected>>', self._toggle_in_progress) self.start_entry.bind('<<DateEntrySelected>>', self._select_start) self.end_entry.bind('<<DateEntrySelected>>', self._select_end) self.start_hour.bind("<<ComboboxSelected>>", self._select_start_hour) self.start_min.bind("<<ComboboxSelected>>", self._select_start_min) self.end_min.bind("<<ComboboxSelected>>", self._select_end_time) self.end_hour.bind("<<ComboboxSelected>>", self._select_end_time) self.bind_class("TCombobox", "<<ComboboxSelected>>", self.__clear_selection, add=True) # self.wait_visibility(self) # self.grab_set() self.summary.focus_set() def _toggle_lim(self, val=True): if val: val = self._repeat_lim.get() if val == 'until': self.s_after.configure(state='disabled') self._llim.state(('disabled', )) self.until_entry.state(('!disabled', )) elif val == 'after': self._llim.state(('!disabled', )) self.s_after.configure(state='normal') self.until_entry.state(('disabled', )) else: self.s_after.configure(state='disabled') self._llim.state(('disabled', )) self.until_entry.state(('disabled', )) def _toggle_rep(self): rep = self._repeat.get() state = state = '!' * int(rep) + "disabled" for r in self._freqs: r.state((state, )) for r in self._rb_lim: r.state((state, )) self._lfreq.state((state, )) self._toggle_wd(rep) self._toggle_lim(rep) def _toggle_wd(self, val=True): if val: val = self._repeat_freq.get() state = '!' * int(val == 'week') + "disabled" for ch in self._week_days: ch.state((state, )) def _toggle_whole_day(self): if self._whole_day.get(): self.start_min.set('00') self.start_hour.set('00') self.end_min.set('59') self.end_hour.set('23') self.start_min.state(("disabled", )) self.start_hour.state(("disabled", )) self.end_min.state(("disabled", )) self.end_hour.state(("disabled", )) else: self.start_min.state(("!disabled", )) self.start_hour.state(("!disabled", )) self.end_min.state(("!disabled", )) self.end_hour.state(("!disabled", )) def _toggle_in_progress(self, event=None): if self.task_progress.get() == _('In Progress'): self.in_progress.state(('!disabled', )) else: if self.task_progress.get() == _('Completed'): self.in_progress.set('100%') self.in_progress.state(('disabled', )) def _change_label(self): if self._task.get(): self.task_progress.state(('!disabled', )) self._toggle_in_progress() self._end_label.configure(text=_('Deadline')) else: self.task_progress.state(('disabled', )) self.in_progress.state(('disabled', )) self._end_label.configure(text=_('End')) def _on_move(self, event): self.start_cal.withdraw() self.end_cal.withdraw() self.until_cal.withdraw() @staticmethod def __clear_selection(event): combo = event.widget combo.selection_clear() def _select_start(self, event=None): dt = self.start_entry.get_date() - self.start_date self.end_date = self.end_date + dt self.end_entry.set_date(self.end_date) self.start_date = self.start_entry.get_date() def _select_end(self, event=None): self.end_date = self.end_entry.get_date() start = self.start_entry.get_date() if start >= self.end_date: self.start_date = self.end_date self.start_entry.set_date(self.end_date) start_time = time(int(self.start_hour.get()), int(self.start_min.get())) end_time = time(int(self.start_hour.get()), int(self.end_min.get())) if start_time > end_time: self.start_hour.set(self.end_hour.get()) self.start_min.set(self.end_min.get()) def _select_start_hour(self, event): h = int(self.start_hour.get()) self.end_hour.set('%02d' % ((h + 1) % 24)) def _select_start_min(self, event): m = int(self.start_min.get()) self.end_min.set('%02d' % m) def _select_end_time(self, event): if self.start_entry.get() == self.end_entry.get(): start_time = time(int(self.start_hour.get()), int(self.start_min.get())) end_time = time(int(self.end_hour.get()), int(self.end_min.get())) if start_time > end_time: self.start_hour.set(self.end_hour.get()) self.start_min.set(self.end_min.get()) def add_reminder(self, date=None): def remove(): self.alarms.remove((when, what)) rem.destroy() rem = Frame(self.frame_alarms) frame_when = Frame(rem, style='txt.TFrame', relief='sunken', border=1) when = Spinbox(frame_when, from_=0, to=59, width=3, justify='center', relief='flat', highlightthickness=0, validate='key', validatecommand=(self._only_nb, '%P')) when.pack() when.delete(0, 'end') what = Combobox(rem, width=8, state='readonly', values=(_('minutes'), _('hours'), _('days'))) if date: hour = int(self.start_hour.get()) minute = int(self.start_min.get()) dt = datetime.combine(self.start_entry.get_date(), time(hour=hour, minute=minute)) - date if dt.days > 0: when.insert(0, str(dt.days)) what.set(_('days')) else: h, m, s = str(dt).split(':') if h != "0": when.insert(0, h) what.set(_('hours')) else: when.insert(0, str(int(m))) what.set(_('minutes')) else: when.insert(0, '15') what.set(_('minutes')) self.alarms.append((when, what)) Label(rem, text=_('Reminder:')).pack(side='left', padx=4, pady=4) frame_when.pack(side='left', pady=4, padx=4) what.pack(side='left', pady=4, padx=4) Button(rem, image=self.img_moins, padding=0, command=remove).pack(side='left', padx=4, pady=4) rem.pack() def ok(self): summary = self.summary.get() if not summary: showerror(_("Error"), _("The field 'Summary' cannot be empty."), parent=self) return self.event['Summary'] = summary self.event['Place'] = self.place.get() self.event['Start'] = "%s %s:%s" % ( self.start_entry.get_date().strftime("%Y-%m-%d"), self.start_hour.get(), self.start_min.get()) self.event['End'] = "%s %s:%s" % (self.end_entry.get_date().strftime( "%Y-%m-%d"), self.end_hour.get(), self.end_min.get()) self.event['Description'] = self.desc.get('1.0', 'end') self.event['Category'] = self.category.get() if not self._task.get(): self.event['Task'] = False else: prog = self.task_progress.get() if prog == _('In Progress'): self.event['Task'] = self.in_progress.get() else: self.event['Task'] = TASK_REV_TRANSLATION[prog] self.event["WholeDay"] = self._whole_day.get() if not self._repeat.get(): self.event['Repeat'] = {} else: days = [] for i in range(7): if "selected" in self._week_days[i].state(): days.append(i) repeat = { 'Frequency': self._repeat_freq.get(), 'Limit': self._repeat_lim.get(), 'NbTimes': int(self.s_after.get()), 'EndDate': self.until_entry.get_date(), 'WeekDays': days } self.event['Repeat'] = repeat self.event.reminder_remove_all() for when, what in self.alarms: dt = int(when.get()) unit = FREQ_REV_TRANSLATION[what.get()] date = self.event['Start'] - timedelta(**{unit: dt}) self.event.reminder_add(date) if self._new: self.master.event_add(self.event) else: self.master.event_configure(self.event.iid) self.destroy() def cancel(self): if not self._new: self.master.widgets['Calendar'].add_event(self.event) self.destroy()
class Tooltip2: def __init__(self, widget, *, bg='#FFFFEA', pad=(5, 3, 5, 3), text='widget info', waittime=400, wraplength=500, pos=TIP_RIGHT): self.waittime = waittime # in miliseconds, originally 500 self.wraplength = wraplength # in pixels, originally 180 self.widget = widget self.text = text self.widget.bind('<Configure>', self.onConfigure, add='+') # self.widget.winfo_toplevel().bind('<Configure>', self.onWindowConfigure, add='+') self.bg = bg self.pad = pad self.pos = pos self.id = None self.win = None self.label = None def onWindowConfigure(self, event): if not event.widget.winfo_viewable(): self.hide() else: self.updatePosition() def onConfigure(self, event=None): self.updatePosition() def onEnter(self, event=None): self.schedule() def onLeave(self, event=None): self.unschedule() self.hide() def schedule(self): self.unschedule() self.id = self.widget.after(self.waittime, self.show) def unschedule(self): id_ = self.id self.id = None if id_: self.widget.after_cancel(id_) def show(self, text=None, pos=None): self.hide() if text is not None: self.text = text if pos is not None: self.pos = pos bg = self.bg pad = self.pad widget = self.widget # self.widget.bind('<Configure>', self.onConfigure, add='+') self.win = Frame(self.widget.winfo_toplevel(), background=bg, highlightcolor='red', highlightthickness=2, highlightbackground='red', borderwidth=0) self.label = Label( self.win, text=self.text, justify=LEFT, background=bg, # foreground='blue', # relief=SOLID, borderwidth=0, wraplength=self.wraplength) self.label.grid(padx=(pad[0], pad[2]), pady=(pad[1], pad[3]), sticky=NSEW) # self.win.grid() # self.win.place(in_=self.widget, x=0,y=0) # widget.update_idletasks() self.updatePosition() def hide(self): if self.win: # self.widget.unbind('<Configure>', self.onConfigure) self.win.destroy() self.win = None def updatePosition(self): if self.win: x, y = self._tip_pos_calculator(self.widget, self.win) self.win.place(in_=self.widget, x=x, y=y) def _tip_pos_calculator(self, widget, frm, tip_delta=(5, 3)): w = widget width, height = frm.winfo_width(), frm.winfo_height() width = self.label.winfo_reqwidth() + self.pad[0] + self.pad[ 2] + float(self.win.cget('highlightthickness')) * 2 height = self.label.winfo_reqheight() + self.pad[1] + self.pad[ 3] + float(self.win.cget('highlightthickness')) * 2 if self.pos == TIP_BELOW: x1, y1 = 0, w.winfo_height() + tip_delta[1] elif self.pos == TIP_ABOVE: x1, y1 = 0, -height - tip_delta[1] else: x1, y1 = w.winfo_width() + tip_delta[0], (w.winfo_height() - height) / 2 return x1, y1
def create_widgets(self): self.frame = frame = Frame(self, borderwidth=2, relief='sunken') frame.pack(side='top', expand=True, fill='both') frame_buttons = Frame(self) frame_buttons.pack(side='bottom', fill='x') self.button_ok = Button(frame_buttons, text='OK', width=8, command=self.ok) self.button_ok.grid(row=0, column=0, padx=5, pady=5) self.button_cancel = Button(frame_buttons, text='Cancel', width=8, command=self.cancel) self.button_cancel.grid(row=0, column=1, padx=5, pady=5) # Basic entry key sequence. self.frame_keyseq_basic = Frame(frame, name='keyseq_basic') self.frame_keyseq_basic.grid(row=0, column=0, sticky='nsew', padx=5, pady=5) basic_title = Label(self.frame_keyseq_basic, text=f"New keys for '{self.action}' :") basic_title.pack(anchor='w') basic_keys = Label(self.frame_keyseq_basic, justify='left', textvariable=self.key_string, relief='groove', borderwidth=2) basic_keys.pack(ipadx=5, ipady=5, fill='x') # Basic entry controls. self.frame_controls_basic = Frame(frame) self.frame_controls_basic.grid(row=1, column=0, sticky='nsew', padx=5) # Basic entry modifiers. self.modifier_checkbuttons = {} column = 0 for modifier, variable in zip(self.modifiers, self.modifier_vars): label = self.modifier_label.get(modifier, modifier) check = Checkbutton(self.frame_controls_basic, command=self.build_key_string, text=label, variable=variable, onvalue=modifier, offvalue='') check.grid(row=0, column=column, padx=2, sticky='w') self.modifier_checkbuttons[modifier] = check column += 1 # Basic entry help text. help_basic = Label(self.frame_controls_basic, justify='left', text="Select the desired modifier keys\n"+ "above, and the final key from the\n"+ "list on the right.\n\n" + "Use upper case Symbols when using\n" + "the Shift modifier. (Letters will be\n" + "converted automatically.)") help_basic.grid(row=1, column=0, columnspan=4, padx=2, sticky='w') # Basic entry key list. self.list_keys_final = Listbox(self.frame_controls_basic, width=15, height=10, selectmode='single') self.list_keys_final.insert('end', *AVAILABLE_KEYS) self.list_keys_final.bind('<ButtonRelease-1>', self.final_key_selected) self.list_keys_final.grid(row=0, column=4, rowspan=4, sticky='ns') scroll_keys_final = Scrollbar(self.frame_controls_basic, orient='vertical', command=self.list_keys_final.yview) self.list_keys_final.config(yscrollcommand=scroll_keys_final.set) scroll_keys_final.grid(row=0, column=5, rowspan=4, sticky='ns') self.button_clear = Button(self.frame_controls_basic, text='Clear Keys', command=self.clear_key_seq) self.button_clear.grid(row=2, column=0, columnspan=4) # Advanced entry key sequence. self.frame_keyseq_advanced = Frame(frame, name='keyseq_advanced') self.frame_keyseq_advanced.grid(row=0, column=0, sticky='nsew', padx=5, pady=5) advanced_title = Label(self.frame_keyseq_advanced, justify='left', text=f"Enter new binding(s) for '{self.action}' :\n" + "(These bindings will not be checked for validity!)") advanced_title.pack(anchor='w') self.advanced_keys = Entry(self.frame_keyseq_advanced, textvariable=self.key_string) self.advanced_keys.pack(fill='x') # Advanced entry help text. self.frame_help_advanced = Frame(frame) self.frame_help_advanced.grid(row=1, column=0, sticky='nsew', padx=5) help_advanced = Label(self.frame_help_advanced, justify='left', text="Key bindings are specified using Tkinter keysyms as\n"+ "in these samples: <Control-f>, <Shift-F2>, <F12>,\n" "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n" "Upper case is used when the Shift modifier is present!\n\n" + "'Emacs style' multi-keystroke bindings are specified as\n" + "follows: <Control-x><Control-y>, where the first key\n" + "is the 'do-nothing' keybinding.\n\n" + "Multiple separate bindings for one action should be\n"+ "separated by a space, eg., <Alt-v> <Meta-v>." ) help_advanced.grid(row=0, column=0, sticky='nsew') # Switch between basic and advanced. self.button_level = Button(frame, command=self.toggle_level, text='<< Basic Key Binding Entry') self.button_level.grid(row=2, column=0, stick='ew', padx=5, pady=5) self.toggle_level()
def __init__(self): tkinter.Tk.__init__(self) # Menu Setup menuBar = Menu(self) fileMenu = Menu(menuBar, tearoff=False) fileMenu.add_command(label="Open...", command=self.loadSequence) fileMenu.add_command(label="Close", command=self.closeSequence) fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self.destroy) aboutMenu = Menu(menuBar, tearoff=False) aboutMenu.add_command(label="Help", command=self.showHelp) aboutMenu.add_command(label="About...", command=self.showAbout) menuBar.add_cascade(label="File", menu=fileMenu) menuBar.add_cascade(label="About", menu=aboutMenu) # Window Setup self.title("Rotostitch " + __version__) self.config(menu=menuBar) self.iconbitmap(default=os.path.join(RESOURCE_DIR, "rotostitch-icon.ico")) masterFrame = Frame(self) masterFrame.pack(expand=1, fill=Tkc.BOTH, padx=2, pady=2) self.status = StatusBar(self) self.status.pack(anchor=Tkc.W, fill=Tkc.X, side=Tkc.BOTTOM) # Image review panels frame imgFrame = Frame(masterFrame, borderwidth=2, relief=Tkc.GROOVE) imgFrame.pack(expand=1, fill=Tkc.BOTH) imgFrame.columnconfigure(0, weight=1) imgFrame.columnconfigure(1, weight=0) imgFrame.columnconfigure(2, weight=1) imgFrame.rowconfigure(0, weight=1) imgFrame.rowconfigure(1, weight=0, pad=3) # Creation options frame settingsFrame = Frame(masterFrame, borderwidth=2, relief=Tkc.GROOVE) settingsFrame.pack(fill=Tkc.X) settingsFrame.columnconfigure(1, weight=1, pad=4) create = Button(masterFrame, text="Create", command=self.merge) create.pack(anchor='se', pady=2) self.previewStart = ZoomImage(imgFrame, width=200, height=200, borderwidth=2, relief=Tkc.RIDGE, cursor="crosshair") self.previewStart.grid(row=0, column=0, sticky=Tkc.NSEW) self.previewEnd = ZoomImage(imgFrame, width=200, height=200, borderwidth=2, relief=Tkc.RIDGE) self.previewEnd.grid(row=0, column=2, sticky=Tkc.NSEW) self.previewStart.bind("<Button>", self._startPreviewClicked) self.previewStart.bind("<<Dragged>>", self._previewDragged) self.previewEnd.bind("<<Dragged>>", self._previewDragged) # Binding just the previews to the MouseWheel event should work but doesn't. # The workaround is to bind everything to the mousewheel event # and filter it for just our previews in our callback... self.bind_all("<MouseWheel>", self.previewsScrollZoom) zoomFrame = Frame(imgFrame) zoomFrame.grid(row=0, column=1) self.zoomInImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "plus.gif")) zoomIn = Button(zoomFrame, image=self.zoomInImg, command=self.previewsZoomIn) zoomIn.pack() self.zoomResetImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "refresh.gif")) zoomReset = Button(zoomFrame, image=self.zoomResetImg, command=self.previewsResetZoom) zoomReset.pack() self.zoomOutImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "minus.gif")) zoomOut = Button(zoomFrame, image=self.zoomOutImg, command=self.previewsZoomOut) zoomOut.pack() self.differenceImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "difference.gif")) self.differenceBtn = ToggleButton(imgFrame, image=self.differenceImg) self.differenceBtn.grid(row=1, column=1) self.differenceBtn.bind("<Button1-ButtonRelease>", self.toggleDifference) startSpinFrame = Frame(imgFrame) startSpinFrame.grid(row=1, column=0) endSpinFrame = Frame(imgFrame) endSpinFrame.grid(row=1, column=2) startLabel = Label(startSpinFrame, text="Start Frame:") startLabel.pack(side=Tkc.LEFT) self.startSpin = Spinbox(startSpinFrame) self.startSpin.pack() self.startSpin.changedCallback = self.updateStartPreview endLabel = Label(endSpinFrame, text="End Frame:") endLabel.pack(side=Tkc.LEFT) self.endSpin = Spinbox(endSpinFrame) self.endSpin.pack() self.endSpin.changedCallback = self.updateEndPreview widthHeightFrame = Frame(settingsFrame) widthHeightFrame.grid(row=0, column=1, columnspan=2, sticky=Tkc.E+Tkc.W) widthLabel = Label(settingsFrame, text="Width:") widthLabel.grid(row=0, column=0, sticky=Tkc.W) self.activePic = PhotoImage(file=os.path.join(RESOURCE_DIR, "go.gif")) self.widthSetButton = Button(widthHeightFrame, text="Set", command=self.activateSetWidth, image=self.activePic, compound=Tkc.LEFT) self.widthSetButton.grid(row=0, column=1, sticky=Tkc.W) heightLabel = Label(widthHeightFrame, text="Height:") heightLabel.grid(row=0, column=2, padx=10, sticky=Tkc.E) self.unactivePic = PhotoImage(file=os.path.join(RESOURCE_DIR, "stop.gif")) self.heightSetButton = Button(widthHeightFrame, text="Set", command=self.activateSetHeight, image=self.unactivePic, compound=Tkc.LEFT) self.heightSetButton.grid(row=0, column=3, sticky=Tkc.W) rotationLabel = Label(settingsFrame, text="Rotation:") rotationLabel.grid(row=1, column=0, sticky=Tkc.W) rotFrame = Frame(settingsFrame) rotFrame.grid(row=1, column=1, sticky=Tkc.W) self.rotVar = IntVar() self.rotVar.set(1) rotLeft = Radiobutton(rotFrame, text="Counter Clockwise", value=1, variable=self.rotVar) rotLeft.pack(side=Tkc.LEFT, padx=4) rotRight = Radiobutton(rotFrame, text="Clockwise", value=2, variable=self.rotVar) rotRight.pack(padx=4) outputLabel = Label(settingsFrame, text="Save As:") outputLabel.grid(row=2, column=0, sticky=Tkc.W) self.outputPathVar = StringVar() outputEntry = Entry(settingsFrame, textvariable=self.outputPathVar) outputEntry.grid(row=2, column=1, sticky=Tkc.EW) self.outputImg = PhotoImage(file=os.path.join(RESOURCE_DIR, "folder.gif")) outputSearch = Button(settingsFrame, image=self.outputImg, command=self.setSavePath) outputSearch.grid(row=2, column=2, sticky=Tkc.W) # Object variables self.sequenceLoaded = False self.currentSequence = None self.startImage = None self.endImage = None self.differenceOn = False self.overlayTag = "OverlayItems" self.settingWidth = True self.settingHeight = False self.width = {'start': Coord(), 'end': Coord()} self.height = {'start1': Coord(), 'end1': Coord(), 'start2': Coord(), 'end2': Coord()}
def __init__(self, tab): super().__init__(tab) lblName = Label(self.frmFields, text='Название') self.entName = Entry(self.frmFields) lblName.grid(row=0, **self.grd.cl0_pdSt) self.entName.grid(row=0, **self.grd.cl1_pdSt)
class Application(Frame): """The main Tk application, a simple dialog.""" def __init__(self, master=None): super().__init__(master) self.badge = None self.grid() self.columnconfigure(0, minsize=200) self.columnconfigure(1, minsize=200) self.rowconfigure(0, minsize=300) self.rowconfigure(3, minsize=30) self.create_widgets() self.connect() def create_widgets(self): """Sets up dialog elements.""" self.select = tix.FileSelectBox(self, browsecmd=self.on_file_selected, pattern="*.fs", directory="forth") # self.select["textVariable"] = self.forth_file self.select.grid(row=0, columnspan=2, sticky='n' + 'w' + 'e') self.connect_btn = Button(self, text="Connect", command=self.toggle_connect) self.connect_btn.grid(row=1, column=0, columnspan=2) self.exec_btn = Button(self, text="Execute", command=self.send_file) self.exec_btn.state(["disabled"]) self.exec_btn.grid(row=2, column=0, sticky='w' + 'e', padx=5, pady=3) self.quit = Button(self, text="QUIT", command=self.master.destroy) self.quit.grid(row=2, column=1, sticky='w' + 'e', padx=5, pady=3) self.status_panel = Frame(self, relief="groove", borderwidth=3) self.status_panel.grid(row=3, columnspan=2, sticky='nwse') self.connect_status = Label(self.status_panel, text="Not Connected") self.connect_status.grid(row=0, padx=5, pady=5, sticky="w") if self.badge is not None: self.connect_btn.state(["disabled"]) self.connect_status.config(text="Connected: " + self.badge.os_device) def send_file(self, _retry=False): """Send the selected file to the badge.""" if self.badge: try: # oddly, very first set LED seems to not set correct color self.badge.led(0, 0, 128) self.badge.led(0, 0, 128) with open(self.select.cget("value"), 'r') as forthin: self.badge.forth_run(forthin.read()) time.sleep(1) # because forth_run() may be too fast self.badge.led(0, 128, 0) except IOError: if not _retry: self.connect() self.send_file(True) else: raise def toggle_connect(self): "If connected, disconnect, otherwise connect." if self.connect_btn.cget("text") == "Connect": self.connect() else: self.disconnect() def disconnect(self): "Disconnect from current badge." isinstance(self.badge, Badge) self.badge.close() self.badge = None self.connect_btn.config(text="Connect") self.connect_status.config(text="Not connected.") self.exec_btn.state(["disabled"]) def connect(self): """Attempt to connect to a badge; toggle Connect button if successful.""" try: self.badge = Badge() self.connect_status.config(text="Connected: " + self.badge.os_device) self.connect_btn.config(text="Disconnect") # enable "Execute" if file is selected self.on_file_selected(self.select.cget("value")) except BadgeSerialException: self.connect_status.config(text="Not connected") def on_file_selected(self, selected_file): """Respond to user selection of file by enabling the Execute button.""" if Path(selected_file).is_file: self.exec_btn.state(["!disabled"]) else: self.exec_btn.state(["disabled"])
class Example(Frame): contadorQuerysTabs = 1 def __init__(self): super().__init__() #self contador numero tab querys #Creacion de ventana self.master.title("TytusDB") self.pack(fill=BOTH, expand=True) self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(3, weight=1) self.rowconfigure(5, pad=7) self.lbl = Label(self, text="TytusDB") self.lbl.grid(sticky=W, pady=4, padx=5) self.nb = CustomNotebook(self) self.fm = Frame(self.nb) self.fm.pack(fill=BOTH, expand=True) self.fm.columnconfigure(1, weight=1) self.fm.columnconfigure(3, pad=7) self.fm.rowconfigure(3, weight=1) self.fm.rowconfigure(5, pad=7) self.nb.add(self.fm, text='Query '+str(self.contadorQuerysTabs)) self.nb.grid(row=1, column=1, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N) self.area = Text(self.fm) self.area.grid(row=1, column=1, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N) # *************************** BARRA DE MENÚ *************************** menubar = Menu(self.master) self.master.filemenu = Menu(menubar, tearoff=0) self.master.filemenu.add_command(label="Nuevo") self.master.filemenu.add_command(label="Abrir",command=self.openFile) self.master.filemenu.add_command(label="Guardar", command=self.saveFile) self.master.filemenu.add_command(label="Salir", command=self.master.quit) self.master.helpmenu = Menu(menubar, tearoff=0) self.master.helpmenu.add_command(label="Documentación") self.master.helpmenu.add_command(label="Acerca de...") self.master.servermenu = Menu(menubar, tearoff=0) self.master.servermenu.add_command(label="Nueva conexión") self.master.servermenu.add_command(label="Quitar conexión") self.master.herramientasMenu = Menu(menubar, tearoff=0) self.master.herramientasMenu.add_command(label="Query Tool", command=self.addQueryTool) self.master.herramientasMenu.add_command(label="run", command=self.run) menubar.add_cascade(label="Archivo", menu=self.master.filemenu) menubar.add_cascade(label="Servidor", menu=self.master.servermenu) menubar.add_cascade(label="Herramientas", menu=self.master.herramientasMenu) menubar.add_cascade(label="Ayuda", menu=self.master.helpmenu) self.master.config(menu=menubar); # ********************************************************************* # ******************************* ÁRBOL ******************************* self.treeview = Treeview(self) self.treeview.grid(row=1, column=0, rowspan=4, sticky=E + W + S + N); servers = self.treeview.insert("", tk.END, text="Servidores") srvr1 = self.treeview.insert(servers, tk.END, text="server_vd2020") dbs = self.treeview.insert(srvr1, tk.END, text="Databases") dvdrental = self.treeview.insert(dbs, tk.END, text="dvdrental") funcdvdrental = self.treeview.insert(dvdrental, tk.END, text="Functions") tabldvdrental = self.treeview.insert(dvdrental, tk.END, text="Tables") triggersdvdrental = self.treeview.insert(dvdrental, tk.END, text="Trigger Functions") viewsdvdrental = self.treeview.insert(dvdrental, tk.END, text="Views") sports = self.treeview.insert(dbs, tk.END, text="sports") funcsports = self.treeview.insert(sports, tk.END, text="Functions") tablsport = self.treeview.insert(sports, tk.END, text="Tables") triggersport = self.treeview.insert(sports, tk.END, text="Trigger Functions") viewsport = self.treeview.insert(sports, tk.END, text="Views") logingrp = self.treeview.insert(srvr1, tk.END, text="Login/Group Roles") usr1 = self.treeview.insert(logingrp, tk.END, text="user1") usr2 = self.treeview.insert(logingrp, tk.END, text="user2") usr3 = self.treeview.insert(logingrp, tk.END, text="user3") usr4 = self.treeview.insert(logingrp, tk.END, text="user4") # ********************************************************************* # ********************************************************************* #Metodo agregar QueryTool def addQueryTool( self ): self.contadorQuerysTabs = self.contadorQuerysTabs+1 self.nb.fm = Frame(self.nb) self.nb.fm.pack(fill=BOTH, expand=True) self.nb.fm.columnconfigure(1, weight=1) self.nb.fm.columnconfigure(3, pad=7) self.nb.fm.rowconfigure(3, weight=1) self.nb.fm.rowconfigure(5, pad=7) self.nb.add(self.nb.fm, text='Query '+str(self.contadorQuerysTabs)) self.nb.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N) self.nb.fm.area = Text(self.nb.fm) self.nb.fm.area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N) #self.lbl.configure(text="Cambia") def run(self): active_object = self.nb.nametowidget(self.nb.select()) messagebox.showinfo("Info",active_object.area.get("1.0",'end-1c')) #print(self.nb.index(self.nb.select())) #print(self.nb.tab(self.nb.select(), "text")) def saveFile( self ): f = filedialog.asksaveasfile(initialdir="/", title="Select file", mode='w', defaultextension=".sql") if f is None: # asksaveasfile return `None` if dialog closed with "cancel". return active_object = self.nb.nametowidget(self.nb.select()) text2save = str(active_object.area.get("1.0", 'end-1c')) # starts from `1.0`, not `0.0` self.nb.tab(self.nb.select(), text=os.path.basename(f.name)) f.write(text2save) f.close() def openFile( self ): filename = filedialog.askopenfilename(initialdir="/", title="Select a File") with open(filename, "r") as f: self.contadorQuerysTabs = self.contadorQuerysTabs + 1 self.nb.fm = Frame(self.nb) self.nb.fm.pack(fill=BOTH, expand=True) self.nb.fm.columnconfigure(1, weight=1) self.nb.fm.columnconfigure(3, pad=7) self.nb.fm.rowconfigure(3, weight=1) self.nb.fm.rowconfigure(5, pad=7) self.nb.add(self.nb.fm, text=os.path.basename(filename)) self.nb.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N) self.nb.fm.area = Text(self.nb.fm) self.nb.fm.area.insert(1.0, f.read()) self.nb.fm.area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N)
class Application(Frame): def __init__(self,master): super().__init__(master) self.toolsThickness = 20 self.rgb = "#%02x%02x%02x" % (255, 255, 255) self.cv = tk.Canvas(self) self.initUI() def initUI(self): self.frame = Frame(self,) self.master.title("Digit Recognition") self.pack(fill=BOTH, expand = True) root.iconbitmap('Logo of Digital Reconigiion.ico') #The canvas self.myCanvas = tk.Canvas(self, width = 800,height = 500,bg="black", borderwidth=5) self.myCanvas.grid(rowspan = 500,columnspan = 800) self.myCanvas.bind("<B1-Motion>", self.draw) self.myCanvas.bind("<Button-1>", self.setPreviousXY) #The Predict Button self.img = tk.PhotoImage(file = "button.png") self.Button1 = Button(self, text = "Predict", width=30, command = self.Predict, image = self.img) self.Button1.grid(row = 80, column = 802) #The Clear Button self.img2 = tk.PhotoImage(file = "button2.png") self.Button2 = Button(self, text = "Clear Screen", width=30, command=self.deleteAll, image = self.img2) self.Button2.grid(row = 120, column = 802) #The dsplay Button self.label2 = Label(self,width =20, text = str, font=("Times New Roman", 16,"bold")) self.label2.grid(row = 160, column = 802) self.var = StringVar(self) self.var.set("Team Members:") #The Dropdown self.box = ttk.Combobox(self, text = "Team:", values = choices, state = "readonly") self.box.set("Team members:") self.box.grid(row = 260, column = 802) self.button5 = Button(self,text = "Go", command = self.click) self.button5.grid(row =265,column = 802) #Display Team info self.label_chosen_variable= Label(self, text = chosen_option) self.label_chosen_variable.grid(row = 270, column = 802) #LOGO self.img3 = PhotoImage(file = 'final_digit.png') self.label = Label(self, image = self.img3) self.label.grid(row = 50, column = 802) def click(self): chosen_option = self.box.get() if chosen_option == "1505205": chosen_option = "Name : CHAMPAK SINHA\nRoll no. : 1505205\nSection : CS3" elif chosen_option == "1505137": chosen_option = "Name : RISHAB\nRoll no. : 1505137\nSection : CS2" elif chosen_option == "1505232": chosen_option = "Name : PRANESH BISWAS\nRoll no. : 1505232\nSection : CS3" elif chosen_option == "1505095": chosen_option = "Name : ANISH HOTA\nRoll no. : 1505095\nSection : CS2" elif chosen_option == "1505361": chosen_option = "Name : ANAND KUMAR\nRoll no. : 1505361\nSection : CS5" self.label_chosen_variable.config(text = chosen_option) def setThickness(self, event): print("Thickness is set to 20") self.toolsThickness = 20 def setPreviousXY(self, event): print("now") self.previousX = event.x self.previousY = event.y def draw(self, event): #line 2 self.myCanvas.create_oval(event.x - self.toolsThickness, event.y - self.toolsThickness, event.x + self.toolsThickness, event.y + self.toolsThickness, fill = self.rgb, outline ="" ) def SAVE(self): print('\n def _snapsaveCanvas(self):') canvas = self._canvas() # Get Window Coordinates of Canvas self.grabcanvas = ImageGrab.grab(bbox=canvas).save("out_snapsave.jpg") print('Screenshot tkinter canvas and saved as "out_snapsave.jpg w/o displaying screenshot."') def _canvas(self): print(' def _canvas(self):') print('self.cv.winfo_rootx() = ', root.winfo_rootx()) print('self.cv.winfo_rooty() = ', root.winfo_rooty()) print('self.cv.winfo_x() =', root.winfo_x()) print('self.cv.winfo_y() =', root.winfo_y()) print('self.cv.winfo_width() = 1000') print('self.cv.winfo_height() =', root.winfo_height()) x=root.winfo_rootx()+5 y=root.winfo_rooty()+5 x1=x+805 y1=y+root.winfo_height()-11 box=(x,y,x1,y1) print('box = ', box) return box def deleteAll(self): self.myCanvas.delete("all") def Predict(self): self.SAVE() call(["python", "script3.py"]) file = open("output.txt","r") str = " Output-> " + file.read() print (str) file.close() self.label2.config(text = str)
def __init__(self, parent=None): super().__init__(parent) parent.bind('<Return>', self.on_accept_button_click) self.pack(side=LEFT, fill=BOTH, expand=True) self.columnconfigure(0, weight=1) self.rowconfigure(1, weight=1) style = AppStyle() style.configure("SELF.TLabel", width=15) style.configure("SELF.TEntry", width=200, padding=5) style.configure("SELF.TMenubutton", width=200, padding=5) # Tab container. notebook = Notebook(self) # Main tab content main = Frame(notebook) main.columnconfigure(1, weight=1) screen_label = Label(main, text="Screen", style="SELF.TLabel") screen_label.grid(row=0, column=0, padx=[10, 0], pady=[10, 0], sticky=W) self.screen_entry = Entry(main, style="SELF.TEntry") self.screen_entry.grid(row=0, column=1, padx=[0, 10], pady=[10, 0], sticky=W + E) width_label = Label(main, text="Width percent", style="SELF.TLabel") width_label.grid(row=1, column=0, padx=[10, 0], pady=[5, 0], sticky=W) self.width_entry = Entry(main, style="SELF.TEntry") self.width_entry.grid(row=1, column=1, padx=[0, 10], pady=[5, 0], sticky=W + E) height_label = Label(main, text="Height percent", style="SELF.TLabel") height_label.grid(row=2, column=0, padx=[10, 0], pady=[5, 0], sticky=W) self.height_entry = Entry(main, style="SELF.TEntry") self.height_entry.grid(row=2, column=1, padx=[0, 10], pady=[5, 0], sticky=W + E) camera_type_label = Label(main, text="Camera type", style="SELF.TLabel") camera_type_label.grid(row=3, column=0, padx=[10, 0], pady=[5, 10], sticky=W) self.camera_type_entry = Entry(main, style="SELF.TEntry") self.camera_type_entry.grid(row=3, column=1, padx=[0, 10], pady=[5, 10], sticky=W + E) # Frames tab content. frames = Frame(notebook) frames.columnconfigure(1, weight=1) frame_interval_label = Label(frames, text="Frame interval", style="SELF.TLabel") frame_interval_label.grid(row=0, column=0, padx=[10, 0], pady=[10, 0], sticky=W) self.frame_interval_entry = Entry(frames, style="SELF.TEntry") self.frame_interval_entry.grid(row=0, column=1, padx=[0, 10], pady=[10, 0], sticky=W + E) frame_rate_label = Label(frames, text="Frame rate", style="SELF.TLabel") frame_rate_label.grid(row=1, column=0, padx=[10, 0], pady=[10, 0], sticky=W) self.frame_rate_entry = Entry(frames, style="SELF.TEntry") self.frame_rate_entry.grid(row=1, column=1, padx=[0, 10], pady=[10, 0], sticky=W + E) frame_count_label = Label(frames, text="Frame count", style="SELF.TLabel") frame_count_label.grid(row=2, column=0, padx=[10, 0], pady=[10, 0], sticky=W) self.frame_count_entry = Entry(frames, style="SELF.TEntry") self.frame_count_entry.grid(row=2, column=1, padx=[0, 10], pady=[10, 0], sticky=W + E) # Cameras tab content. cameras = Frame(notebook) cameras.columnconfigure(1, weight=1) camera_label = Label(cameras, text="Cameras", style="SELF.TLabel") camera_label.grid(row=0, column=0, padx=[10, 0], pady=[10, 0], sticky=W) self.selected_camera_var = StringVar(self) self.selected_camera_var.trace('w', self.on_camera_option_select) self.cameras_options = OptionMenu(cameras, self.selected_camera_var, style="SELF.TMenubutton") self.cameras_options.grid(row=0, column=1, padx=[0, 10], pady=[10, 0], sticky=E) add_cam_button = Button(cameras, text="Add", width=5, command=self.on_add_cam_button_click) add_cam_button.grid(row=0, column=2, padx=[0, 10], pady=[10, 0], sticky=E) delete_cam_button = Button(cameras, text="Delete", width=5, command=self.on_delete_cam_button_click) delete_cam_button.grid(row=0, column=3, padx=[0, 10], pady=[10, 0], sticky=E) self.edit_cam_entry = Entry(cameras, style="SELF.TEntry") self.edit_cam_entry.grid(row=1, column=0, columnspan=3, padx=10, pady=[5, 0], sticky=W + E) edit_cam_button = Button(cameras, text="Edit", width=5, command=self.on_edit_cam_button_click) edit_cam_button.grid(row=1, column=2, columnspan=2, padx=[0, 10], pady=[5, 0], sticky=E) # Add the tabs. notebook.add(main, text="Main") notebook.add(frames, text="Frames") notebook.add(cameras, text="Cameras") notebook.grid(row=0, column=0, columnspan=4, padx=10, pady=10, sticky=W + E) accept_button = Button(self, text="Accept") accept_button.grid(row=1, column=1, padx=[0, 10], sticky=N + E) accept_button.bind("<Button-1>", self.on_accept_button_click) default_button = Button(self, text="Default") default_button.grid(row=1, column=2, padx=[0, 10], sticky=N + E) default_button.bind("<Button-1>", self.on_default_button_click) cancel_button = Button(self, text="Cancel") cancel_button.grid(row=1, column=3, padx=[0, 10], sticky=N + E) cancel_button.bind("<Button-1>", self.on_cancel_button_click) # Load configuration. self.load_config()
def entry_integer(parent, lftext, llimit, ulimit, messtext, out_var): """Integer layout for entry Parameters ---------- parent : str parent handle lftext : str text on LabelFrame llimit : int lower limit ulimit : int upper limit messtext : str message out_var : int tkvar handle Returns ------- integer """ st1 = Style() st1.theme_use('default') st1.configure('brown.TLabelframe', background='#C9B99B') st1.configure('brown.TLabelframe.Label', background='#EDEF77') st1.configure('brown.TLabel', background='#EDEF77') st1.configure('lowr.TLabel', background='lightblue') st1.configure('upr.TLabel', background='red') lf0 = Labelframe(parent, text=lftext, style='brown.TLabelframe') lf0.grid(row=0, column=0, padx=10, pady=10) ulab = Label(lf0, text=str(ulimit)+" upper limit", style='brown.TLabel') ulab.grid(row=0, column=1, padx=10) llab = Label(lf0, text=str(llimit)+" lower limit", style='brown.TLabel') llab.grid(row=2, column=1, padx=10) def end_input(_evt): """limit on integer Parameters ---------- evt : str bind handle Returns ------- None """ print('evt', entsv.get()) ulab['style'] = 'brown.TLabel' llab['style'] = 'brown.TLabel' if llimit < int(entsv.get()) < ulimit: mee_lbl['text'] = "That's OK" out_var.set(int(entsv.get())) elif llimit >= int(entsv.get()): mee_lbl['text'] = "Input below lower limit" llab['style'] = 'lowr.TLabel' else: mee_lbl['text'] = "Input above upper limit" ulab['style'] = 'upr.TLabel' def is_okay(text): """ validation function Parameters ---------- text : str text if allowed Returns ------- boolean """ print(text) if text in("", "-"): return True try: int(text) except ValueError: return False return True vcmd = lf0.register(is_okay) entsv = IntVar() ent0 = Entry(lf0, validate='key', validatecommand=(vcmd, '%P'), textvariable=entsv) ent0.bind("<Return>", end_input) ent0.grid(row=1, column=0, padx=10) ent0.focus() mee_lbl = Label(lf0, text=messtext, style='brown.TLabel') mee_lbl.grid(row=2, column=0, pady=10, padx=10)
class Application(Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.grid(row=0, column=0, sticky="nesw", padx=20, pady=20) self._create_widgets() self._selected_genre = set() self._helper = None self._books = [] self._is_started = False def _add_titles_to_listbox(self): books = [] self.books.delete(0, tk.END) for genre in sorted(self._selected_genre): books.extend(self._helper.get_books_in_genres(self._books, genre)) books.sort() self.books.insert(tk.END, *books) def _create_widgets(self): def _create_label(frame, text, coordinates): label = Label(frame, text=text, justify=tk.LEFT, anchor="w", width=20) label.grid(row=coordinates[0], column=coordinates[1]) _create_label(self, "Output Folder:", (0, 0)) self.output_path = Entry(self) self.output_path.grid(row=1, column=0, columnspan=2, sticky="ew", pady=(0, 15)) _create_label(self, "Available Genres:", (2, 0)) _create_label(self, "Books to Download:", (2, 1)) self.genres = tk.Listbox(self, selectmode="multiple") def on_genre_select(evt): indices = evt.widget.curselection() self._selected_genre.clear() for index in indices: value = evt.widget.get(index) self._selected_genre.add(value) self._add_titles_to_listbox() self.genres.bind("<<ListboxSelect>>", on_genre_select) self.genres["height"] = 20 self.genres["width"] = 30 self.genres.grid(row=3, column=0, padx=(0, 10)) self.books = tk.Listbox(self) self.books["height"] = 20 self.books["width"] = 30 self.books.grid(row=3, column=1, padx=(10, 0)) self._pdf = tk.IntVar(value=1) self.pdf = Checkbutton(self, text="PDF", variable=self._pdf) self.pdf.grid(row=4, column=0, pady=10) self._epub = tk.IntVar(value=1) self.epub = Checkbutton(self, text="EPUB", variable=self._epub) self.epub.grid(row=4, column=1, pady=10) self._status_text = tk.StringVar() self.status = Label(self, textvariable=self._status_text) self.status.grid(row=5, column=0, columnspan=2) self._current_bar_value = tk.IntVar(value=0) self.bar = Progressbar(self, variable=self._current_bar_value) self._download_btn = tk.StringVar() db = Button(self, textvariable=self._download_btn) db["command"] = self.start_download self._download_btn.set("Download") db.grid(row=7, column=0, columnspan=2, pady=10) LOG.info("All widgets created.") def set_output_folder(self, path): if self.output_path: self.output_path.insert(tk.END, path) def populate_genres(self, genres): self._genre_mapping = genres for genre in sorted(genres): self.genres.insert(tk.END, genre) LOG.info("Added {} genres".format(len(genres))) def start_download(self): titles = self.books.get(0, tk.END) if not titles: self._status_text.set("Please select a genre to continue") return self._is_started = not self._is_started self._toggle_state(not self._is_started) if self._is_started: books = self._books.copy() for book in books.iterrows(): if book[1]["Book Title"] not in titles: books = books.drop(index=book[0]) LOG.info("Starting to download {} books".format(len(books))) self.bar["maximum"] = len(books) self._helper.STOP_FLAG = False self._download_thread = threading.Thread( daemon=True, target=self._helper.download_books, args=(books, self.output_path.get()), kwargs={ "pdf": self._pdf.get(), "epub": self._epub.get(), "verbose": True, "label": self._status_text, "progressbar": self._current_bar_value, }, ) self._download_thread.start() self._thread_check_in(self._download_thread) else: self._helper.STOP_FLAG = True def _thread_check_in(self, thread, period=100): if thread.isAlive(): self.master.after(period, self._thread_check_in, thread, period) else: self._is_started = False self._toggle_state(True) def _toggle_state(self, enable): state = tk.NORMAL if enable else tk.DISABLED text = "Download" if enable else "Stop" status = "" if enable else "Starting downloader ..." self.output_path.config(state=state) self.genres.config(state=state) self.books.config(state=state) self.pdf.config(state=state) self.epub.config(state=state) self._download_btn.set(text) self._status_text.set(status) if enable: self.bar.grid_remove() else: self.bar.grid(row=6, column=0, columnspan=2, pady=10, sticky="ew")
class signUpPage(Frame): ''' The user is taken to this Frame if they choose to sign up this class implements the Frame Class in Tkinter and contains the required functions that will allow it to work well in this project ''' def __init__(self, parent, main, **kw): Frame.__init__(self, parent, **kw) self.main = main self.label_head = Label(text='Sign Up Page', font=MED_FONT) self.l_user = Label(text='Username') self.user = Entry(text='must have atleast 5 chars') self.l_pass = Label(text='Password') self.l_pass2 = Label(text='re-enter') self.password = Entry(show='*') self.password2 = Entry(show='*') self.sign_up_b = Button(text='Sign Up', command=lambda: self.sign_up(main)) self.back_b = Button( text='Back', command=lambda: self.main.show_frame(LOGIN_PAGE, SIGN_UP_PAGE)) self.age = BooleanVar() self.age_c = Checkbutton(text='Are you above 16 years of age', variable=self.age, onvalue=True, offvalue=False) self.balance = BooleanVar() self.balance_c = Checkbutton( text='Do you have 10000 rupees in \nyour bank account', variable=self.balance, onvalue=True, offvalue=False) def showItems(self, main): self.label_head.grid(column=0, row=0, columnspan=2) self.l_user.grid(column=0, row=1) self.user.grid(column=1, row=1) self.l_pass.grid(column=0, row=2) self.l_pass2.grid(column=0, row=3) self.password.grid(column=1, row=2) self.password2.grid(column=1, row=3) self.age_c.grid(column=0, columnspan=2, row=4) self.balance_c.grid(column=0, columnspan=2, row=5) self.sign_up_b.grid(column=0, row=6, columnspan=2) self.back_b.grid(column=0, row=7, columnspan=2) def hideItems(self, main): self.label_head.grid_forget() self.l_user.grid_forget() self.user.grid_forget() self.l_pass.grid_forget() self.l_pass2.grid_forget() self.password.grid_forget() self.password2.grid_forget() self.sign_up_b.grid_forget() self.back_b.grid_forget() self.age_c.grid_forget() self.balance_c.grid_forget() def sign_up(self, main): ''' Similar to the login check function it does the necessary checks to make sure that a person actually is above 18 (not really) and has the required amount of money to open an account on this platform also it creates pop ups when ever an exceptional circumstance is reached ''' password1 = self.password.get() password2 = self.password2.get() username = self.user.get() bool1 = username not in main.users_dict.keys() bool2 = (password1 == password2) bool3 = len(password1) >= 5 bool4 = username == 'admin' bool5 = self.age.get() bool6 = self.balance.get() if not bool1: num = str(randint(100, 999)) showinfo(message='Username already exists, try: ' + username + num) self.password.delete(0, END) self.password2.delete(0, END) elif not bool2: showinfo(message='Passwords dont match') self.password.delete(0, END) self.password2.delete(0, END) elif not bool3: showinfo(message='Password must be more than 5 characters') self.password.delete(0, END) self.password2.delete(0, END) elif bool4: showinfo(message='Please don\'t use that username it is reserved') elif not bool5: showinfo(message='You must be 16 years or older to join') elif not bool6: showinfo(message='You need to have 10000 to create an account') else: buff = [] for name in main.shares_dict.keys(): temp = {} temp['name'] = name temp['tot_owned'] = '0' temp['money_spent'] = '0' buff.append(temp) self.main.users_dict[username] = buff self.main.pass_dict[username] = bytes(password1, 'utf-8') k = getData.key() self.main.pass_dict2[username] = encode(bytes(password1, 'utf-8')) self.main.accounts[username] = { 'balance': str(10**4), 'profit': '0' } self.main.present_user = username self.main.p_user_dict = self.main.users_dict[username] self.main.login = True self.main.show_frame(VIEW_STOCK, SIGN_UP_PAGE) self.password.delete(0, END) self.password2.delete(0, END) self.user.delete(0, END)
class StringEntry: """String class for entry added colour, change state integer and float classes added Parameters ---------- parent : str parent handle lf_text : str text on LabelFrame mess_text : str message def_inp : str default text colour : str frame colour mod : str enable or disable state switch Returns ------- string """ def __init__(self, parent, lf_text, mess_text, def_inp="", colour='brown', mod=False): self.parent = parent self.lf_text = lf_text self.mess_text = mess_text self.mod = mod self.ent0 = None # for entry self.cb_opt = None # for check option self.out_var = StringVar() self.out_var.set(def_inp) self.farbe = farbe = { 'blue': 'light blue', 'brown': 'brown1', 'green': 'light green', 'pink': '#EAAFBF' } colour = colour if colour in farbe else 'brown' self.colour = colour st1 = Style() st1.theme_use('default') st1.configure(colour + '.TLabelframe', background='#C9B99B') st1.configure(colour + '.TLabelframe.Label', background=farbe[colour]) st1.configure(colour + '.TCheckbutton', background=farbe[colour]) st1.configure('brown.TLabel', background='#EDEF77') self.construct() def construct(self): """construct of LabelFrame and message Parameters ---------- None Returns ------- None """ self.lf1 = Labelframe(self.parent, text=self.lf_text, style=self.colour + '.TLabelframe') self.lf1.grid(column=0, row=0, padx=10, pady=10) self.messlbl = Label(self.lf1, text=self.mess_text, style='brown.TLabel') self.messlbl.grid(row=2, column=0, pady=10, padx=10) self.make_entry() def make_entry(self): """construct of Entry Parameters ---------- None Returns ------- None """ vcmd = self.lf1.register(self.is_okay) self.ent0 = ent0 = Entry(self.lf1, validate='key', validatecommand=(vcmd, '%P', '%S', '%i'), textvariable=self.out_var) ent0.bind("<Return>", self.end_input) ent0.grid(row=1, column=0, padx=10) ent0.focus() if self.mod in (True, False): self.modify() def modify(self): """construct of state switch Parameters ---------- None Returns ------- None """ lf_text = self.lf_text # entry disabled until checkbox is ticked self.cb_opt = Checkbutton(self.lf1, command=self.toggle_opt, style=self.colour + '.TCheckbutton') self.lf1['labelwidget'] = self.cb_opt if self.mod: self.ent0.state(['!disabled']) self.cb_opt.state(['!selected']) self.cb_opt['text'] = lf_text + '\n Check to prevent editing ' self.ent0.focus() else: self.ent0.state(['disabled']) self.cb_opt.state(['selected']) self.cb_opt['text'] = lf_text + '\n Check to modify ' def toggle_opt(self): """state switch logic Parameters ---------- None Returns ------- None """ lf_text = self.lf_text # state of entry controlled # by the state of the check button in Option frame label widget if self.cb_opt.instate(['selected']): self.ent0.state(['disabled']) self.cb_opt['text'] = lf_text + '\n Check to modify ' else: self.ent0.state(['!disabled']) # enable option self.cb_opt['text'] = lf_text + '\n Check to prevent editing ' self.ent0.focus() def end_input(self, _evt): """limit on string Parameters ---------- evt : str bind handle Returns ------- None """ # print('evt',self.ensv.get()) if len(self.out_var.get()) > 5: self.messlbl['text'] = "That's OK" else: self.messlbl['text'] = "Should be at least 6 characters long" def is_okay(self, text, inp, ind): """ validation function Parameters ---------- text : str text if allowed inp : str current input Returns ------- boolean """ ind = int(ind) print(ind) if (inp.isalnum() or inp in (",", ".", "'", " ")) and ind > 0: return True else: return bool((text.isupper() or text == "") and ind == 0)
class DatabaseContent: def __init__(self, root): self.master = Frame(master=root) self.labelframe = None self.btn = None self.db_max = None self.db_min = None self.db_current = None self.text_field = None self.field_width = 40 self.field_height = 10 self.data_ing = DataProcessing() self.db = DB() self.config_file = './res/config/dbconfig.ini' def on_create_labelframe(self, name, col, row, px, py, pos): self.labelframe = LabelFrame(master=self.master, text=name) self.labelframe.grid(column=col, row=row, padx=px, pady=py, sticky=pos) def add_btn(self, col, row, colpad, rowpad): self.btn = sbutton(root=self.labelframe).get_btn() self.btn.configure(text='Load Content') self.btn.configure(command=self.on_writing_in_the_field) MessageTip(gui=self.btn, msg='Click here to pull the db') self.btn.grid(column=col, row=row, padx=rowpad, pady=colpad, sticky='W') def on_create_label(self, label_name, col, row, colpad, rowpad, pos): lab = Label(master=self.labelframe, text=label_name) lab.grid(column=col, row=row, padx=colpad, pady=rowpad, sticky=pos) def on_create_field(self, col, row, px, py, cspan): self.text_field = scrollT(master=self.labelframe, width=self.field_width, height=self.field_height, wrap=WORD) self.text_field.grid(column=col, row=row, padx=px, pady=py, columnspan=cspan) def on_writing_in_the_field(self): if self.btn['text'] == 'Load Content': self.btn.configure(text='Loading...') self.btn.configure(bg='#ffa500') print(self.btn['text'], self.btn['state']) self.write_all() time.sleep(.5) self.btn.configure(text='Load Content') self.btn.configure(bg='#00bfff') def format_date(self, d): return d.strftime('%Y %b %d') def write_all(self): print('Inhalt der Datenbank( aktuell ): \n') self.text_field.get(1.0, END) print('Inhalt nicht leer, wird gelöscht...') self.text_field.delete(1.0, END) connection = self.db.in_connecting(self.config_file) df = self.db.read_db_content(connection) id = df['id'].values strom = df['strom'].values datum = df['datum'].values m = df.min() print("MIN IN DF: ", m['strom'], " date: ", m['datum']) print("STATISTIK:") self.print_db_stats(df) for i, s, d in zip(id, strom, datum): self.text_field.insert(INSERT, ' ' + str(i) + '\t\t' + str(s) + "\t " + str( self.format_date(d)) + '\n') print(i, "\t", s, "\t", d) time.sleep(.2) def print_db_stats(self, df): new_df = self.data_ing.on_getting_data_from_server(df) min, max, current = new_df.min(), new_df.max(), self.data_ing.select_current_value(new_df) df_min = new_df[new_df['strom'] == min['strom']] df_max = new_df[new_df['strom'] == max['strom']] text1 = ' {} Watt \t\t Datum: {}, den {} {} {}'.format(df_min['strom'][0], df_min['wochentag'][0], df_min['tag'][0], df_min.index[0].strftime('%b'), df_min['jahr'][0]) text2 = ' {} Watt \t\t Datum: {}, den {} {} {}'.format(df_max['strom'][0], df_max['wochentag'][0], df_max['tag'][0], df_max.index[0].strftime('%b'), df_max['jahr'][0]) text3 = ' {} Watt \t\t Datum: {}, den {} {} {}'.format(current['strom'][0], current['wochentag'][0], current['tag'][0], current.index[0].strftime('%b'), current['jahr'][0]) self.db_min = Label(master=self.labelframe, text=text1) self.db_min.grid(column=3, row=0, padx=8, pady=8, sticky='N', columnspan=3) self.db_max = Label(master=self.labelframe, text=text2) self.db_max.grid(column=3, row=1, padx=8, pady=8, sticky='N', columnspan=3) self.db_current = Label(master=self.labelframe, text=text3) self.db_current.grid(column=3, row=2, padx=8, pady=8, sticky='N', columnspan=3)
def on_create_label(self, label_name, col, row, colpad, rowpad, pos): lab = Label(master=self.labelframe, text=label_name) lab.grid(column=col, row=row, padx=colpad, pady=rowpad, sticky=pos)
def initialize(self): """ Initialize all the tkinter objects of the frame """ self.title('RGINE Data Analysis') # frame top_frame = tkinter.Frame(self) top_frame.pack(side=tkinter.TOP, fill=tkinter.X) data_frame = tkinter.Frame(top_frame) data_frame.pack(side=tkinter.TOP, fill=tkinter.X) data_frame_csv = tkinter.Frame(data_frame, borderwidth=2, relief=tkinter.GROOVE) data_frame_csv.pack(side=tkinter.LEFT, fill=tkinter.X, padx=5, pady=5) data_frame_data = tkinter.Frame(data_frame, borderwidth=2, relief=tkinter.GROOVE) data_frame_data.pack(side=tkinter.RIGHT, fill=tkinter.X, padx=5, pady=5) plot_frame = tkinter.Frame(top_frame, borderwidth=2, relief=tkinter.GROOVE) plot_frame.pack(side=tkinter.LEFT, fill=tkinter.X, padx=5, pady=5) action_frame = tkinter.Frame(top_frame, borderwidth=2, relief=tkinter.GROOVE) action_frame.pack(side=tkinter.RIGHT, fill=tkinter.X, padx=5, pady=5) # button load_button = Button(data_frame_csv, text="Load CSV file", command=self.load_data, width=20) load_button.grid(row=1, column=1, columnspan=1, rowspan=1, padx=5, pady=5) refresh_file_button = Button(data_frame_csv, text="Refresh CSV file", command=self.refresh_file, width=20) refresh_file_button.grid(row=1, column=2, padx=5, pady=5) display_button = Button(data_frame_data, text="Display data", command=self.display_data, width=20) display_button.grid(row=1, column=3, padx=5, pady=5) save_button = Button(data_frame_data, text="Save data", command=self.save_data, width=20) save_button.grid(row=1, column=4, padx=5, pady=5) clear_button = Button(data_frame_data, text="Clear data", command=self.clear_data, width=20) clear_button.grid(row=1, column=5, padx=5, pady=5) add_button = Button(action_frame, text="Add plot", command=self.add_plot, width=20) add_button.grid(row=1, column=3, rowspan=1, padx=5, pady=5) function_button = Button(action_frame, text="Plot math function", command=self.add_plot_function, width=20) function_button.grid(row=2, column=3, columnspan=1, rowspan=1, padx=5, pady=5) add_plot_button = Button(plot_frame, text="Add Plot frame", command=self.add_plot_frame, width=20) add_plot_button.grid(row=1, column=1, columnspan=1, rowspan=1, padx=5, pady=5) clear_plot_button = Button(plot_frame, text="Clear all plots", command=self.clear_all_plots, width=20) clear_plot_button.grid(row=1, column=2, columnspan=1, rowspan=1, padx=5, pady=5) remove_plot_button = Button(plot_frame, text="Remove all plots", command=self.remove_all_plots, width=20) remove_plot_button.grid(row=2, column=2, columnspan=1, rowspan=1, padx=5, pady=5) # label label_x = Label(action_frame, text="Choose X axis data: ", width=20) label_x.grid(row=1, column=1, padx=5, pady=5) label_y = Label(action_frame, text="Choose Y axis data: ", width=20) label_y.grid(row=2, column=1, padx=5, pady=5) # combo self.__plot_frame_combo = Combobox( plot_frame, textvariable=self.__plot_frame_select_combo, values=self.__plot_frame_list, state='readonly', postcommand=lambda: self.__plot_frame_combo.configure( values=self.__plot_frame_list), width=17) self.__plot_frame_combo.current(0) self.__plot_frame_combo.grid(row=2, column=1, padx=5, pady=5) data_select_combo1 = tkinter.StringVar() self.__variable1_combo = Combobox( action_frame, textvariable=data_select_combo1, values=self.__data_manager.get_field_names(), state='readonly', postcommand=lambda: self.__variable1_combo.configure( values=self.__data_manager.get_field_names()), width=19) self.__variable1_combo.grid(row=1, column=2, padx=5, pady=5) data_select_combo2 = tkinter.StringVar() self.__variable2_combo = Combobox( action_frame, textvariable=data_select_combo2, values=self.__data_manager.get_field_names(), state='readonly', postcommand=lambda: self.__variable2_combo.configure( values=self.__data_manager.get_field_names()), width=19) self.__variable2_combo.grid(row=2, column=2, padx=5, pady=5) # menu frame_menu = tkinter.Menu(self) help_menu = tkinter.Menu(frame_menu, tearoff=0) help_menu.add_command(label="Logger", command=self.open_logger_command) help_menu.add_separator() help_menu.add_command(label="How to", command=self.how_to_command) help_menu.add_command(label="About", command=self.about_command) frame_menu.add_cascade(label="Help", menu=help_menu) self.config(menu=frame_menu)
class HelpSource(Query): "Get menu name and help source for Help menu." # Used in ConfigDialog.HelpListItemAdd/Edit, (941/9) def __init__(self, parent, title, *, menuitem='', filepath='', used_names={}, _htest=False, _utest=False): """Get menu entry and url/local file for Additional Help. User enters a name for the Help resource and a web url or file name. The user can browse for the file. """ self.filepath = filepath message = 'Name for item on Help menu:' super().__init__(parent, title, message, text0=menuitem, used_names=used_names, _htest=_htest, _utest=_utest) def create_extra(self): "Add path widjets to rows 10-12." frame = self.frame pathlabel = Label(frame, anchor='w', justify='left', text='Help File Path: Enter URL or browse for file') self.pathvar = StringVar(self, self.filepath) self.path = Entry(frame, textvariable=self.pathvar, width=40) browse = Button(frame, text='Browse', width=8, command=self.browse_file) self.path_error = Label(frame, text=' ', foreground='red', font=self.error_font) pathlabel.grid(column=0, row=10, columnspan=3, padx=5, pady=[10, 0], sticky=W) self.path.grid(column=0, row=11, columnspan=2, padx=5, sticky=W + E, pady=[10, 0]) browse.grid(column=2, row=11, padx=5, sticky=W + S) self.path_error.grid(column=0, row=12, columnspan=3, padx=5, sticky=W + E) def askfilename(self, filetypes, initdir, initfile): # htest # # Extracted from browse_file so can mock for unittests. # Cannot unittest as cannot simulate button clicks. # Test by running htest, such as by running this file. return filedialog.Open(parent=self, filetypes=filetypes)\ .show(initialdir=initdir, initialfile=initfile) def browse_file(self): filetypes = [("HTML Files", "*.htm *.html", "TEXT"), ("PDF Files", "*.pdf", "TEXT"), ("Windows Help Files", "*.chm"), ("Text Files", "*.txt", "TEXT"), ("All Files", "*")] path = self.pathvar.get() if path: dir, base = os.path.split(path) else: base = None if platform[:3] == 'win': dir = os.path.join(os.path.dirname(executable), 'Doc') if not os.path.isdir(dir): dir = os.getcwd() else: dir = os.getcwd() file = self.askfilename(filetypes, dir, base) if file: self.pathvar.set(file) item_ok = SectionName.entry_ok # localize for test override def path_ok(self): "Simple validity check for menu file path" path = self.path.get().strip() if not path: #no path specified self.showerror('no help file path specified.', self.path_error) return None elif not path.startswith(('www.', 'http')): if path[:5] == 'file:': path = path[5:] if not os.path.exists(path): self.showerror('help file path does not exist.', self.path_error) return None if platform == 'darwin': # for Mac Safari path = "file://" + path return path def entry_ok(self): "Return apparently valid (name, path) or None" self.path_error['text'] = '' name = self.item_ok() path = self.path_ok() return None if name is None or path is None else (name, path)
def __init__(self, parent, pipeline_name, annotation, *args, **kwargs): self.global_info = kwargs.pop('global_info') Frame.__init__(self, parent, *args, **kwargs) self.parameters = [] self.pipeline_name = pipeline_name #pipeline_name = kwargs['pipeline_name'] pipepanel = self #pipeline_name = self.pfamily.get() #parent = (*args)[0] parent.add(pipepanel, text=pipeline_name) parent.pack(side=LEFT, fill=BOTH, padx=10, pady=10, expand=YES) datapath = StringVar() workpath = StringVar() targetspath = StringVar() self.datapath = datapath self.workpath = workpath self.targetspath = targetspath self.annotation = annotation self.genome = annotation.get() self.nends = -1 self.n_set_data_directory = 0 l = Label(pipepanel, text="Data Directory:") l.grid(row=1, column=1, sticky=W, padx=0, pady=10) l = Label(pipepanel, text="Working Directory:") l.grid(row=3, column=1, sticky=W, padx=0, pady=10) self.dry_button = dry_button = Button(self, text="Dry Run", command=self.dryrun, state='active') dry_button.grid(row=4, column=4, sticky=E) self.run_button = run_button = Button(self, text="Run", command=self.runslurm, state='active') run_button.grid(row=4, column=5) data_entry = Entry( pipepanel, bd=2, width=50, #bg = entryBgColor, #fg = entryFgColor, textvariable=datapath, state='normal') self.work_entry = work_entry = Entry( pipepanel, bd=2, width=50, #bg=entryBgColor, #fg=entryFgColor, textvariable=workpath, state='normal') data_entry.grid(row=1, column=2, columnspan=3) self.data_button = data_button = Button( pipepanel, text="Open Directory", command=self.set_data_directory) data_button.grid(row=1, column=5) data_count_label = Label(pipepanel, text="FastQ files Found:") data_count_label.grid(row=2, column=1) data_count = Label(pipepanel, text="0") data_count.grid(row=2, column=2) self.data_count = data_count work_entry.grid(row=3, column=2, columnspan=3) work_sel_button = Button(pipepanel, text="Open Directory", command=self.sel_work_dir) work_sel_button.grid(row=3, column=5) self.work_button = work_button = Button(pipepanel, text="Initialize Directory", command=self.init_work_dir) work_button.grid(row=4, column=3) work_button.config(state="active") #( "disabled" )
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): Style().configure("TButton", padding=(0, 5, 0, 5), width=8, font='serif 10') self.screenvar = StringVar() self.screenstr = '' self.screen = Label(self, textvariable=self.screenvar, justify=RIGHT) self.cls = Button(text="Temizle", command=self.clsButtonEvent) self.bck = Button(text="Sil", command=self.backButtonEvent) self.lbl = Button() self.clo = Button(text="Kapat", command=self.closeButtonEvent) self.sev = Button(text="7", command=self.number7ButtonEvent) self.eig = Button(text="8", command=self.number8ButtonEvent) self.nin = Button(text="9", command=self.number9ButtonEvent) self.div = Button(text="/", command=self.divButtonEvent) self.fou = Button(text="4", command=self.number4ButtonEvent) self.fiv = Button(text="5", command=self.number5ButtonEvent) self.six = Button(text="6", command=self.number6ButtonEvent) self.mul = Button(text="*", command=self.mulButtonEvent) self.one = Button(text="1", command=self.number1ButtonEvent) self.two = Button(text="2", command=self.number2ButtonEvent) self.thr = Button(text="3", command=self.number3ButtonEvent) self.mns = Button(text="-", command=self.minButtonEvent) self.zer = Button(text="0", command=self.number0ButtonEvent) self.dot = Button(text=".", command=self.dotButtonEvent) self.equ = Button(text="=", command=self.eqButtonEvent) self.pls = Button(text="+", command=self.plusButtonEvent) # self.UIWithPack() # Pack Layout self.UIWithGrid() # Grid Layout self.pack() def UIWithPack(self): frame1 = Frame(self) frame2 = Frame(self) frame3 = Frame(self) frame4 = Frame(self) frame5 = Frame(self) self.screen.pack(fill=X) for frame in(frame1, frame2, frame3, frame4, frame5): frame.pack() for widget_1 in (self.cls, self.bck, self.lbl, self.clo): widget_1.pack(in_=frame1, side=LEFT) for widget_1 in (self.sev, self.eig, self.nin, self.div): widget_1.pack(in_=frame2, side=LEFT) for widget_1 in (self.fou, self.fiv, self.six, self.mul): widget_1.pack(in_=frame3, side=LEFT) for widget_1 in (self.one, self.two, self.thr, self.mns): widget_1.pack(in_=frame4, side=LEFT) for widget_1 in (self.zer, self.dot, self.equ, self.pls): widget_1.pack(in_=frame5, side=LEFT) def UIWithGrid(self): self.columnconfigure(0, pad=3) self.columnconfigure(1, pad=3) self.columnconfigure(2, pad=3) self.columnconfigure(3, pad=3) self.rowconfigure(0, pad=3) self.rowconfigure(1, pad=3) self.rowconfigure(2, pad=3) self.rowconfigure(3, pad=3) self.rowconfigure(4, pad=3) self.screen.grid(row=0, columnspan=4, sticky=W+E) self.cls.grid(in_=self, row=1, column=0) self.bck.grid(in_=self, row=1, column=1) self.lbl.grid(in_=self, row=1, column=2) self.clo.grid(in_=self, row=1, column=3) self.sev.grid(in_=self, row=2, column=0) self.eig.grid(in_=self, row=2, column=1) self.nin.grid(in_=self, row=2, column=2) self.div.grid(in_=self, row=2, column=3) self.fou.grid(in_=self, row=3, column=0) self.fiv.grid(in_=self, row=3, column=1) self.six.grid(in_=self, row=3, column=2) self.mul.grid(in_=self, row=3, column=3) self.one.grid(in_=self, row=4, column=0) self.two.grid(in_=self, row=4, column=1) self.thr.grid(in_=self, row=4, column=2) self.mns.grid(in_=self, row=4, column=3) self.zer.grid(in_=self, row=5, column=0) self.dot.grid(in_=self, row=5, column=1) self.equ.grid(in_=self, row=5, column=2) self.pls.grid(in_=self, row=5, column=3) def number1ButtonEvent(self): self.screenstr += '1' self.screenvar.set(self.screenstr) def number2ButtonEvent(self): self.screenstr += '2' self.screenvar.set(self.screenstr) def number3ButtonEvent(self): self.screenstr += '3' self.screenvar.set(self.screenstr) def number4ButtonEvent(self): self.screenstr += '4' self.screenvar.set(self.screenstr) def number5ButtonEvent(self): self.screenstr += '5' self.screenvar.set(self.screenstr) def number6ButtonEvent(self): self.screenstr += '6' self.screenvar.set(self.screenstr) def number7ButtonEvent(self): self.screenstr += '7' self.screenvar.set(self.screenstr) def number8ButtonEvent(self): self.screenstr += '8' self.screenvar.set(self.screenstr) def number9ButtonEvent(self): self.screenstr += '9' self.screenvar.set(self.screenstr) def number0ButtonEvent(self): self.screenstr += '0' self.screenvar.set(self.screenstr) def divButtonEvent(self): self.screenstr += '/' self.screenvar.set(self.screenstr) def mulButtonEvent(self): self.screenstr += '*' self.screenvar.set(self.screenstr) def minButtonEvent(self): self.screenstr += '-' self.screenvar.set(self.screenstr) def plusButtonEvent(self): self.screenstr += '+' self.screenvar.set(self.screenstr) def closeButtonEvent(self): self.parent.destroy() def backButtonEvent(self): self.screenstr = self.screenstr[:-1] self.screenvar.set(self.screenstr) def dotButtonEvent(self): self.screenstr += '.' self.screenvar.set(self.screenstr) def eqButtonEvent(self): self.screenstr = str(eval(self.screenstr)) self.screenvar.set(self.screenstr) def clsButtonEvent(self): self.screenstr = '' self.screenvar.set(self.screenstr)
class CustomRun(Query): """Get settings for custom run of module. 1. Command line arguments to extend sys.argv. 2. Whether to restart Shell or not. """ # Used in runscript.run_custom_event def __init__(self, parent, title, *, cli_args=[], _htest=False, _utest=False): """cli_args is a list of strings. The list is assigned to the default Entry StringVar. The strings are displayed joined by ' ' for display. """ message = 'Command Line Arguments for sys.argv:' super().__init__(parent, title, message, text0=cli_args, _htest=_htest, _utest=_utest) def create_extra(self): "Add run mode on rows 10-12." frame = self.frame self.restartvar = BooleanVar(self, value=True) restart = Checkbutton(frame, variable=self.restartvar, onvalue=True, offvalue=False, text='Restart shell') self.args_error = Label(frame, text=' ', foreground='red', font=self.error_font) restart.grid(column=0, row=10, columnspan=3, padx=5, sticky='w') self.args_error.grid(column=0, row=12, columnspan=3, padx=5, sticky='we') def cli_args_ok(self): "Validity check and parsing for command line arguments." cli_string = self.entry.get().strip() try: cli_args = shlex.split(cli_string, posix=True) except ValueError as err: self.showerror(str(err)) return None return cli_args def entry_ok(self): "Return apparently valid (cli_args, restart) or None." cli_args = self.cli_args_ok() restart = self.restartvar.get() return None if cli_args is None else (cli_args, restart)
class IntegerEntry(StringEntry): """Integer class for entry Parameters ---------- parent : str parent handle lf_text : str text on LabelFrame mess_text : str message l_limit : int lower limit u_limit : int upper limit def_inp : str default text colour : str frame colour mod : str enable or disable state switch Returns ------- integer """ def __init__(self, parent, lf_text, mess_text, l_limit, u_limit, def_inp="", colour='brown', mod=False): self.parent = parent self.lf_text = lf_text self.mess_text = mess_text self.mod = mod self.colour = colour StringEntry.__init__(self, parent, lf_text, mess_text, def_inp, colour, mod) self.l_limit = l_limit self.u_limit = u_limit self.out_var = IntVar() self.out_var.set(def_inp) self.farbe = farbe = { 'blue': 'light blue', 'brown': '#EDEF77', 'green': 'light green', 'pink': '#EAAFBF' } colour = colour if colour in farbe else 'brown' self.colour = colour st1 = Style() st1.theme_use('default') st1.configure(colour + '.TLabelframe', background='#C9B99B') st1.configure(colour + '.TLabelframe.Label', background=farbe[colour]) st1.configure(colour + '.TCheckbutton', background=farbe[colour]) st1.configure('brownn.TLabel', background='#EDEF77') st1.configure('lowr.TLabel', background='lightblue') st1.configure('upr.TLabel', background='red') self.construct() self.limits() def limits(self): """limit logic Parameters ---------- None Returns ------- None """ self.ulab = Label(self.lf1, text=str(self.u_limit) + " upper limit", style='brown.TLabel') self.ulab.grid(row=0, column=1, padx=10) self.llab = Label(self.lf1, text=str(self.l_limit) + " lower limit", style='brown.TLabel') self.llab.grid(row=2, column=1, padx=10) self.make_entry() def end_input(self, _evt): """limit on integer Parameters ---------- evt : str bind handle Returns ------- None """ self.ulab['style'] = 'brown.TLabel' self.llab['style'] = 'brown.TLabel' if self.l_limit < int(self.out_var.get()) < self.u_limit: self.messlbl['text'] = "That's OK" elif self.l_limit >= int(self.out_var.get()): self.messlbl['text'] = "Input below or at lower limit" self.llab['style'] = 'lowr.TLabel' else: self.messlbl['text'] = "Input above or at upper limit" self.ulab['style'] = 'upr.TLabel' def is_okay(self, text, inp, ind): """ validation function Parameters ---------- text : str text if allowed inp : str current input Returns ------- boolean """ if text in ("", "-"): return True try: int(text) except ValueError: return False return True