def setupSelectedFilterType(self, selectedFilterFileName, filterType): groupDesctiptionNotebook = Notebook(self) groupDesctiptionNotebook.grid(row=3, column=0, columnspan=4, sticky=E + W) groupNameList = jsonHelper.getAllGroups() groupDescriptionFrameList = [] for groupName in groupNameList: groupDescriptionFrame = GroupDescriptionCheckboxFrame(groupDesctiptionNotebook, groupName) # get selected filters for groupname selectedFilterList = [] if filterType == "Head": selectedFilterList = jsonHelper.getHeadFiltersListForGroup(groupName) else: selectedFilterList = jsonHelper.getJawFiltersListForGroup(groupName) isEnabled = selectedFilterFileName in selectedFilterList groupDescriptionFrame.enableCheckButtonInt.set(isEnabled) groupDescriptionFrameList.append(groupDescriptionFrame) groupDescriptionFrame.pack(fill=BOTH, expand=True) groupDesctiptionNotebook.add(groupDescriptionFrame, text=groupName) Button( self, text="Apply & Close", relief=RAISED, command=lambda: self.applyFilterTypeButtonPressed( selectedFilterFileName, groupDescriptionFrameList, filterType ), ).grid(row=4, column=1, columnspan=1, sticky=S + E)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) tool_tabs = Notebook(self.tk_object) tool_tabs.pack(fill='x') with self.attribute_lock: self._tool_tabs = tool_tabs self.window_manager = WindowManager()
class TestWindow(Tk): def __init__(self): super().__init__() # Set the window parameters self.wm_title("Test Window") self.wm_geometry("800x600") self._nb = Notebook(self) self._nb.pack(fill=BOTH, expand=1) # Add the ScrollableTreeview self.STV = ScrollableTreeview( self._nb, columns=('first','second'), headers={ '#0':'Default', 'first':{'text':'First'}, 'second':{'text':'Second'} } ) self._nb.add(self.STV, text="Scrollable Treeview") iid = self.STV.insert('', 'end', text='Root Node') self.STV.insert(iid, 'end', text='Child 1') self.STV.insert(iid, 'end', text='Child 2')
def setupSelectedModuleConfig(self, selectedModuleFileName): groupDesctiptionNotebook = Notebook(self) groupDesctiptionNotebook.grid(row=3, column=0, columnspan=4, sticky=E + W) groupNameList = jsonHelper.getAllGroups() groupDescriptionFrameList = [] for groupName in groupNameList: groupDescriptionFrame = GroupDescriptionCheckboxFrame(groupDesctiptionNotebook, groupName) modulesForGroupList = jsonHelper.getModuleListForGroup(groupName) isEnabled = selectedModuleFileName in modulesForGroupList groupDescriptionFrame.enableCheckButtonInt.set(isEnabled) groupDescriptionFrameList.append(groupDescriptionFrame) groupDescriptionFrame.pack(fill=BOTH, expand=True) groupDesctiptionNotebook.add(groupDescriptionFrame, text=groupName) Button( self, text="Apply & Close", relief=RAISED, command=lambda: self.applyModuleButtonPressed(selectedModuleFileName, groupDescriptionFrameList), ).grid(row=4, column=1, columnspan=1, sticky=S + E)
def __init__(self, parent): Notebook.__init__(self, parent, style='Type.TNotebook') logger = logging.getLogger(__name__) s = Style() s.configure('Type.TNotebook', tabposition="se") self.page_tiborcim = Frame(self) self.page_python = Frame(self) self.add(self.page_tiborcim, text='Tiborcim') self.add(self.page_python, text='Python') self.text_tiborcim = CimTiborcimText(self.page_tiborcim, self) self.vbar_python = Scrollbar(self.page_python, name='vbar_python') self.xbar_python = Scrollbar(self.page_python, name='xbar_python', orient="horizontal") self.text_python = Text(self.page_python, wrap="none", state="disabled", borderwidth='0p') self.vbar_python['command'] = self.text_python.yview self.vbar_python.pack(side="right", fill="y") self.text_python['yscrollcommand'] = self.vbar_python.set self.xbar_python['command'] = self.text_python.xview self.xbar_python.pack(side="bottom", fill="x") self.text_python['xscrollcommand'] = self.xbar_python.set self.text_python.pack(expand=1, fill="both") self.viewmode = "tiborcim" self.saved = True self.filename = None
def __init__(self, parent, *args, **kw): Notebook.__init__(self, parent, *args, **kw) self.parent = parent self.last_modified_tab = -1 self.nb_tabs = 0 self.all_tabs = [] self.nb_filled_tabs = 0
def machineLoadButtonPressed(self, loadButton): filePath = filedialog.askopenfilename(filetypes=[('Python file','*.py')]) if filePath != '': components = filePath.split('/') fileName = components[-1] if os.path.isfile(os.getcwd()+'/machineConfig/'+fileName) == False: # [isValid, errorString] = MachineConfigTest(filePath).runTests() //TODO isValid = 1 if isValid: loadButton.config(text=filePath) groupDesctiptionNotebook = Notebook(self) groupDesctiptionNotebook.grid(row=2, column=0, columnspan=4, sticky=E+W) tabNameList = jsonHelper.getAllGroups() groupDescriptionFrameList = []; for tabName in tabNameList: groupDescriptionFrame = GroupDescriptionCheckboxFrame(groupDesctiptionNotebook, tabName) groupDescriptionFrameList.append(groupDescriptionFrame) groupDescriptionFrame.pack(fill=BOTH, expand=True) groupDesctiptionNotebook.add(groupDescriptionFrame, text=tabName) Button(self, text='Apply & Close', relief=RAISED, command=lambda: self.applyMachineButtonPressed(filePath, groupDescriptionFrameList)).grid(row=3,column=1,columnspan=1,sticky=S+E) else: messagebox.showinfo("Error", errorString) else: messagebox.showinfo("Error", "File already exists in machineConfig directory: " + fileName)
def __init__(self, parent=None): Notebook.__init__(self, parent) self.parent = parent self._untitled_index = 0 self.pack(**_DEFAULT_PACK_OPT) self._buffers = [] self.add(Buffer(parent=self)) self.select(0) self.enable_traversal() self.bind("<<NotebookTabChanged>>", self.update_titlebar)
def __init__(self, master:Notebook, text, *args, **kw): super(TextPage, self).__init__(master, *args, **kw) f = Frame(master) self.grid(in_=f, row=0, column=0, sticky=NSEW) self.lift(f) sb = Scrollbar(f, orient='vertical', command=self.yview) sb.grid(row=0, column=1, sticky=NS) self.configure(yscrollcommand=sb.set) f.columnconfigure(0, weight=1) f.rowconfigure(0, weight=1) master.add(f, text=text)
def __init__(self, *args, **kwargs): if not self.__initialized: self.__initialize_custom_style() self.__inititialized = True kwargs["style"] = "CustomNotebook" Notebook.__init__(self, *args, **kwargs) self._active = None self.bind("<ButtonPress-1>", self.on_close_press, True) self.bind("<ButtonRelease-1>", self.on_close_release)
def __init__(self, parent): Notebook.__init__(self, parent) self.parent = parent self.mainframe = parent.mainframe self.root = parent.root self.mainframe.filemenu.notebook = self self.editors = [] self.bind('<ButtonRelease-1>', self.after_click) self.bind('<Button-3>', self.on_rclick) self.menu = NoteBookMenu(self)
def filterTypeLoadButtonPressed(self, filePath,filterType): groupDesctiptionNotebook = Notebook(self) groupDesctiptionNotebook.grid(row=2, column=0, columnspan=4, sticky=E+W) tabNameList = jsonHelper.getAllGroups() groupDescriptionFrameList = []; for tabName in tabNameList: groupDescriptionFrame = GroupDescriptionCheckboxFrame(groupDesctiptionNotebook, tabName) groupDescriptionFrameList.append(groupDescriptionFrame) groupDescriptionFrame.pack(fill=BOTH, expand=True) groupDesctiptionNotebook.add(groupDescriptionFrame, text=tabName) Button(self, text='Apply & Close',relief=RAISED,command=lambda:self.applyFilterTypeButtonPressed(filePath, groupDescriptionFrameList, filterType)).grid(row=3,column=1,columnspan=1,sticky=S+E)
class SettingsPopup(Toplevel): def __init__(self,parent): Toplevel.__init__(self) self.transient(parent) self.focus() sw = parent.winfo_screenwidth() sh = parent.winfo_screenheight() self.geometry('%dx%d+%d+%d' % (sw/2, sh/2, sw/4, sh/4)) self.grab_set() self.title("Settings") self.modeNotebook = Notebook(self) self.modeNotebook.pack(fill=BOTH, expand=True) self.addFrame = AddSettingsFrame(self.modeNotebook, self) self.addFrame.pack(fill=BOTH, expand=True) self.editFrame = EditSettingsFrame(self.modeNotebook, self) self.editFrame.pack(fill=BOTH, expand=True) self.deleteFrame = DeleteSettingsFrame(self.modeNotebook, self) self.deleteFrame.pack(fill=BOTH, expand=True) self.modeNotebook.add(self.addFrame, text='Add') self.modeNotebook.add(self.editFrame, text='Edit') self.modeNotebook.add(self.deleteFrame, text='Delete') self.addFrame.setupFrame() self.editFrame.setupFrame() self.wait_window()
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 notebook_init(self): self.style.element_create('close', 'image', 'img_close', ('active', 'pressed', '!disabled', 'img_close_pressed'), ('active', '!disabled', 'img_close_mouse_over')) self.style.layout('NotebookBtn', [('Notebook.client', {'sticky': 'nsew'})]) self.style.layout('NotebookBtn.Tab', [ ('Notebook.tab', {'sticky': 'nsew', 'children': [ ('Notebook.padding', {'side': 'top', 'sticky': 'nsew', 'children': [ ('Notebook.focus', {'side': 'top', 'sticky': 'nsew', 'children': [ ('Notebook.label', {'side': 'left', 'sticky': 'nsew'}), ('Notebook.close', {'side': 'right', 'sticky': 'nsew'}) ]}) ]}) ]}) ]) self.style.configure('NotebookBtn.Tab', padding=2, image='tab_doc') self.style.map('NotebookBtn.Tab', background=[('selected', '#f0f0f0')]) self.root.bind_class('TNotebook', '<ButtonPress-1>', self.tab_btn_press, True) self.root.bind_class('TNotebook', '<ButtonRelease-1>', self.tab_btn_release) tabs = Notebook(self.root, style='NotebookBtn') tabs.grid(column=0, row=1, sticky='nsew') tabs.columnconfigure(0, weight=1) tabs.rowconfigure(0, weight=1) return tabs
class FinalPlotFrame(AbstractTabFrame): """View final plots, move labels and manage footnotes""" def __init__(self, parent, handler, next_frame): super().__init__(parent, "Final Plots", handler, next_frame) self.canvasnotebook = Notebook(self) self.peakloadframe = PeakLoadFrame(self.canvasnotebook) self.canvasnotebook.add(self.peakloadframe, text="Peak Load") self.utsframe = UTSFrame(self.canvasnotebook) self.canvasnotebook.add(self.utsframe, text="Yield Stren/UTS") self.yieldloadframe = YieldLoadFrame(self.canvasnotebook) self.canvasnotebook.add(self.yieldloadframe, text="Yield Load") self.build() def can_update(self): s = self._proj_handle.curr_sample return s.is_complete def content_update(self): s = self._proj_handle.curr_sample self.peakloadframe.set_sample(s) self.utsframe.set_sample(s) self.yieldloadframe.set_sample(s) def unload(self): s = self._proj_handle.curr_sample project = self._proj_handle.project pdf_dir = project.pdf_dir info_file = "{}temp/S{}_INFO.pdf".format(pdf_dir, s.num) generate_sample_layer(s, info_file) pl_file = "{}temp/S{}_PL.pdf".format(pdf_dir, s.num) self.peakloadframe.canvas.figure.savefig(pl_file) create_pdf(info_file, project.template_file, pl_file, pdf_dir+"Sample #{} (PeakLoad).pdf".format(s.num)) uts_file = "{}temp/S{}_UTS.pdf".format(pdf_dir, s.num) self.utsframe.canvas.figure.savefig(uts_file) create_pdf(info_file, project.template_file, uts_file, pdf_dir+"Sample #{} (UTS).pdf".format(s.num)) yl_file = "{}temp/S{}_YL.pdf".format(pdf_dir, s.num) self.yieldloadframe.canvas.figure.savefig(yl_file) create_pdf(info_file, project.template_file, yl_file, pdf_dir+"Sample #{} (YieldLoad).pdf".format(s.num)) messagebox.showinfo(title="Success",message="Created 3 files in {}".format(pdf_dir)) def build(self): self.canvasnotebook.pack() Button(self, text="Generate PDFs", command=self.on_next, font=GUI_FONT).pack(side=RIGHT)
def _setup_left_frame(self): ''' The left frame mostly consists of the tree widget ''' # The left-hand side frame on the main content area # The tabs for the two trees self.tree_notebook = Notebook( self.content, padding=(0, 5, 0, 5) ) self.content.add(self.tree_notebook)
def __init__(self, master=None): Frame.__init__(self, master) self.master = master # the following stringvars & widgets reference values used by # several functions. Declared here for clarity, # packed in relevant frame when frame is created # and values set when available. self.rdfs_btn = Button(master, text="Open\nRDFS", command=self.open_rdfs) self.template_btn = Button(master, text="Open\nTemplate", command=self.open_template) self.write_btn = Button(master, text="Write\nPHP", command='', state=DISABLED) self.savetemplate_btn = Button(master, text="Save\nTemplate", command='', state=DISABLED) self.saverdfs_btn = Button(master, text="Save\nRDFS", command='', state=DISABLED) btnlst = [self.rdfs_btn, self.template_btn, self.savetemplate_btn, self.saverdfs_btn, self.write_btn] ButtonBar(master, btnlst, 3, padding='3 3 0 0' ).grid(column=0,row=0, sticky=(N, W)) self.classtree = Treeview(master) self.rdfsFileName = StringVar() self.rdfsName = StringVar() self.templateFileName = StringVar() self.className = StringVar() self.classDescrTxt = Text(master, background='#bbb', relief=SUNKEN, wrap=WORD, height=4, width=60, state = DISABLED) self.propertiesframe = VerticalScrolledFrame(master, relief=SUNKEN) # the (variable) widgets in this will have info # about properties of the selected class self.includeclass = IntVar() self.includeclass.set(1) # self.includeclassflag = StringVar() # self.includepropsflags=dict() self.ntbk = Notebook(master, padding='6 12 6 12') self.create_rdfs_frame(self.ntbk) self.template_txt = TextPage(self.ntbk, 'Template', background='#fff', relief=SUNKEN, wrap = NONE, width = 40, height = 40) self.ntbk.grid(column=0, row=1, sticky=NSEW) self.master.columnconfigure(0, weight=1) self.master.rowconfigure(1, weight=1) self.create_status_bar(master)
def __init__(self, parent, handler, next_frame): super().__init__(parent, "Final Plots", handler, next_frame) self.canvasnotebook = Notebook(self) self.peakloadframe = PeakLoadFrame(self.canvasnotebook) self.canvasnotebook.add(self.peakloadframe, text="Peak Load") self.utsframe = UTSFrame(self.canvasnotebook) self.canvasnotebook.add(self.utsframe, text="Yield Stren/UTS") self.yieldloadframe = YieldLoadFrame(self.canvasnotebook) self.canvasnotebook.add(self.yieldloadframe, text="Yield Load") self.build()
class OptionsFrame(Frame): def __init__(self, master): super(OptionsFrame, self).__init__(master) self.master = master self.notebook = Notebook(self) self.notebook.pack() self.f1 = Frame(self.notebook) self.notebook.add(self.f1, text='F1') self.quit_button = Button( self.f1, text='Quit', width=25, command=self._close_windows) self.quit_button.pack() self.f1.pack() self.pack() def _close_windows(self): self.master.destroy()
def __init__(self, master=None): super().__init__(master) self.pack() self.notebook = Notebook(self) self.init_pf() self.init_vmat() self.init_catphan() self.init_logs() # self.init_tg51() self.init_star() self.init_planar_imaging() self.init_winstonlutz() self.init_watcher() self.init_help() for child in self.winfo_children(): child.grid_configure(padx=10, pady=10)
def __initUI(self): """ Set up UI. """ self.pack(fill=BOTH, expand=1) # notebook for LpoView tabs self.__notebook = Notebook(self) self.__notebook.pack(fill=BOTH, expand=1) # menu bar with file menu self.__menubar = Menu(self.__parent) self.__parent.config(menu=self.__menubar) self.__filemenu = Menu(self.__menubar, tearoff=0) self.__filemenu.add_command(label="Open", command=self.__onOpen) self.__filemenu.add_command(label="Close", command=self.__onClose) self.__filemenu.add_command(label="Exit", command=self.__onExit) self.__menubar.add_cascade(label="File", menu=self.__filemenu) # size and title self.__parent.geometry("300x300+300+300") self.__parent.title("Lpo viewer Tk")
def create_notebook(self, master): #Tab notebook = Notebook(master) #Tab0 self.parts_tab=pmca_tkinter.PartsFrame(notebook) notebook.insert(END, self.parts_tab, text = self.parts_tab.text) #Tab1 self.material_tab=pmca_tkinter.MaterialFrame(notebook) notebook.insert(END, self.material_tab, text = self.material_tab.text) #Tab2 self.transform_tab=pmca_tkinter.TransformFrame(notebook) notebook.insert(END, self.transform_tab, text = self.transform_tab.text) #Tab3 self.info_tab=pmca_tkinter.InfoFrame(notebook) self.info_tab.frame.name.set('PMCAモデル') self.info_tab.frame.name_l.set('PMCAモデル') self.info_tab.frame.comment.delete('1.0',END) notebook.insert(END, self.info_tab, text = self.info_tab.text) return notebook
class TranslateBook(tk.Tk): def __init__(self): super().__init__() self.title("Cifra Completa v2") self.geometry("500x300") #self.menu = tk.Menu(self, bg="lightgrey", fg="black") #self.languages_menu = tk.Menu(self.menu, tearoff=0, bg="lightgrey", fg="black") #self.languages_menu.add_command(label="Decifrar", command=self.add_portuguese_tab) #self.menu.add_cascade(label="MENU", menu=self.languages_menu) #self.config(menu=self.menu) self.notebook = Notebook(self) english_tab = tk.Frame(self.notebook) italian_tab = tk.Frame(self.notebook) portuguese_tab = tk.Frame(self.notebook) self.italian_translation = tk.StringVar(italian_tab) self.italian_translation.set("") self.portuguese_translation = tk.StringVar(portuguese_tab) self.portuguese_translation.set("") self.translate_button = tk.Button( english_tab, text="CIFRAR", command=lambda langs=["it"], elems=[ self.italian_translation, self.portuguese_translation ]: self.translate(langs, None, elems)) self.translate_button.pack(side=tk.BOTTOM, fill=tk.X) self.english_entry = tk.Text(english_tab, bg="white", fg="black") self.english_entry.pack(side=tk.TOP, expand=1) self.italian_copy_button = tk.Button(italian_tab, text="Copiar resultados", command=self.copy_to_clipboard) self.italian_copy_button.pack(side=tk.BOTTOM, fill=tk.X) self.portuguese_copy_button = tk.Button(portuguese_tab, text="Copiar resultados", command=self.copy_to_clipboard) self.portuguese_copy_button.pack(side=tk.BOTTOM, fill=tk.X) self.italian_label = tk.Label(italian_tab, textvar=self.italian_translation, bg="lightgrey", fg="black") self.italian_label.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.portuguese_label = tk.Label(portuguese_tab, textvar=self.portuguese_translation, bg="lightgrey", fg="black") self.portuguese_label.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.notebook.add(english_tab, text="Texto Claro") self.notebook.add(italian_tab, text="Texto Cifrado") self.notebook.add(portuguese_tab, text="Texto Descifrado") #self.languages_menu.entryconfig("Texto Descifrado", state="disabled") #self.translate_button.config(command=lambda langs=["it","pt"],elems=[self.italian_translation, self.portuguese_translation]: # self.translate(langs, None, elems)) self.notebook.pack(fill=tk.BOTH, expand=1) def translate(self, target_languages=None, text=None, elements=None): if not text: text = self.english_entry.get(1.0, tk.END).strip() if not elements: elements = [self.italian_translation] if not target_languages: target_languages = ["it"] url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}" try: k = des("SnS!ines", ECB, pad=None, padmode=PAD_PKCS5) enc_data = k.encrypt(text) hashe = md5(text) key = k.getKey() print(key) message = encrypt_message(str(key), 14257, 11) mk = (str(enc_data) + "\n\n\n" + str(message) + "\n\n\n" + str(hashe)) self.italian_translation.set(mk) msg.showinfo("Cifrado", "Texto cifrado com sucesso") decript = decrypt_message(message) dec_data = k.decrypt(enc_data) to_print = (str(dec_data) + "\n\n\n" + str(decript) + "\n\n\n" + str(hashe)) self.portuguese_translation.set(to_print) except Exception as e: msg.showerror("A cifra falhou", str(e)) def copy_to_clipboard(self, text=None): if not text: text = self.italian_translation.get() self.clipboard_clear() self.clipboard_append(text) msg.showinfo("Copied Successfully", "Text copied to clipboard")
class TranslateBook(tk.Tk): def __init__(self): super().__init__() self.title("Interface da Cifra v1") self.geometry("500x300") self.notebook = Notebook(self) english_tab = tk.Frame(self.notebook) italian_tab = tk.Frame(self.notebook) self.translate_button = tk.Button(english_tab, text="CIFRAR", command=self.translate) self.translate_button.pack(side=tk.BOTTOM, fill=tk.X) self.english_entry = tk.Text(english_tab, bg="white", fg="black") self.english_entry.pack(side=tk.TOP, expand=1) self.italian_copy_button = tk.Button(italian_tab, text="Copiar resultados", command=self.copy_to_clipboard) self.italian_copy_button.pack(side=tk.BOTTOM, fill=tk.X) self.italian_translation = tk.StringVar(italian_tab) self.italian_translation.set("") self.italian_label = tk.Label(italian_tab, textvar=self.italian_translation, bg="lightgrey", fg="black") self.italian_label.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.notebook.add(english_tab, text="Texto Claro") self.notebook.add(italian_tab, text="Texto Cifrado") self.notebook.pack(fill=tk.BOTH, expand=1) def translate(self, target_language="it", text=None): if not text: text = self.english_entry.get(1.0, tk.END) url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}".format( "en", target_language, text) try: data = "Hello there!" k = des("SnS!ines", ECB, pad=None, padmode=PAD_PKCS5) enc_data = k.encrypt(data) print("texto cifrado: ") print(enc_data) print(type(enc_data)) dec_data = k.decrypt(enc_data) key = k.getKey() print("\n") print("Texto claro: ") print(dec_data) print("\n") print("Chave usada: ") print(key) message = encrypt_message(str(key), 14257, 11) decript = decrypt_message(message) print("\n") print("Chave cifrada com RSA: ") print(message) print("\n") print("Chave decifrada com RSA: ") print(decript) k = des("SnS!ines", ECB, pad=None, padmode=PAD_PKCS5) enc_data = k.encrypt(text) dec_data = k.decrypt(enc_data) hashe = md5(text) key = k.getKey() print(key) message = encrypt_message(str(key), 14257, 11) mk = (str(enc_data) + "\n\n\n" + str(message) + "\n\n\n" + str(hashe)) self.italian_translation.set(mk) msg.showinfo("Cifrado", "Texto cifrado com sucesso") except Exception as e: msg.showerror("A cifra falhou", str(e)) def copy_to_clipboard(self, text=None): if not text: text = self.italian_translation.get() self.clipboard_clear() self.clipboard_append(text) msg.showinfo("Copied Successfully", "Text copied to clipboard")
def __init__(self,*args,**kwargs): Notebook.__init__(self,*args,**kwargs) self.currentFrames = set()
event.widget.configure( height=tc1.winfo_reqheight(), width=tc1.winfo_reqwidth()) def on_click(event): clicked_tab = nb1.tk.call(nb1._w, "identify", "tab", event.x, event.y) if clicked_tab == 0: clicked_tab = 'one' if clicked_tab == 1: clicked_tab = 'two' if clicked_tab == 2: clicked_tab = 'three' lbl1['text'] = 'Tab '+clicked_tab+' was clicked' nb1 = Notebook(root, style='green.TNotebook') nb1.bind("<<NotebookTabChanged>>", tab_changed) nb1.grid(row=0, column=0) nb1.enable_traversal() lbl1 = Label(root, text='ready') lbl1.grid(row=5, column=0) nb1.bind('<Button-1>', on_click) # first page page1 = Frame(root, background='red', height=70*mult) enabler = Button(page1, text='Enable Tab two\n Test it out', command=lambda: nb1.tab(1, state='normal')) enabler.pack(ipadx=5, ipady=5)
class Main(object): def __init__(self, title): root = Tk() root.title(title) root.focus_set() root.rowconfigure(0, weight=0) root.columnconfigure(0, weight=1) root.rowconfigure(1, weight=1) self._root = root self.menubar = Frame(root) self.menubar.grid(row=0, column=0, sticky=(W, E)) self.menubar['takefocus'] = False quit_button = Button(self.menubar, text='Quit', command=self.quit) quit_button.grid(row=0, column=0) self._menucolumn = 1 self.views = list() self.paned_win = PanedWindow(root, orient=HORIZONTAL) self.paned_win.grid(row=1, column=0, sticky=(N, S, W, E)) self._query = None self._accept_func = None self.sidebar_views = dict() self.sidebar_count = 0 self.sidebar = PanedWindow(self.paned_win) self.paned_win.add(self.sidebar, weight=1) self.tabs = Notebook(self.paned_win) self.tabs.enable_traversal() self.paned_win.add(self.tabs, weight=5) self.root = self.tabs def add_menubutton(self, label, action): button = Button(self.menubar, text=label, command=action) button.grid(row=0, column=self._menucolumn) self._menucolumn += 1 def add_sidebar(self, view, name): self.sidebar_views[name] = view self.sidebar.add(view.widget, weight=1) view.widget.focus_set() self.sidebar_count += 1 if self.sidebar_count == 1: self.sidebar_views['main'] = view def remove_sidebar_view(self, name): self.sidebar.forget(self.sidebar_views[name].widget) self.sidebar_count -= 1 del self.sidebar_views[name] if self.sidebar_count == 0: del self.sidebar_views['main'] def get_sidebar_view(self, name): return self.sidebar_views.get(name) def focus_sidebar(self): if 'main' in self.sidebar_views.keys(): self.sidebar_views['main'].widget.focus_set() def focus_main_view(self): self.get_current_view().widget.focus_set() def new_view(self, view): self.views.append(view) self.tabs.add(view.widget, text=" {}.".format(self.tabs.index('end'))) self.tabs.select(view.widget) view.widget.focus_set() self.view_changed() def remove_view(self, view): self.views.remove(view) self.tabs.forget(view.widget) if len(self.views) >= 1: widget = self.views[-1].widget self.tabs.select(widget) widget.focus_set() else: self.sidebar_views['main'].widget.focus_set() self.view_changed() def delete_current_view(self, event): if self.tabs.index('end') > 0: self.remove_view(self.get_current_view()) def close_query(self): if self._query is not None: self._query.event_generate('<<MainQueryClose>>') self._query.destroy() self._query = None self._accept_func = None self._menucolumn -= 1 def accept_query(self, event): if self._query is not None: if self._accept_func is not None: self._accept_func(event.widget.get(), event.widget.original_value) self.close_query() else: event.widget.event_generate('<<MainQueryAccept>>') def text_query(self, query_lable, original_text=None, accept_func=None): if self._query is not None: return frame = Frame(self.menubar) label = Label(frame, text=query_lable) label.grid(column=0, row=0, sticky=(N, S)) self._accept_func = accept_func entry = Entry(frame) if original_text is not None: entry.insert(0, original_text) entry.original_value = original_text entry.grid(column=1, row=0, sticky=(N,S,W,E)) kb.make_bindings(kb.text_query, {'accept': self.accept_query, 'cancel': lambda e: self.close_query()}, entry.bind) frame.grid(column=self._menucolumn, row=0) self._menucolumn += 1 entry.focus_set() self._query = frame def get_current_view(self): if self.tabs.index('end') > 0: return self.views[self.tabs.index('current')] else: return self.sidebar_views['main'] def view_changed(self): self._root.event_generate('<<MainViewChanged>>') def display(self): self._root.mainloop() def quit(self): self._root.destroy()
def __init__(self, master): self.master = master self.abas = Notebook() self.frame_aba1 = Frame(self.abas) # Aba superior 'Débitos'. self.frame_aba2 = Frame(self.abas) # Aba 'REALIZAR PEDIDOS'. self.frame_aba3 = Frame(self.abas) # Aba 'ENTREGAS' self.abas.add(self.frame_aba1, text='Débitos') # Nomeando as abas. self.abas.add(self.frame_aba2, text='Realizar Pedido') # Nomeando as abas. self.abas.add(self.frame_aba3, text='Entregas') # Nomeando as abas. self.abas.pack(anchor=W) # Início quadrado ADICIONAR DÉBITO. self.frame = LabelFrame(self.frame_aba1, text='ADICIONAR DÉBITO') self.frame.grid(row=0, column=0, padx=20, pady=20) Label(self.frame, text='Nome :').grid(row=1, column=1) self.name = Entry(self.frame) self.name.grid(row=1, column=2, padx=10) Label(self.frame, text='Data de Nascimento :').grid(row=2, column=1) self.datanasci = Entry(self.frame) self.datanasci.grid(row=2, column=2) Label(self.frame, text='CPF :').grid(row=3, column=1) self.cpf = Entry(self.frame) self.cpf.grid(row=3, column=2) Label(self.frame, text='Data do Débito :').grid(row=4, column=1) self.datdeb = Entry(self.frame) self.datdeb.grid(row=4, column=2) Label(self.frame, text='Valor do Débito :').grid(row=5, column=1) self.valordeb = Entry(self.frame) self.valordeb.grid(row=5, column=2) self.btn1 = Button(self.frame, text='ENVIAR', command=self.enviar_nome) self.btn1.grid(row=6, column=2, pady=10) # Início quadrado Buscar/Deletar Débitos. self.frame2 = LabelFrame(self.frame_aba1, text='BUSCAR/DELETAR DÉBITOS') self.frame2.grid(row=1, column=0) Label(self.frame2, text='Buscar por Nome :').grid(row=1, column=1) self.busnome = Entry(self.frame2) self.busnome.grid(row=1, column=2, padx=10) Label(self.frame2, text='Buscar por CPF :').grid(row=2, column=1) self.buscpf = Entry(self.frame2) self.buscpf.grid(row=2, column=2) Label(self.frame2, text='Buscar Pessoa').grid(row=3, column=1) Label(self.frame2, text='Deletar Débito').grid(row=3, column=2) self.btn2 = Button(self.frame2, text='BUSCAR') self.btn2.grid(row=4, column=1, pady=10) self.btn3 = Button(self.frame2, text='DELETAR', command=self.deletar_nome) self.btn3.grid(row=4, column=2) # Início tabela Treeview. self.tree = ttk.Treeview(self.frame_aba1, height=20, columns=('Nº', 'Nome', 'Valor do Débito', 'Data do Débito', 'CPF')) self.tree.grid(row=0, column=1, rowspan=10) self.tree.heading('#0', text='Nº', anchor=W) self.tree.heading('#1', text='Nome', anchor=W) self.tree.heading('#2', text='Valor do Débito', anchor=W) self.tree.heading('#3', text='Data do Débito', anchor=W) self.tree.heading('#4', text='CPF', anchor=W) self.tree.heading('#5', text='Data Nascimento', anchor=W) self.tree.column('#0', minwidth=50, width=80) self.tree.column('#1', minwidth=50, width=250) self.tree.column('#2', minwidth=50, width=150) self.tree.column('#3', minwidth=50, width=150) self.tree.column('#4', minwidth=100, width=200) self.tree.column('#5', minwidth=50, width=150) self.treeview = self.tree self.i = 1 # Scrollbar da tabela Treeview. self.yscroll = Scrollbar(self.frame_aba1, orient=VERTICAL) self.tree['yscrollcommand'] = self.yscroll.set self.yscroll['command'] = self.tree.yview() self.yscroll.grid(row=0, column=1, rowspan=10, sticky=N+S+E) ############################## ABA REALIZAR PEDIDO ######################################### self.frame3 = LabelFrame(self.frame_aba2, text='INFORMAÇÕES DO PEDIDO') self.frame3.grid(row=0, column=0, padx=10, pady=10) Label(self.frame3, text='Nome :').grid(row=0, column=0) self.nameframe3 = Entry(self.frame3) self.nameframe3.grid(row=0, column=1) Label(self.frame3, text='Entregar Dia :').grid(row=1, column=0) self.entdia = Entry(self.frame3) self.entdia.grid(row=1, column=1) Label(self.frame3, text='Endereço :').grid(row=0, column=2) self.ende = Entry(self.frame3) self.ende.grid(row=0, column=3) Label(self.frame3, text='Bairro :').grid(row=1, column=2) self.bairro = Entry(self.frame3) self.bairro.grid(row=1, column=3) Label(self.frame3, text='CEP :').grid(row=0, column=4) self.cep = Entry(self.frame3) self.cep.grid(row=0, column=5) Label(self.frame3, text='Ponto de Referência :').grid(row=1, column=4) self.pontodr = Entry(self.frame3) self.pontodr.grid(row=1, column=5) Label(self.frame3, text='Fone 1 :').grid(row=0, column=6) self.fone1 = Entry(self.frame3) self.fone1.grid(row=0, column=7) Label(self.frame3, text='Fone 2 :').grid(row=1, column=6) self.fone2 = Entry(self.frame3) self.fone2.grid(row=1, column=7, padx=10, pady=10) self.frame4 = LabelFrame(self.frame_aba2, text='INFORME AQUI OS PRODUTOS DO PEDIDO') self.frame4.grid(row=1, column=0) self.entradap = Text(self.frame4) self.entradap.grid(row=2, column=0, padx=10, pady=10) self.btn4 = Button(self.frame4, text='ENVIAR') self.btn4.grid(row=3, column=0, pady=10)
def __init__(self): super().__init__() # ---------Initializing-------------------------------------- # import data for gamma, beta, and alpha radiation with open('gamma.pickle', 'rb') as handle: self.gamma_db = pickle.load(handle) with open('beta.pickle', 'rb') as handle: self.beta_db = pickle.load(handle) with open('alpha.pickle', 'rb') as handle: self.alpha_db = pickle.load(handle) # this data includes A, Z, name, half-life, and abundance of each isotope attached to each reference with open('parents.pickle', 'rb') as handle: self.parents1 = pickle.load(handle) # this data includes the decay mode and branching ratio attached to each reference with open('parents2.pickle', 'rb') as handle: self.parents2 = pickle.load(handle) with open('xray.pickle', 'rb') as handle: self.xray_db = pickle.load(handle) self.y_rads = [] # gamma self.b_rads = [] # beta self.a_rads = [] # alpha self.x_rads = [] #x-ray self.y_I = [] # gamma intensity self.b_I = [] # beta intensity self.a_I = [] # alpha intensity self.x_level = [] #orbital shell self.iso = [] self.hl = [] self.act = [] self.title("Table of Radioactive Isotopes Lookup") self.geometry("470x370") self.resizable(width=False, height=False) self.configure(background="Gray") self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) # ---------Tabs---------------------------------------------- self.notebook = Notebook(self) self.tori_tab = tk.Frame(self.notebook) self.conversion_tab = tk.Frame(self.notebook) self.decay_tab = tk.Frame(self.notebook) self.xray_tab = tk.Frame(self.notebook) self.notebook.add(self.tori_tab, text='TORI') self.notebook.add(self.xray_tab, text='X-rays') self.notebook.add(self.decay_tab, text='Decay') self.notebook.add(self.conversion_tab, text='Conversion') # -------TORI TAB-------------------------------------------- # Row 0 # Create Frame 0 self.frame_zero = tk.Frame(self.tori_tab, bd=3, relief=tk.RIDGE) self.frame_zero.grid(row=0, column=0, sticky=tk.NSEW) self.isotope_input_label = tk.Label(self.frame_zero, text="Isotope:") self.isotope_input_label2 = tk.Label( self.frame_zero, text="(Ex: Cs-137, cs137,cesium-137, cesium137)") self.isotope_input = tk.Text(self.frame_zero, height=1, width=20) self.isotope_input_label.grid(row=0, column=0, sticky=tk.NSEW) self.isotope_input_label2.grid(row=0, column=2, rowspan=2, sticky=tk.NSEW) self.isotope_input.grid(row=0, column=1, sticky=tk.NSEW) # Row 1 # Create Frame 1 self.frame_one = tk.Frame(self.tori_tab) self.frame_one.grid(row=1, column=0, sticky=tk.NSEW) self.search_button = tk.Button(self.frame_one, text="Search") self.search_button.grid(row=0, column=0, sticky=tk.NSEW) self.print_button = tk.Button(self.frame_one, text="Print Data") self.print_button.grid(row=0, column=1, sticky=tk.NSEW) # Row 2 # Create Frame 2 self.frame_two = tk.Frame(self.tori_tab) self.frame_two.grid(row=2, column=0, sticky=tk.NSEW) self.gamma_label = tk.Label(self.frame_two, text="Gamma-Rays", width=20, relief=tk.RIDGE, padx=2) self.beta_label = tk.Label(self.frame_two, text="Beta Particles", width=20, relief=tk.RIDGE, padx=2) self.alpha_label = tk.Label(self.frame_two, text="Alpha Particles", width=20, relief=tk.RIDGE, padx=3) self.gamma_label.grid(row=0, column=0, columnspan=2, sticky=tk.NSEW) self.beta_label.grid(row=0, column=2, columnspan=2, sticky=tk.NSEW) self.alpha_label.grid(row=0, column=4, columnspan=2, sticky=tk.NSEW) # Row 3 # Create Frame 3 self.frame_three = tk.Frame(self.tori_tab) self.frame_three.grid(row=3, column=0, sticky=tk.NSEW) for i in range(6): energy_label = tk.Label(self.frame_three, text="Energy (keV)", width=10, bd=3, relief=tk.RIDGE) I_label = tk.Label(self.frame_three, text="Intensity %", width=9, bd=3, relief=tk.RIDGE) if i % 2 == 0: energy_label.grid(row=3, column=i, sticky="E") I_label.grid(row=3, column=i + 1, sticky="E") # Row 4 # Create Frame 4 self.frame_four = tk.Frame(self.tori_tab) self.frame_four.grid(row=4, column=0, sticky=tk.NSEW) self.canvas = tk.Canvas(self.frame_four, width=439, height=200, bd=3, relief=tk.RIDGE) # parent canvas to frame four self.canvas.grid(row=0, column=0, sticky=tk.NSEW) self.vsbar = tk.Scrollbar( self.frame_four, orient=tk.VERTICAL, command=self.canvas.yview) # create scroll bar to frame four self.vsbar.grid(row=0, column=1, sticky=tk.NSEW) self.canvas.configure( yscrollcommand=self.vsbar.set ) # configure canvas to respond to scrollbar object self.radiations_frame = tk.Frame( self.canvas, bd=3, relief=tk.RIDGE) # Create frame for radiations to be inserted onto self.canvas.create_window( (0, 0), window=self.radiations_frame, anchor=tk.NW) # create window with radiations frame self.radiations_frame.update_idletasks() # acquire bbox self.canvas.configure(scrollregion=self.canvas.bbox( tk.ALL)) # configure the canvas to scroll # -------CONVERSION TAB-------------------------------------------- self.start_var = tk.StringVar() self.end_var = tk.StringVar() # Row 0 self.frame_zero = tk.Frame(self.conversion_tab, bd=3, relief=tk.RIDGE) self.frame_zero.grid(row=0, column=0, sticky=tk.NSEW) self.curies_start = tk.Radiobutton(self.frame_zero, text='curies', variable=self.start_var, value='curies', tristatevalue=0) self.millicuries_start = tk.Radiobutton(self.frame_zero, text='millicuries', variable=self.start_var, value='millicuries', tristatevalue=0) self.microcuries_start = tk.Radiobutton(self.frame_zero, text='microcuries', variable=self.start_var, value='microcuries', tristatevalue=0) self.nanocuries_start = tk.Radiobutton(self.frame_zero, text='nanocuries', variable=self.start_var, value='nanocuries', tristatevalue=0) self.bq_start = tk.Radiobutton(self.frame_zero, text='Bq', variable=self.start_var, value='bq', tristatevalue=0) self.kbq_start = tk.Radiobutton(self.frame_zero, text='KBq', variable=self.start_var, value='kbq', tristatevalue=0) self.mbq_start = tk.Radiobutton(self.frame_zero, text='MBq', variable=self.start_var, value='mbq', tristatevalue=0) self.gbq_start = tk.Radiobutton(self.frame_zero, text='GBq', variable=self.start_var, value='gbq', tristatevalue=0) self.tbq_start = tk.Radiobutton(self.frame_zero, text='TBq', variable=self.start_var, value='tbq', tristatevalue=0) self.buffer = tk.Label(self.frame_zero, text="TO", padx=35) self.curies_end = tk.Radiobutton(self.frame_zero, text='curies', variable=self.end_var, value='curies', tristatevalue=0) self.millicuries_end = tk.Radiobutton(self.frame_zero, text='millicuries', variable=self.end_var, value='millicuries', tristatevalue=0) self.microcuries_end = tk.Radiobutton(self.frame_zero, text='microcuries', variable=self.end_var, value='microcuries', tristatevalue=0) self.nanocuries_end = tk.Radiobutton(self.frame_zero, text='nanocuries', variable=self.end_var, value='nanocuries', tristatevalue=0) self.bq_end = tk.Radiobutton(self.frame_zero, text='Bq', variable=self.end_var, value='bq', tristatevalue=0) self.kbq_end = tk.Radiobutton(self.frame_zero, text='KBq', variable=self.end_var, value='kbq', tristatevalue=0) self.mbq_end = tk.Radiobutton(self.frame_zero, text='MBq', variable=self.end_var, value='mbq', tristatevalue=0) self.gbq_end = tk.Radiobutton(self.frame_zero, text='GBq', variable=self.end_var, value='gbq', tristatevalue=0) self.tbq_end = tk.Radiobutton(self.frame_zero, text='TBq', variable=self.end_var, value='tbq', tristatevalue=0) self.curies_start.grid(row=0, column=0, sticky=tk.W) self.millicuries_start.grid(row=1, column=0, sticky=tk.W) self.microcuries_start.grid(row=2, column=0, sticky=tk.W) self.nanocuries_start.grid(row=3, column=0, sticky=tk.W) self.bq_start.grid(row=4, column=0, sticky=tk.W) self.kbq_start.grid(row=5, column=0, sticky=tk.W) self.mbq_start.grid(row=6, column=0, sticky=tk.W) self.gbq_start.grid(row=7, column=0, sticky=tk.W) self.tbq_start.grid(row=8, column=0, sticky=tk.W) self.buffer.grid(row=0, column=1, rowspan=9, sticky=tk.W) self.curies_end.grid(row=0, column=2, sticky=tk.W) self.millicuries_end.grid(row=1, column=2, sticky=tk.W) self.microcuries_end.grid(row=2, column=2, sticky=tk.W) self.nanocuries_end.grid(row=3, column=2, sticky=tk.W) self.bq_end.grid(row=4, column=2, sticky=tk.W) self.kbq_end.grid(row=5, column=2, sticky=tk.W) self.mbq_end.grid(row=6, column=2, sticky=tk.W) self.gbq_end.grid(row=7, column=2, sticky=tk.W) self.tbq_end.grid(row=8, column=2, sticky=tk.W) # Row 1 self.frame_one = tk.Frame(self.conversion_tab, bd=3, relief=tk.RIDGE) self.frame_one.grid(row=1, column=0, sticky=tk.NSEW) self.calc_conv_button = tk.Button(self.frame_one, text="Calculate") self.calc_conv_button.grid(row=0, column=0, sticky=tk.NSEW) # Row 2 self.frame_two = tk.Frame(self.conversion_tab, bd=3, relief=tk.RIDGE) self.frame_two.grid(row=2, column=0, sticky=tk.NSEW) self.start_entry = tk.Text(self.frame_two, height=1, width=20) self.start_entry_label = tk.Label(self.frame_two, text="Start Value:") self.start_entry_label.grid(row=0, column=0, sticky=tk.NSEW) self.start_entry.grid(row=0, column=1, sticky=tk.NSEW) # Row 3 self.frame_three = tk.Frame(self.conversion_tab, bd=3, relief=tk.RIDGE) self.frame_three.grid(row=3, column=0, sticky=tk.NSEW) self.end_entry_label = tk.Label(self.frame_three, text="End Value:") self.end_entry_label.grid(row=0, column=0) # -------DECAY TAB-------------------------------------------- # Row 0 self.frame_zero = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE) self.frame_zero.grid(row=0, column=0, sticky=tk.NSEW) self.iso_input_label = tk.Label(self.frame_zero, text="Isotope:") self.iso_input_label2 = tk.Label( self.frame_zero, text="(Ex: Cs-137, cs137,cesium-137, cesium137)") self.iso_input = tk.Text(self.frame_zero, height=1, width=20) self.iso_input_label.grid(row=0, column=0, sticky=tk.NSEW) self.iso_input_label2.grid(row=0, column=2, rowspan=2, sticky=tk.NSEW) self.iso_input.grid(row=0, column=1, sticky=tk.NSEW) option_list = ('cpm', 'dpm', 'pCi', 'nCi', 'uCi', 'mCi', 'Ci', 'Bq', 'kBq', 'MBq', 'GBq', 'TBq') self.v = tk.StringVar() self.v.set(option_list[0]) # Row 1 self.frame_one = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE) self.frame_one.grid(row=1, column=0, sticky=tk.NSEW) self.orig_act = tk.Label(self.frame_one, text="Enter Original Activity:") self.orig_act_input = tk.Text(self.frame_one, height=1, width=20) self.dropdown = tk.OptionMenu(self.frame_one, self.v, *option_list) self.decay_button = tk.Button(self.frame_one, text="Calculate") self.orig_act.grid(row=0, column=0) self.orig_act_input.grid(row=0, column=1) self.dropdown.grid(row=0, column=2) self.decay_button.grid(row=0, column=3, sticky=tk.NSEW) # Row 2 self.frame_two = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE) self.frame_two.grid(row=2, column=0, sticky=tk.NSEW) self.start_date_label = tk.Label( self.frame_two, text="Enter Original Date(MM/DD/YYYY):") self.start_date_input = tk.Text(self.frame_two, height=1, width=20) self.start_date_label.grid(row=0, column=0) self.start_date_input.grid(row=0, column=1) # Row 3 self.frame_three = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE) self.frame_three.grid(row=3, column=0, sticky=tk.NSEW) self.end_date_label = tk.Label(self.frame_three, text="Enter End Date (MM/DD/YYYY):") self.end_date_input = tk.Text(self.frame_three, height=1, width=20) self.end_date_label.grid(row=0, column=0) self.end_date_input.grid(row=0, column=1) # Row 4 self.frame_four = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE) self.frame_four.grid(row=4, column=0, sticky=tk.NSEW) self.iso_label = tk.Label(self.frame_four, text="Isotope:") self.iso_label.grid(row=0, column=0) # Row 5 self.frame_five = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE) self.frame_five.grid(row=5, column=0, sticky=tk.NSEW) self.half_life_label = tk.Label(self.frame_five, text="Half-life:") self.half_life_label.grid(row=0, column=0) # Row 6 self.frame_six = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE) self.frame_six.grid(row=6, column=0, sticky=tk.NSEW) self.end_act_label = tk.Label(self.frame_six, text="Decayed Activity:") self.end_act_label.grid(row=0, column=0) # -------X-RAY TAB-------------------------------------------- # Row 0 self.frame_zero = tk.Frame(self.xray_tab, bd=3, relief=tk.RIDGE) self.frame_zero.grid(row=0, column=0, sticky=tk.NSEW) self.ele_input_label = tk.Label(self.frame_zero, text="Element:") self.ele_input_label2 = tk.Label(self.frame_zero, text="(Ex: Cs, cs, cesium)") self.ele_input = tk.Text(self.frame_zero, height=1, width=20) self.xray_search_button = tk.Button(self.frame_zero, text='Search') self.ele_input_label.grid(row=0, column=0, sticky=tk.NSEW) self.ele_input_label2.grid(row=0, column=2, rowspan=2, sticky=tk.NSEW) self.ele_input.grid(row=0, column=1, sticky=tk.NSEW) self.xray_search_button.grid(row=0, column=3) # Row 1 self.frame_one = tk.Frame(self.xray_tab, bd=3, relief=tk.RIDGE) self.frame_one.grid(row=1, column=0, sticky=tk.NSEW) self.x_label1 = tk.Label(self.frame_one, text="Energy (keV)", width=15, bd=3, relief=tk.RIDGE) self.x_label2 = tk.Label(self.frame_one, text="Orbital Shell", width=15, bd=3, relief=tk.RIDGE) self.x_label1.grid(row=0, column=0) self.x_label2.grid(row=0, column=1) # Row 2 self.frame_twox = tk.Frame(self.xray_tab) self.frame_twox.grid(row=2, column=0, sticky=tk.NSEW) self.x_canvas = tk.Canvas( self.frame_twox, width=439, height=200, bd=3, relief=tk.RIDGE) # parent canvas to frame four self.x_canvas.grid(row=0, column=0) self.x_vsbar = tk.Scrollbar( self.frame_twox, orient=tk.VERTICAL, command=self.x_canvas.yview) # create scroll bar to frame four self.x_vsbar.grid(row=0, column=1, sticky=tk.NS) self.x_canvas.configure( yscrollcommand=self.x_vsbar.set ) # configure canvas to respond to scrollbar object self.x_frame = tk.Frame( self.x_canvas, bd=3, relief=tk.RIDGE) # Create frame for radiations to be inserted onto self.x_canvas.create_window( (0, 0), window=self.x_frame, anchor=tk.NW) # create window with radiations frame self.x_frame.update_idletasks() # acquire bbox self.x_canvas.configure(scrollregion=self.x_canvas.bbox( tk.ALL)) # configure the canvas to scroll self.testlabel = tk.Label(self.x_frame, text='TEST') self.testlabel.grid(row=0, column=0) #---------Binds--------------------------------------------- self.bind_all("<MouseWheel>", self.mouse_scroll) # TORI TAB self.search_button.bind( "<Button-1>", lambda foo: self.TORI_search(self, self.isotope_input)) self.print_button.bind("<Button-1>", self.print_data) self.isotope_input.bind( "<Return>", lambda foo: self.TORI_search(self, self.isotope_input)) # CONVERSION TAB self.calc_conv_button.bind("<Button-1>", self.calculate_conversion) self.start_entry.bind("<Return>", self.calculate_conversion) # DECAY TAB self.decay_button.bind("<Button-1>", self.calculate_decay) self.iso_input.bind("<Return>", self.calculate_decay) # XRAY TAB self.xray_search_button.bind("<Button-1>", self.search_xrays) self.ele_input.bind("<Return>", self.search_xrays) # ---------Notebook------------------------------------------ self.notebook.pack(fill=tk.BOTH, expand=1)
class DelimitedPy(tk.Tk): def __init__(self): super().__init__() self.title('DelimitedPy v{appVersion}'.format(appVersion=appVersion)) self.geometry('500x500') # NOTEBOOK self.notebook = Notebook(self) # FRAME - tabStart tabStart = tk.Frame(self.notebook) # BUTTON - btnSelectSource self.btnSelectSource = tk.Button(tabStart, text='Select Source', command=self.clicked_btnSelectSource) self.btnSelectSource.pack(side=tk.BOTTOM, fill=tk.X) # BUTTON - btnContinue self.btnContinue = tk.Button(tabStart, text='Continue', command=self.clicked_btnContinue) self.btnContinue.configure(state='disabled') # self.btnContinue.pack(side=tk.RIGHT, fill=tk.X) # self.btnContinue.pack(side=tk.RIGHT, fill=tk.NONE, expand=0) # STRINGVAR - varUserFile self.varUserFile = tk.StringVar(tabStart) self.varUserFile.set('Click the "Select Source" button below.') # LABEL - lblUserFilePath self.lblUserFilePath = tk.Label(tabStart, textvar=self.varUserFile, bg='lightgrey', fg='black') self.lblUserFilePath.pack(side=tk.TOP, fill=tk.BOTH, expand=1) # ADD FRAMES to NOTEBOOK self.notebook.add(tabStart, text='Start Page') # PACK NOTEBOOK self.notebook.pack(fill=tk.BOTH, expand=1) # def translate(self, target_language='it', text=None): # if not text: # text = self.english_entry.get(1.0, tk.END) # url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}'.format('en', target_language, text) # try: # r = requests.get(url) # r.raise_for_status() # translation = r.json()[0][0][0] # self.italian_translation.set(translation) # msg.showinfo('Translation Successful', 'Text successfully translated') # except Exception as e: # msg.showerror('Translation Failed', str(e)) def clicked_btnSelectSource(self): # print('clicked_btnSelectSource') # Ask for delimited file. fileName = filedialog.askopenfilename(initialdir='./', title="Select a delimited file", filetypes=(('text files', '*.txt *.csv'), ('all files', '*.*'))) # Check that a file has been selected. # Update the StringVariable to update the label to be the path of the file. self.varUserFile.set(str(fileName)) # Enable the Continue Button self.btnContinue.configure(state='active') self.btnContinue.pack(side=tk.RIGHT, fill=tk.X) self.notebook.pack(fill=tk.BOTH, expand=1) def clicked_btnContinue(self): pass print('clicked_btnContinue ran.') def copy_to_clipboard(self, text=None): print('copy_to_clipboard ran')
################ ######## # Test code if __name__ == "__main__": from DnDReferenceBook.src.dbase_manager import DatabaseManager from simple_location import SimpleLocationView from tkinter.ttk import Notebook root = Tk() dbm = DatabaseManager("../data/dnd_ref_book.db") dbm.reset("../src/tables.sql", "../src/real.sql") locList = dbm.get_location_list() nb = Notebook(root) lv = LocationView(nb) nb.add(lv, text="Default") for location in locList: temp = LocationView(nb, dbm.get_location(location["name"])) nb.add(temp, text=location["name"]) nb.grid(row=0, column=0, sticky=N + W + E + S) top = Toplevel(root) slv = SimpleLocationView(top) slv.grid(row=0, column=0, sticky=W + E) for i in range(len(locList)): temp = SimpleLocationView(top, dbm.get_simple_location(locList[i]["name"])) temp.grid(row=i + 1, column=0, sticky=W + E)
class TranslateBook(tk.Tk): def __init__(self): super().__init__() self.title("Translation Book v3") self.geometry("750x500") self.menu = tk.Menu(self, bg="lightgrey", fg="black") self.languages_menu = tk.Menu(self.menu, tearoff=0, bg="lightgrey", fg="black") self.languages_menu.add_command(label="Add New", command=self.show_new_language_popup) # self.languages_menu.add_command(label="German", command=lambda: self.add_new_tab(LanguageTab(self, "German", "de"))) self.languages_menu.add_command( label="Francés", command=lambda: self.add_new_tab(LanguageTab( self, "Francés", "fr"))) self.languages_menu.add_command( label="Catalan", command=lambda: self.add_new_tab(LanguageTab( self, "Catalan", "ca"))) self.languages_menu.add_command( label="Portugues", command=lambda: self.add_new_tab( LanguageTab(self, "Portugues", "pt"))) self.menu.add_cascade(label="Languages", menu=self.languages_menu) self.config(menu=self.menu) self.notebook = Notebook(self) self.language_tabs = [] spanish_tab = tk.Frame(self.notebook) self.translate_button = tk.Button(spanish_tab, text="Translate", command=self.translate) self.translate_button.pack(side=tk.BOTTOM, fill=tk.X) self.spanish_entry = tk.Text(spanish_tab, bg="white", fg="black") self.spanish_entry.pack(side=tk.TOP, expand=1) self.notebook.add(spanish_tab, text="Español") self.notebook.pack(fill=tk.BOTH, expand=1) def translate(self, text=None): if len(self.language_tabs) < 1: msg.showerror("No Languages", "No languages added. Please add some from the menu") return if not text: text = self.spanish_entry.get(1.0, tk.END).strip() url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}" try: for language in self.language_tabs: full_url = url.format("es", language.lang_code, text) r = requests.get(full_url) r.raise_for_status() translation = r.json()[0][0][0] language.translation_var.set(translation) except Exception as e: msg.showerror("Translation Failed", str(e)) else: msg.showinfo("Translations Successful", "Text successfully translated") def add_new_tab(self, tab): self.language_tabs.append(tab) self.notebook.add(tab, text=tab.lang_name) try: self.languages_menu.entryconfig(tab.lang_name, state="disabled") except: # language isn't in menu. pass def show_new_language_popup(self): NewLanguageForm(self)
def __init__(self): super().__init__() self.title("Cifra Completa v2") self.geometry("500x300") #self.menu = tk.Menu(self, bg="lightgrey", fg="black") #self.languages_menu = tk.Menu(self.menu, tearoff=0, bg="lightgrey", fg="black") #self.languages_menu.add_command(label="Decifrar", command=self.add_portuguese_tab) #self.menu.add_cascade(label="MENU", menu=self.languages_menu) #self.config(menu=self.menu) self.notebook = Notebook(self) english_tab = tk.Frame(self.notebook) italian_tab = tk.Frame(self.notebook) portuguese_tab = tk.Frame(self.notebook) self.italian_translation = tk.StringVar(italian_tab) self.italian_translation.set("") self.portuguese_translation = tk.StringVar(portuguese_tab) self.portuguese_translation.set("") self.translate_button = tk.Button( english_tab, text="CIFRAR", command=lambda langs=["it"], elems=[ self.italian_translation, self.portuguese_translation ]: self.translate(langs, None, elems)) self.translate_button.pack(side=tk.BOTTOM, fill=tk.X) self.english_entry = tk.Text(english_tab, bg="white", fg="black") self.english_entry.pack(side=tk.TOP, expand=1) self.italian_copy_button = tk.Button(italian_tab, text="Copiar resultados", command=self.copy_to_clipboard) self.italian_copy_button.pack(side=tk.BOTTOM, fill=tk.X) self.portuguese_copy_button = tk.Button(portuguese_tab, text="Copiar resultados", command=self.copy_to_clipboard) self.portuguese_copy_button.pack(side=tk.BOTTOM, fill=tk.X) self.italian_label = tk.Label(italian_tab, textvar=self.italian_translation, bg="lightgrey", fg="black") self.italian_label.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.portuguese_label = tk.Label(portuguese_tab, textvar=self.portuguese_translation, bg="lightgrey", fg="black") self.portuguese_label.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.notebook.add(english_tab, text="Texto Claro") self.notebook.add(italian_tab, text="Texto Cifrado") self.notebook.add(portuguese_tab, text="Texto Descifrado") #self.languages_menu.entryconfig("Texto Descifrado", state="disabled") #self.translate_button.config(command=lambda langs=["it","pt"],elems=[self.italian_translation, self.portuguese_translation]: # self.translate(langs, None, elems)) self.notebook.pack(fill=tk.BOTH, expand=1)
def init_tabs(self): """Creating Tabs : Dice, Map, Encounters, Treasure""" tab_bar = Notebook(self) tab_bar.pack(fill=BOTH, padx=2, pady=3) #Dice self.tab_dice = DiceTab(tab_bar) tab_bar.add(self.tab_dice, text="Dice") #Map self.tab_map = MapTab(tab_bar) tab_bar.add(self.tab_map, text="Map") #Encounters self.tab_encounters = EncountersTab(tab_bar) tab_bar.add(self.tab_encounters, text="Encounters") #Treasure self.tab_treasure = TreasureTab(tab_bar) tab_bar.add(self.tab_treasure, text="Treasure") #Character Sheet self.tab_character_sheet = CharacterSheetTab(tab_bar) tab_bar.add(self.tab_character_sheet, text="Character Sheet") #Disease Generator self.tab_disease = DiseaseTab(tab_bar) tab_bar.add(self.tab_disease, text="Disease")
def initGUI(self): #create root window self.rootWindow = Tk() self.statusText = StringVar(value=self.statusStr) # at this point, statusStr = "" self.setStatusStr("Simulation not yet started") self.rootWindow.wm_title(self.titleText) # titleText = 'PyCX Simulator' self.rootWindow.protocol('WM_DELETE_WINDOW', self.quitGUI) self.rootWindow.geometry('450x300') self.rootWindow.columnconfigure(0, weight=1) self.rootWindow.rowconfigure(0, weight=1) self.notebook = Notebook(self.rootWindow) # self.notebook.grid(row=0,column=0,padx=2,pady=2,sticky='nswe') # commented out by toshi on 2016-06-21(Tue) 18:30:25 self.notebook.pack(side=TOP, padx=2, pady=2) self.frameRun = Frame() self.frameSettings = Frame() self.frameParameters = Frame() self.frameInformation = Frame() self.notebook.add(self.frameRun,text="Run") self.notebook.add(self.frameSettings,text="Settings") self.notebook.add(self.frameParameters,text="Parameters") self.notebook.add(self.frameInformation,text="Info") self.notebook.pack(expand=NO, fill=BOTH, padx=5, pady=5 ,side=TOP) # self.notebook.grid(row=0, column=0, padx=5, pady=5, sticky='nswe') # commented out by toshi on 2016-06-21(Tue) 18:31:02 self.status = Label(self.rootWindow, width=40,height=3, relief=SUNKEN, bd=1, textvariable=self.statusText) # self.status.grid(row=1,column=0,padx=5,pady=5,sticky='nswe') # commented out by toshi on 2016-06-21(Tue) 18:31:17 self.status.pack(side=TOP, fill=X, padx=5, pady=5, expand=NO) # ----------------------------------- # frameRun # ----------------------------------- # buttonRun self.runPauseString = StringVar() self.runPauseString.set("Run") self.buttonRun = Button(self.frameRun,width=30,height=2,textvariable=self.runPauseString,command=self.runEvent) self.buttonRun.pack(side=TOP, padx=5, pady=5) self.showHelp(self.buttonRun,"Runs the simulation (or pauses the running simulation)") # buttonStep self.buttonStep = Button(self.frameRun,width=30,height=2,text='Step Once',command=self.stepOnce) self.buttonStep.pack(side=TOP, padx=5, pady=5) self.showHelp(self.buttonStep,"Steps the simulation only once") # buttonReset self.buttonReset = Button(self.frameRun,width=30,height=2,text='Reset',command=self.resetModel) self.buttonReset.pack(side=TOP, padx=5, pady=5) self.showHelp(self.buttonReset,"Resets the simulation") # ----------------------------------- # frameSettings # ----------------------------------- can = Canvas(self.frameSettings) lab = Label(can, width=25,height=1,text="Step size ", justify=LEFT, anchor=W,takefocus=0) lab.pack(side='left') self.stepScale = Scale(can,from_=1, to=50, resolution=1,command=self.changeStepSize,orient=HORIZONTAL, width=25,length=150) self.stepScale.set(self.stepSize) self.showHelp(self.stepScale,"Skips model redraw during every [n] simulation steps\nResults in a faster model run.") self.stepScale.pack(side='left') can.pack(side='top') can = Canvas(self.frameSettings) lab = Label(can, width=25,height=1,text="Step visualization delay in ms ", justify=LEFT, anchor=W,takefocus=0) lab.pack(side='left') self.stepDelay = Scale(can,from_=0, to=max(2000,self.timeInterval), resolution=10,command=self.changeStepDelay,orient=HORIZONTAL, width=25,length=150) self.stepDelay.set(self.timeInterval) self.showHelp(self.stepDelay,"The visualization of each step is delays by the given number of milliseconds.") self.stepDelay.pack(side='left') can.pack(side='top') # -------------------------------------------- # frameInformation # -------------------------------------------- scrollInfo = Scrollbar(self.frameInformation) self.textInformation = Text(self.frameInformation, width=45,height=13,bg='lightgray',wrap=WORD,font=("Courier",10)) scrollInfo.pack(side=RIGHT, fill=Y) self.textInformation.pack(side=LEFT,fill=BOTH,expand=YES) scrollInfo.config(command=self.textInformation.yview) self.textInformation.config(yscrollcommand=scrollInfo.set) # -------------------------------------------- # ParameterSetters # -------------------------------------------- for variableSetter in self.parameterSetters: can = Canvas(self.frameParameters) lab = Label(can, width=25,height=1,text=variableSetter.__name__+" ",anchor=W,takefocus=0) lab.pack(side='left') ent = Entry(can, width=11) ent.insert(0, str(variableSetter())) if variableSetter.__doc__ != None and len(variableSetter.__doc__) > 0: self.showHelp(ent,variableSetter.__doc__.strip()) ent.pack(side='left') can.pack(side='top') self.varEntries[variableSetter]=ent if len(self.parameterSetters) > 0: self.buttonSaveParameters = Button(self.frameParameters,width=50,height=1, command=self.saveParametersCmd,text="Save parameters to the running model",state=DISABLED) self.showHelp(self.buttonSaveParameters, "Saves the parameter values.\nNot all values may take effect on a running model\nA model reset might be required.") self.buttonSaveParameters.pack(side='top',padx=5,pady=5) self.buttonSaveParametersAndReset = Button(self.frameParameters,width=50,height=1, command=self.saveParametersAndResetCmd,text="Save parameters to the model and reset the model") self.showHelp(self.buttonSaveParametersAndReset,"Saves the given parameter values and resets the model") self.buttonSaveParametersAndReset.pack(side='top',padx=5,pady=5)
class LpoViewer(Frame): """ This class implements the window of the Lpo viewer. This class implements a menu and tab management for the LpoView. """ def __init__(self, parent): """ Create new window. """ Frame.__init__(self, parent) self.__parent = parent self.__initUI() def __initUI(self): """ Set up UI. """ self.pack(fill=BOTH, expand=1) # notebook for LpoView tabs self.__notebook = Notebook(self) self.__notebook.pack(fill=BOTH, expand=1) # menu bar with file menu self.__menubar = Menu(self.__parent) self.__parent.config(menu=self.__menubar) self.__filemenu = Menu(self.__menubar, tearoff=0) self.__filemenu.add_command(label="Open", command=self.__onOpen) self.__filemenu.add_command(label="Close", command=self.__onClose) self.__filemenu.add_command(label="Exit", command=self.__onExit) self.__menubar.add_cascade(label="File", menu=self.__filemenu) # size and title self.__parent.geometry("300x300+300+300") self.__parent.title("Lpo viewer Tk") def __onExit(self): """ Close the app. """ self.__parent.withdraw() self.quit() def __onClose(self): """ Close the selected LPO. """ tab = self.__notebook.select() if tab != '': self.__notebook.forget(tab) def __onOpen(self): """ Open a new LPO (with file chooser). """ ftypes = [('LPO files', '*.lpo'), ('All files', '*')] dialog = filedialog.Open(self, filetypes=ftypes) file = dialog.show() if file != '': self.openLpo(file) def openLpo(self, file): """ This method shows the LPO contained in the given file as new tab. """ lpos = partialorder.parse_lpo_file(file) # parse LPO from file print(lpos[0]) self.showLpo(lpos[0]) # show first lpo (Assumption: Only 1 LPO in a file) def showLpo(self, lpo): """ Show the given LPO in a new tab. """ lpo_view = LpoView(self.__notebook) self.__notebook.add(lpo_view, text=lpo.name, sticky="nswe") lpo_view.showLpo(lpo)
def change_language(self): language = RUSSIAN_LANGUAGE if get_language( ) == UKRAINIAN_LANGUAGE else UKRAINIAN_LANGUAGE set_language(language) self.destroy_and_rebuild() self.update_table_data() def destroy_and_rebuild(self): for child in self.winfo_children(): child.destroy() self.set_widgets() self.grid_widgets() async def async_generator(generator): for item in generator: yield item if __name__ == '__main__': Base.metadata.create_all(engine) root = tk.Tk() note = Notebook(root) tab1 = Application(note) tab2 = tk.Frame(note) note.add(tab1, text='Main app') note.add(tab2, text='Additional tab') note.grid() root.mainloop()
def __init__(self, *args, **kwargs): ''' node_name: The name of this node. Usually set by ModelNode.__setattr__ automatically. figure_meta: Meta information of figure. The rest parameters are passed to PanedWindow.__init__. ''' node_name = kwargs.pop('node_name', '') super().__init__(node_name=node_name) self.__selected_curve = (None, None) figure_meta = None if 'figure_meta' not in kwargs \ else kwargs.pop('figure_meta') kwargs['orient'] = 'horizontal' paned_window = PanedWindow(*args, **kwargs) paned_window.config(sashwidth=4, sashrelief='groove', bg='forestgreen') # figureTabsStyle = Style() # figureTabsStyle.configure('Figure.TNotebook', tabposition='sw') # figureTabs = Notebook(paned_window, style='Figure.TNotebook') figureTabs = Notebook(paned_window) self.figureTabs = figureTabs figureTabs.bind('<<NotebookTabChanged>>', self._on_tab_change) self.lock_attribute('figureTabs') if figure_meta: self.make_figures(figure_meta) self.lock_elements() paned_window.add(figureTabs, stretch='always') listPan = PanedWindow(paned_window, orient='vertical') listPan.config(sashwidth=4, sashrelief='groove', bg='forestgreen') paned_window.add(listPan, stretch='never') listFrm = Frame(listPan) listPan.add(listFrm, stretch='always') Label(listFrm, text='Curves', bg='#b5d6b0').pack(side='top', fill='x') self.__list = ScrolledList(listFrm, relief='groove') self.__list.list_config(width=20) self.__list.list_click_callback = self._on_list_click self.__list.pack(fill='both', expand='yes') listFrm = Frame(listPan) listPan.add(listFrm, stretch='never') Label(listFrm, text='Indicators', bg='#b5d6b0').pack(side='top', fill='x') self.__indicator_listbox = ScrolledList(listFrm, relief='groove') self.__indicator_listbox.list_config(width=20) self.__indicator_listbox.pack(fill='both', expand='yes') with self.attribute_lock: set_attributes( self, paned_window=paned_window, grid_group_observer=self.GridGroupObserver(self), axis_group_observer=self.AxisGroupObserver(self), clear_group_observer=self.ClearGroupObserver(self), label_group_observer=self.LabelGroupObserver(self), indicator_group_observer=self.IndicatorGroupObserver(self), data_figure_observer=self.DataFigureObserver(self), data_pool=[])
class Config(Toplevel): def __init__(self, master): Toplevel.__init__(self, master, class_=APP_NAME) self.title(_("Settings")) self.grab_set() self.columnconfigure(0, weight=1) self.columnconfigure(1, weight=1) self.rowconfigure(0, weight=1) self.resizable(True, True) self.minsize(470, 574) style = Style(self) self._bg = style.lookup('TFrame', 'background') self.notebook = Notebook(self) self._validate = self.register(self._validate_entry_nb) self.img_color = PhotoImage(master=self, file=IM_COLOR) self.lang = StringVar(self, LANGUAGES[CONFIG.get("General", "language")]) self.gui = StringVar(self, CONFIG.get("General", "trayicon").capitalize()) self._init_general() self._init_widget() self.notebook.grid(sticky='ewsn', row=0, column=0, columnspan=2) Button(self, text=_('Ok'), command=self.ok).grid(row=1, column=0, sticky='e', padx=4, pady=10) Button(self, text=_('Cancel'), command=self.destroy).grid(row=1, column=1, sticky='w', padx=4, pady=10) def _init_general(self): frame_general = Frame(self) self.notebook.add(frame_general, text=_("General")) # --- Language Label(frame_general, text=_("Language")).grid(row=0, column=0, padx=8, pady=4, sticky="e") menu_lang = Menu(frame_general, tearoff=False, background=self._bg) mb = Menubutton(frame_general, menu=menu_lang, textvariable=self.lang) mb.grid(row=0, column=1, padx=8, pady=4, sticky="w") for lang in LANGUAGES: language = LANGUAGES[lang] menu_lang.add_radiobutton(label=language, value=language, variable=self.lang, command=self.translate) # --- gui toolkit Label(frame_general, text=_("GUI Toolkit for the system tray icon")).grid(row=2, column=0, padx=8, pady=4, sticky="e") menu_gui = Menu(frame_general, tearoff=False, background=self._bg) Menubutton(frame_general, menu=menu_gui, width=9, textvariable=self.gui).grid(row=2, column=1, padx=8, pady=4, sticky="w") for toolkit, b in TOOLKITS.items(): if b: menu_gui.add_radiobutton(label=toolkit.capitalize(), value=toolkit.capitalize(), variable=self.gui, command=self.change_gui) # --- Update delay Label(frame_general, text=_("Feed update delay (min)")).grid(row=4, column=0, padx=8, pady=4, sticky="e") self.entry_delay = Entry(frame_general, width=10, justify='center', validate='key', validatecommand=(self._validate, '%P')) self.entry_delay.grid(row=4, column=1, padx=8, pady=4, sticky='w') self.entry_delay.insert( 0, CONFIG.getint('General', 'update_delay') // 60000) # --- image loading timeout Label(frame_general, text=_("Image loading timeout (s)")).grid(row=5, column=0, padx=8, pady=4, sticky="e") self.entry_timeout = Entry(frame_general, width=10, justify='center', validate='key', validatecommand=(self._validate, '%P')) self.entry_timeout.grid(row=5, column=1, padx=8, pady=4, sticky='w') self.entry_timeout.insert( 0, CONFIG.getint('General', 'img_timeout', fallback=10)) # --- Notifications self.notifications = Checkbutton(frame_general, text=_("Activate notifications")) self.notifications.grid(row=6, column=0, padx=8, pady=4, columnspan=2, sticky='w') if CONFIG.getboolean('General', 'notifications', fallback=True): self.notifications.state(('selected', '!alternate')) else: self.notifications.state(('!selected', '!alternate')) # --- Confirm remove feed self.confirm_feed_rem = Checkbutton( frame_general, text=_("Show confirmation dialog before removing feed")) self.confirm_feed_rem.grid(row=7, column=0, padx=8, pady=4, columnspan=2, sticky='w') if CONFIG.getboolean('General', 'confirm_feed_remove', fallback=True): self.confirm_feed_rem.state(('selected', '!alternate')) else: self.confirm_feed_rem.state(('!selected', '!alternate')) # --- Confirm remove cat self.confirm_cat_rem = Checkbutton( frame_general, text=_("Show confirmation dialog before removing category")) self.confirm_cat_rem.grid(row=8, column=0, padx=8, pady=4, columnspan=2, sticky='w') if CONFIG.getboolean('General', 'confirm_cat_remove', fallback=True): self.confirm_cat_rem.state(('selected', '!alternate')) else: self.confirm_cat_rem.state(('!selected', '!alternate')) # --- Confirm update self.confirm_update = Checkbutton( frame_general, text=_("Check for updates on start-up")) self.confirm_update.grid(row=9, column=0, padx=8, pady=4, columnspan=2, sticky='w') if CONFIG.getboolean('General', 'check_update', fallback=True): self.confirm_update.state(('selected', '!alternate')) else: self.confirm_update.state(('!selected', '!alternate')) # --- Splash supported self.splash_support = Checkbutton( frame_general, text=_("Check this box if the widgets disappear when you click")) self.splash_support.grid(row=10, column=0, padx=8, pady=4, columnspan=2, sticky='w') if not CONFIG.getboolean('General', 'splash_supported', fallback=True): self.splash_support.state(('selected', '!alternate')) else: self.splash_support.state(('!selected', '!alternate')) def _init_widget(self): frame_widget = Frame(self) self.notebook.add(frame_widget, text=_('Widget')) # --- font frame_font = Frame(frame_widget) self.title_font = FontFrame(frame_font, CONFIG.get("Widget", "font_title"), True) self.text_font = FontFrame(frame_font, CONFIG.get("Widget", "font")) frame_font.columnconfigure(1, weight=1) Label(frame_font, text=_('Title')).grid(row=0, column=0, sticky='nw', padx=4, pady=4) self.title_font.grid(row=0, column=1) Separator(frame_font, orient='horizontal').grid(row=1, columnspan=2, sticky='ew', padx=4, pady=4) Label(frame_font, text=_('Text')).grid(row=2, column=0, sticky='nw', padx=4, pady=4) self.text_font.grid(row=2, column=1) # --- opacity self.opacity_frame = OpacityFrame(frame_widget, CONFIG.get("Widget", "alpha")) # --- colors frame_color = Frame(frame_widget) frame_color.columnconfigure(1, weight=1) frame_color.columnconfigure(3, weight=1) self.color_bg = ColorFrame(frame_color, CONFIG.get("Widget", "background"), _('Background color')) self.color_fg = ColorFrame(frame_color, CONFIG.get("Widget", "foreground"), _('Foreground color')) self.color_feed_bg = ColorFrame( frame_color, CONFIG.get("Widget", "feed_background"), _('Background color')) self.color_feed_fg = ColorFrame( frame_color, CONFIG.get("Widget", "feed_foreground"), _('Foreground color')) self.color_link = ColorFrame(frame_color, CONFIG.get("Widget", "link_color"), _('Link color')) Label(frame_color, text=_('General')).grid(row=0, column=0, sticky='w', padx=4, pady=2) self.color_bg.grid(row=0, column=1, sticky='e', padx=4, pady=2) self.color_fg.grid(row=1, column=1, sticky='e', padx=4, pady=2) Separator(frame_color, orient='horizontal').grid(row=2, columnspan=4, sticky='ew', padx=4, pady=4) Label(frame_color, text=_('Feed entry')).grid(row=3, column=0, sticky='w', padx=4, pady=2) self.color_feed_bg.grid(row=3, column=1, sticky='e', padx=4, pady=2) self.color_feed_fg.grid(row=4, column=1, sticky='e', padx=4, pady=2) self.color_link.grid(row=5, column=1, sticky='e', padx=4, pady=2) # --- pack Label(frame_widget, text=_('Font'), font='TkDefaultFont 9 bold', anchor='w').pack(padx=4, fill='x') frame_font.pack(fill='x', padx=14) Separator(frame_widget, orient='horizontal').pack(fill='x', pady=6) self.opacity_frame.pack(padx=(4, 10), fill='x') Separator(frame_widget, orient='horizontal').pack(fill='x', pady=6) Label(frame_widget, text=_('Colors'), font='TkDefaultFont 9 bold', anchor='w').pack(padx=4, fill='x') frame_color.pack(fill='x', padx=14) def display_label(self, value): self.opacity_label.configure(text=" {val} %".format( val=int(float(value)))) def translate(self): showinfo( "Information", _("The language setting will take effect after restarting the application" ), parent=self) @staticmethod def _config_size(variable, font): size = variable.get() if size: font.configure(size=size) @staticmethod def _validate_entry_nb(P): """ Allow only to enter numbers""" parts = P.split(".") b = len(parts) < 3 and P != "." for p in parts: b = b and (p == "" or p.isdigit()) return b def change_gui(self): showinfo( "Information", _("The GUI Toolkit setting will take effect after restarting the application" ), parent=self) def ok(self): # --- general CONFIG.set("General", "language", REV_LANGUAGES[self.lang.get()]) CONFIG.set("General", "trayicon", self.gui.get().lower()) CONFIG.set("General", "update_delay", "%i" % (int(self.entry_delay.get()) * 60000)) CONFIG.set("General", "img_timeout", "%i" % (int(self.entry_timeout.get()))) CONFIG.set('General', 'confirm_feed_remove', str(self.confirm_feed_rem.instate(('selected', )))) CONFIG.set('General', 'confirm_cat_remove', str(self.confirm_cat_rem.instate(('selected', )))) CONFIG.set('General', 'check_update', str(self.confirm_update.instate(('selected', )))) CONFIG.set('General', 'splash_supported', str(not self.splash_support.instate(('selected', )))) CONFIG.set('General', 'notifications', str(self.notifications.instate(('selected', )))) # --- widget CONFIG.set("Widget", "alpha", "%i" % self.opacity_frame.get_opacity()) font_title_dic = self.title_font.get_font() font_title_dic[ 'underline'] = 'underline' if font_title_dic['underline'] else '' font_title_dic['family'] = font_title_dic['family'].replace(' ', '\ ') CONFIG.set( "Widget", "font_title", "{family} {size} {weight} {slant} {underline}".format( **font_title_dic)) font_text_dic = self.text_font.get_font() font_text_dic['family'] = font_text_dic['family'].replace(' ', '\ ') CONFIG.set("Widget", "font", "{family} {size}".format(**font_text_dic)) CONFIG.set("Widget", "foreground", self.color_fg.get_color()) CONFIG.set("Widget", "background", self.color_bg.get_color()) CONFIG.set("Widget", "feed_foreground", self.color_feed_fg.get_color()) CONFIG.set("Widget", "feed_background", self.color_feed_bg.get_color()) CONFIG.set("Widget", "link_color", self.color_link.get_color()) self.destroy()
from tkinter import * from tkinter.ttk import Notebook from views.AdjacencyListGraph import AdjacencyListGraph from views.SimpleFormAdd import AddGraphSimpleFormViewCreator from views.AdjacencyMatrixGraph import AdjacencyMatrixGraph from views.IncidenceMatrixGraph import IncidenceMatrixGraph if __name__ == '__main__': root = Tk() notebook = Notebook(root) frame1 = Frame(notebook) frame2 = Frame(notebook) frame3 = Frame(notebook) frame4 = Frame(notebook) notebook.add(frame1, text='Simple form') notebook.add(frame2, text='Adjacency Matrix Graph') notebook.add(frame3, text='Incidence Matrix Graph') notebook.add(frame4, text='Adjacency List Graph') notebook.pack() AddGraphSimpleFormViewCreator(frame1) AdjacencyMatrixGraph(frame2) IncidenceMatrixGraph(frame3) AdjacencyListGraph(frame4) root.mainloop()
class Statistics(Page): """This class provides the statistics view, in table and graphical form""" def __init__(self, mainUI): super().__init__(mainUI) self.columnconfigure(0, weight=1) self.back_button = Button(self, text="< Back", command=lambda: self.go_to("Welcome")()) self.back_button.grid(row=1, padx=(10, 0), pady=(10, 5), sticky="w") self.choose_date_label = Label(self, text="View statistics from event on: ") self.choose_date_label.grid(row=1, column=1) self.date_to_view = StringVar(name="date") self.choose_date_menu = OptionMenu(self, self.date_to_view, *StatsData.available_dates()) self.date_to_view.set(StatsData.available_dates()[0]) self.choose_date_menu.grid(row=1, column=2) self.date_to_view.trace("w", self.update_ui) # hide border # https://groups.google.com/forum/#!topic/comp.lang.tcl/8a6e4tfWJvo s = Style(self) s.configure('flat.TNotebook', borderwidth=0) self.tabbed_section = Notebook(self, style="flat.TNotebook") # # FIXME: padding self.tabbed_section.grid(row=2, columnspan="3", padx=20, sticky="n") # self.button = Button(self, text="Export event statistics as CSV", command=self.csv_export) self.button.grid(row=3, columnspan="3", pady=10, sticky="n") self.update_ui() def update_ui(self, *args): new_date = StatsData.dates[self.date_to_view.get()] for tab in self.tabbed_section.tabs(): self.tabbed_section.forget(tab) for package in StatsData.packages_for_date(new_date): test_tab = PackageView(self.tabbed_section, new_date, package) self.tabbed_section.add(test_tab, text=package) def csv_export(self): date = StatsData.dates[self.date_to_view.get()] file_path = filedialog.asksaveasfilename(filetypes=(("CSV", ".csv"), ), initialfile=date) # code taken from https://docs.python.org/3/library/csv.html if file_path: with open(file_path, 'w', newline='') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csvwriter.writerow(("package name", "quiz", "question id", "question text", "total times shown", "successful answers", "skips", "abandons")) for package in StatsData.packages_for_date(date): for quiz in StatsData.quizzes_for_package(package, date): for q in StatsData.get_data(date, package, quiz): csvwriter.writerow( (q.package_name, q.quiz, q.q_id, q.text, total_times_shown(q), q.successes, q.skips, q.abandons))
#GUIcalculator.py from tkinter import * from tkinter import ttk #theme for lable and entry import csv from datetime import datetime font_title = ("arial", 22) font_result = ("arial", 14) GUI = Tk() GUI.geometry('650x750+450+25') ## TAB from tkinter.ttk import Notebook Tab = Notebook(GUI) F1 = Frame(Tab) F2 = Frame(Tab) F4 = Frame(Tab) F3 = Frame(Tab) Tab.add(F1, text="Sales") Tab.add(F2, text="Add Products") Tab.add(F3, text="All Products") Tab.add(F4, text="History") Tab.pack(fill=BOTH, expand=1) ############## Add Product (Tab) ################### ## Row0 L0 = ttk.Label(F2, text='Barcode', font=font_title) L0.pack(pady=10) # for c center aglin v_barcode = StringVar()
def _make_overview_tab(self, notebook: ttk.Notebook): tab = tk.Frame(notebook) notebook.add(tab, text='Overview') toolbar = tk.Frame(tab, bd=1, relief=tk.RAISED) toolbar.pack(side=tk.TOP, fill=tk.X) chk_pred_visible = tk.Checkbutton( toolbar, text='Show prediction', variable=self.var_pred_visible, command=lambda: self.update_current_tab()) chk_pred_visible.pack(side=tk.LEFT, fill=tk.Y, padx=2, pady=2) if self.model is None: self.var_pred_visible.set(0) chk_pred_visible.configure(state='disabled') chk_gt_visible = tk.Checkbutton( toolbar, text='Show ground truth', variable=self.var_gt_visible, command=lambda: self.update_current_tab()) if hasattr(self.dataset, 'subset') and self.dataset.subset == 'test': self.var_gt_visible.set(0) chk_gt_visible.configure(state='disabled') chk_gt_visible.pack(side=tk.LEFT, fill=tk.Y, padx=2, pady=2) fig = Figure() fig.subplots_adjust(0.05, 0.10, 0.95, 0.95, 0.05, 0.05) canvas = FigureCanvasTkAgg(fig, tab) canvas.draw() canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) nav_toolbar = NavigationToolbar2Tk(canvas, tab) nav_toolbar.update() canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) prev_ax1: Axes3D = None def update_tab(): fig.clf() skels = [] if self.pred_visible: skels.append(self.current_example['pred_skel']) if self.gt_visible: skels.append(self.current_example['gt_skel']) ax1: Axes3D = fig.add_subplot(1, 2, 1, projection='3d') ax2 = fig.add_subplot(1, 2, 2) ax2.imshow(self.current_example['input_image']) ground_truth = root_relative(self.current_example['gt_skel']['original']) for i, skel in enumerate(skels): alpha = 1 / (3 ** i) skel3d = root_relative(skel['camera_space']) if self.is_aligned: skel3d = apply_rigid_alignment(skel3d, ground_truth) plot_skeleton_on_axes3d(skel3d, CanonicalSkeletonDesc, ax1, invert=True, alpha=alpha) plot_skeleton_on_axes(skel['image_space'], CanonicalSkeletonDesc, ax2, alpha=alpha) # Preserve 3D axes view nonlocal prev_ax1 if prev_ax1 is not None: ax1.view_init(prev_ax1.elev, prev_ax1.azim) prev_ax1 = ax1 canvas.draw() return update_tab
scale2 = Scale(window, label="Simple Scale Horizontal", from_=0, to=100, command=getValue2, fg="white", bg="green", activebackground="red", troughcolor="orange", orient="horizontal") scale2.pack(fill="x") frame2 = Frame(window) frame2.pack(fill="both") tablayout = Notebook(frame2) tab1 = Frame(tablayout) tab1.pack(fill="both") label = Label(tab1, text="same Data in Tab 1") label.pack() tablayout.add(tab1, text="TAB 1") tablayout.pack(fill="both") tab1 = Frame(tablayout) tab1.pack(fill="both") label = Label(tab1, text="same Data in Tab 1") label.pack() # adding table into tab for row in range(5):
def _make_heatmap_tab(self, notebook: ttk.Notebook): tab = tk.Frame(notebook) tab_index = len(notebook.tabs()) notebook.add(tab, text='Heatmaps') if self.model is None: notebook.tab(tab_index, state='disabled') toolbar = tk.Frame(tab, bd=1, relief=tk.RAISED) toolbar.pack(side=tk.TOP, fill=tk.X) joint_names = list(sorted(self.dataset.skeleton_desc.joint_names)) opt_joint = tk.OptionMenu( toolbar, self.var_joint, *joint_names, command=lambda event: self.update_current_tab()) opt_joint.pack(side=tk.LEFT, fill=tk.Y, padx=2, pady=2) var_image_visible = tk.IntVar(value=1) chk_image_visible = tk.Checkbutton( toolbar, text='Show image overlay', variable=var_image_visible, command=lambda: self.update_current_tab()) chk_image_visible.pack(side=tk.LEFT, fill=tk.Y, padx=2, pady=2) var_mean_crosshairs = tk.IntVar(value=1) chk_mean_crosshairs = tk.Checkbutton( toolbar, text='Show mean', variable=var_mean_crosshairs, command=lambda: self.update_current_tab()) chk_mean_crosshairs.pack(side=tk.LEFT, fill=tk.Y, padx=2, pady=2) fig = Figure() canvas = FigureCanvasTkAgg(fig, tab) canvas.draw() canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) nav_toolbar = NavigationToolbar2Tk(canvas, tab) nav_toolbar.update() canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) prev_ax3d: Axes3D = None def update_tab(): fig.clf() joint_index = self.dataset.skeleton_desc.joint_names.index(self.var_joint.get()) cmap = plt.get_cmap('gist_yarg') img = self.current_example['input_image'] hms = [ (3, self.current_example['xy_heatmaps'][-1][joint_index], ('x', 'y')), (1, self.current_example['xz_heatmaps'][-1][joint_index], ('x', 'z')), (4, self.current_example['zy_heatmaps'][-1][joint_index], ('z', 'y')), ] for subplot_id, hm, (xlabel, ylabel) in hms: ax = fig.add_subplot(2, 2, subplot_id) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) extent = [0, hm.size(-1), hm.size(-2), 0] ax.imshow(hm, cmap=cmap, extent=extent) if subplot_id == 3 and var_image_visible.get() != 0: ax.imshow(img, extent=extent, alpha=0.5) if var_mean_crosshairs.get() != 0: ax.axvline( np.average(np.arange(0, hm.size(-1)), weights=np.array(hm.sum(-2))), ls='dashed', ) ax.axhline( np.average(np.arange(0, hm.size(-2)), weights=np.array(hm.sum(-1))), ls='dashed', ) size = self.current_example['xy_heatmaps'][-1].size(-1) ax: Axes3D = fig.add_subplot(2, 2, 2, projection='3d') plot_skeleton_on_axes3d( (root_relative(self.current_example['pred_skel']['normalised']) + 1) * 0.5 * size, self.dataset.skeleton_desc, ax, invert=True) ax.set_xlim(0, size) ax.set_ylim(0, size) ax.set_zlim(size, 0) # Preserve 3D axes view nonlocal prev_ax3d if prev_ax3d is not None: ax.view_init(prev_ax3d.elev, prev_ax3d.azim) prev_ax3d = ax canvas.draw() return update_tab
class Root(tk.Tk): def __init__(self): super().__init__() # ---------Initializing-------------------------------------- # import data for gamma, beta, and alpha radiation with open('gamma.pickle', 'rb') as handle: self.gamma_db = pickle.load(handle) with open('beta.pickle', 'rb') as handle: self.beta_db = pickle.load(handle) with open('alpha.pickle', 'rb') as handle: self.alpha_db = pickle.load(handle) # this data includes A, Z, name, half-life, and abundance of each isotope attached to each reference with open('parents.pickle', 'rb') as handle: self.parents1 = pickle.load(handle) # this data includes the decay mode and branching ratio attached to each reference with open('parents2.pickle', 'rb') as handle: self.parents2 = pickle.load(handle) with open('xray.pickle', 'rb') as handle: self.xray_db = pickle.load(handle) self.y_rads = [] # gamma self.b_rads = [] # beta self.a_rads = [] # alpha self.x_rads = [] #x-ray self.y_I = [] # gamma intensity self.b_I = [] # beta intensity self.a_I = [] # alpha intensity self.x_level = [] #orbital shell self.iso = [] self.hl = [] self.act = [] self.title("Table of Radioactive Isotopes Lookup") self.geometry("470x370") self.resizable(width=False, height=False) self.configure(background="Gray") self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) # ---------Tabs---------------------------------------------- self.notebook = Notebook(self) self.tori_tab = tk.Frame(self.notebook) self.conversion_tab = tk.Frame(self.notebook) self.decay_tab = tk.Frame(self.notebook) self.xray_tab = tk.Frame(self.notebook) self.notebook.add(self.tori_tab, text='TORI') self.notebook.add(self.xray_tab, text='X-rays') self.notebook.add(self.decay_tab, text='Decay') self.notebook.add(self.conversion_tab, text='Conversion') # -------TORI TAB-------------------------------------------- # Row 0 # Create Frame 0 self.frame_zero = tk.Frame(self.tori_tab, bd=3, relief=tk.RIDGE) self.frame_zero.grid(row=0, column=0, sticky=tk.NSEW) self.isotope_input_label = tk.Label(self.frame_zero, text="Isotope:") self.isotope_input_label2 = tk.Label( self.frame_zero, text="(Ex: Cs-137, cs137,cesium-137, cesium137)") self.isotope_input = tk.Text(self.frame_zero, height=1, width=20) self.isotope_input_label.grid(row=0, column=0, sticky=tk.NSEW) self.isotope_input_label2.grid(row=0, column=2, rowspan=2, sticky=tk.NSEW) self.isotope_input.grid(row=0, column=1, sticky=tk.NSEW) # Row 1 # Create Frame 1 self.frame_one = tk.Frame(self.tori_tab) self.frame_one.grid(row=1, column=0, sticky=tk.NSEW) self.search_button = tk.Button(self.frame_one, text="Search") self.search_button.grid(row=0, column=0, sticky=tk.NSEW) self.print_button = tk.Button(self.frame_one, text="Print Data") self.print_button.grid(row=0, column=1, sticky=tk.NSEW) # Row 2 # Create Frame 2 self.frame_two = tk.Frame(self.tori_tab) self.frame_two.grid(row=2, column=0, sticky=tk.NSEW) self.gamma_label = tk.Label(self.frame_two, text="Gamma-Rays", width=20, relief=tk.RIDGE, padx=2) self.beta_label = tk.Label(self.frame_two, text="Beta Particles", width=20, relief=tk.RIDGE, padx=2) self.alpha_label = tk.Label(self.frame_two, text="Alpha Particles", width=20, relief=tk.RIDGE, padx=3) self.gamma_label.grid(row=0, column=0, columnspan=2, sticky=tk.NSEW) self.beta_label.grid(row=0, column=2, columnspan=2, sticky=tk.NSEW) self.alpha_label.grid(row=0, column=4, columnspan=2, sticky=tk.NSEW) # Row 3 # Create Frame 3 self.frame_three = tk.Frame(self.tori_tab) self.frame_three.grid(row=3, column=0, sticky=tk.NSEW) for i in range(6): energy_label = tk.Label(self.frame_three, text="Energy (keV)", width=10, bd=3, relief=tk.RIDGE) I_label = tk.Label(self.frame_three, text="Intensity %", width=9, bd=3, relief=tk.RIDGE) if i % 2 == 0: energy_label.grid(row=3, column=i, sticky="E") I_label.grid(row=3, column=i + 1, sticky="E") # Row 4 # Create Frame 4 self.frame_four = tk.Frame(self.tori_tab) self.frame_four.grid(row=4, column=0, sticky=tk.NSEW) self.canvas = tk.Canvas(self.frame_four, width=439, height=200, bd=3, relief=tk.RIDGE) # parent canvas to frame four self.canvas.grid(row=0, column=0, sticky=tk.NSEW) self.vsbar = tk.Scrollbar( self.frame_four, orient=tk.VERTICAL, command=self.canvas.yview) # create scroll bar to frame four self.vsbar.grid(row=0, column=1, sticky=tk.NSEW) self.canvas.configure( yscrollcommand=self.vsbar.set ) # configure canvas to respond to scrollbar object self.radiations_frame = tk.Frame( self.canvas, bd=3, relief=tk.RIDGE) # Create frame for radiations to be inserted onto self.canvas.create_window( (0, 0), window=self.radiations_frame, anchor=tk.NW) # create window with radiations frame self.radiations_frame.update_idletasks() # acquire bbox self.canvas.configure(scrollregion=self.canvas.bbox( tk.ALL)) # configure the canvas to scroll # -------CONVERSION TAB-------------------------------------------- self.start_var = tk.StringVar() self.end_var = tk.StringVar() # Row 0 self.frame_zero = tk.Frame(self.conversion_tab, bd=3, relief=tk.RIDGE) self.frame_zero.grid(row=0, column=0, sticky=tk.NSEW) self.curies_start = tk.Radiobutton(self.frame_zero, text='curies', variable=self.start_var, value='curies', tristatevalue=0) self.millicuries_start = tk.Radiobutton(self.frame_zero, text='millicuries', variable=self.start_var, value='millicuries', tristatevalue=0) self.microcuries_start = tk.Radiobutton(self.frame_zero, text='microcuries', variable=self.start_var, value='microcuries', tristatevalue=0) self.nanocuries_start = tk.Radiobutton(self.frame_zero, text='nanocuries', variable=self.start_var, value='nanocuries', tristatevalue=0) self.bq_start = tk.Radiobutton(self.frame_zero, text='Bq', variable=self.start_var, value='bq', tristatevalue=0) self.kbq_start = tk.Radiobutton(self.frame_zero, text='KBq', variable=self.start_var, value='kbq', tristatevalue=0) self.mbq_start = tk.Radiobutton(self.frame_zero, text='MBq', variable=self.start_var, value='mbq', tristatevalue=0) self.gbq_start = tk.Radiobutton(self.frame_zero, text='GBq', variable=self.start_var, value='gbq', tristatevalue=0) self.tbq_start = tk.Radiobutton(self.frame_zero, text='TBq', variable=self.start_var, value='tbq', tristatevalue=0) self.buffer = tk.Label(self.frame_zero, text="TO", padx=35) self.curies_end = tk.Radiobutton(self.frame_zero, text='curies', variable=self.end_var, value='curies', tristatevalue=0) self.millicuries_end = tk.Radiobutton(self.frame_zero, text='millicuries', variable=self.end_var, value='millicuries', tristatevalue=0) self.microcuries_end = tk.Radiobutton(self.frame_zero, text='microcuries', variable=self.end_var, value='microcuries', tristatevalue=0) self.nanocuries_end = tk.Radiobutton(self.frame_zero, text='nanocuries', variable=self.end_var, value='nanocuries', tristatevalue=0) self.bq_end = tk.Radiobutton(self.frame_zero, text='Bq', variable=self.end_var, value='bq', tristatevalue=0) self.kbq_end = tk.Radiobutton(self.frame_zero, text='KBq', variable=self.end_var, value='kbq', tristatevalue=0) self.mbq_end = tk.Radiobutton(self.frame_zero, text='MBq', variable=self.end_var, value='mbq', tristatevalue=0) self.gbq_end = tk.Radiobutton(self.frame_zero, text='GBq', variable=self.end_var, value='gbq', tristatevalue=0) self.tbq_end = tk.Radiobutton(self.frame_zero, text='TBq', variable=self.end_var, value='tbq', tristatevalue=0) self.curies_start.grid(row=0, column=0, sticky=tk.W) self.millicuries_start.grid(row=1, column=0, sticky=tk.W) self.microcuries_start.grid(row=2, column=0, sticky=tk.W) self.nanocuries_start.grid(row=3, column=0, sticky=tk.W) self.bq_start.grid(row=4, column=0, sticky=tk.W) self.kbq_start.grid(row=5, column=0, sticky=tk.W) self.mbq_start.grid(row=6, column=0, sticky=tk.W) self.gbq_start.grid(row=7, column=0, sticky=tk.W) self.tbq_start.grid(row=8, column=0, sticky=tk.W) self.buffer.grid(row=0, column=1, rowspan=9, sticky=tk.W) self.curies_end.grid(row=0, column=2, sticky=tk.W) self.millicuries_end.grid(row=1, column=2, sticky=tk.W) self.microcuries_end.grid(row=2, column=2, sticky=tk.W) self.nanocuries_end.grid(row=3, column=2, sticky=tk.W) self.bq_end.grid(row=4, column=2, sticky=tk.W) self.kbq_end.grid(row=5, column=2, sticky=tk.W) self.mbq_end.grid(row=6, column=2, sticky=tk.W) self.gbq_end.grid(row=7, column=2, sticky=tk.W) self.tbq_end.grid(row=8, column=2, sticky=tk.W) # Row 1 self.frame_one = tk.Frame(self.conversion_tab, bd=3, relief=tk.RIDGE) self.frame_one.grid(row=1, column=0, sticky=tk.NSEW) self.calc_conv_button = tk.Button(self.frame_one, text="Calculate") self.calc_conv_button.grid(row=0, column=0, sticky=tk.NSEW) # Row 2 self.frame_two = tk.Frame(self.conversion_tab, bd=3, relief=tk.RIDGE) self.frame_two.grid(row=2, column=0, sticky=tk.NSEW) self.start_entry = tk.Text(self.frame_two, height=1, width=20) self.start_entry_label = tk.Label(self.frame_two, text="Start Value:") self.start_entry_label.grid(row=0, column=0, sticky=tk.NSEW) self.start_entry.grid(row=0, column=1, sticky=tk.NSEW) # Row 3 self.frame_three = tk.Frame(self.conversion_tab, bd=3, relief=tk.RIDGE) self.frame_three.grid(row=3, column=0, sticky=tk.NSEW) self.end_entry_label = tk.Label(self.frame_three, text="End Value:") self.end_entry_label.grid(row=0, column=0) # -------DECAY TAB-------------------------------------------- # Row 0 self.frame_zero = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE) self.frame_zero.grid(row=0, column=0, sticky=tk.NSEW) self.iso_input_label = tk.Label(self.frame_zero, text="Isotope:") self.iso_input_label2 = tk.Label( self.frame_zero, text="(Ex: Cs-137, cs137,cesium-137, cesium137)") self.iso_input = tk.Text(self.frame_zero, height=1, width=20) self.iso_input_label.grid(row=0, column=0, sticky=tk.NSEW) self.iso_input_label2.grid(row=0, column=2, rowspan=2, sticky=tk.NSEW) self.iso_input.grid(row=0, column=1, sticky=tk.NSEW) option_list = ('cpm', 'dpm', 'pCi', 'nCi', 'uCi', 'mCi', 'Ci', 'Bq', 'kBq', 'MBq', 'GBq', 'TBq') self.v = tk.StringVar() self.v.set(option_list[0]) # Row 1 self.frame_one = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE) self.frame_one.grid(row=1, column=0, sticky=tk.NSEW) self.orig_act = tk.Label(self.frame_one, text="Enter Original Activity:") self.orig_act_input = tk.Text(self.frame_one, height=1, width=20) self.dropdown = tk.OptionMenu(self.frame_one, self.v, *option_list) self.decay_button = tk.Button(self.frame_one, text="Calculate") self.orig_act.grid(row=0, column=0) self.orig_act_input.grid(row=0, column=1) self.dropdown.grid(row=0, column=2) self.decay_button.grid(row=0, column=3, sticky=tk.NSEW) # Row 2 self.frame_two = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE) self.frame_two.grid(row=2, column=0, sticky=tk.NSEW) self.start_date_label = tk.Label( self.frame_two, text="Enter Original Date(MM/DD/YYYY):") self.start_date_input = tk.Text(self.frame_two, height=1, width=20) self.start_date_label.grid(row=0, column=0) self.start_date_input.grid(row=0, column=1) # Row 3 self.frame_three = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE) self.frame_three.grid(row=3, column=0, sticky=tk.NSEW) self.end_date_label = tk.Label(self.frame_three, text="Enter End Date (MM/DD/YYYY):") self.end_date_input = tk.Text(self.frame_three, height=1, width=20) self.end_date_label.grid(row=0, column=0) self.end_date_input.grid(row=0, column=1) # Row 4 self.frame_four = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE) self.frame_four.grid(row=4, column=0, sticky=tk.NSEW) self.iso_label = tk.Label(self.frame_four, text="Isotope:") self.iso_label.grid(row=0, column=0) # Row 5 self.frame_five = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE) self.frame_five.grid(row=5, column=0, sticky=tk.NSEW) self.half_life_label = tk.Label(self.frame_five, text="Half-life:") self.half_life_label.grid(row=0, column=0) # Row 6 self.frame_six = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE) self.frame_six.grid(row=6, column=0, sticky=tk.NSEW) self.end_act_label = tk.Label(self.frame_six, text="Decayed Activity:") self.end_act_label.grid(row=0, column=0) # -------X-RAY TAB-------------------------------------------- # Row 0 self.frame_zero = tk.Frame(self.xray_tab, bd=3, relief=tk.RIDGE) self.frame_zero.grid(row=0, column=0, sticky=tk.NSEW) self.ele_input_label = tk.Label(self.frame_zero, text="Element:") self.ele_input_label2 = tk.Label(self.frame_zero, text="(Ex: Cs, cs, cesium)") self.ele_input = tk.Text(self.frame_zero, height=1, width=20) self.xray_search_button = tk.Button(self.frame_zero, text='Search') self.ele_input_label.grid(row=0, column=0, sticky=tk.NSEW) self.ele_input_label2.grid(row=0, column=2, rowspan=2, sticky=tk.NSEW) self.ele_input.grid(row=0, column=1, sticky=tk.NSEW) self.xray_search_button.grid(row=0, column=3) # Row 1 self.frame_one = tk.Frame(self.xray_tab, bd=3, relief=tk.RIDGE) self.frame_one.grid(row=1, column=0, sticky=tk.NSEW) self.x_label1 = tk.Label(self.frame_one, text="Energy (keV)", width=15, bd=3, relief=tk.RIDGE) self.x_label2 = tk.Label(self.frame_one, text="Orbital Shell", width=15, bd=3, relief=tk.RIDGE) self.x_label1.grid(row=0, column=0) self.x_label2.grid(row=0, column=1) # Row 2 self.frame_twox = tk.Frame(self.xray_tab) self.frame_twox.grid(row=2, column=0, sticky=tk.NSEW) self.x_canvas = tk.Canvas( self.frame_twox, width=439, height=200, bd=3, relief=tk.RIDGE) # parent canvas to frame four self.x_canvas.grid(row=0, column=0) self.x_vsbar = tk.Scrollbar( self.frame_twox, orient=tk.VERTICAL, command=self.x_canvas.yview) # create scroll bar to frame four self.x_vsbar.grid(row=0, column=1, sticky=tk.NS) self.x_canvas.configure( yscrollcommand=self.x_vsbar.set ) # configure canvas to respond to scrollbar object self.x_frame = tk.Frame( self.x_canvas, bd=3, relief=tk.RIDGE) # Create frame for radiations to be inserted onto self.x_canvas.create_window( (0, 0), window=self.x_frame, anchor=tk.NW) # create window with radiations frame self.x_frame.update_idletasks() # acquire bbox self.x_canvas.configure(scrollregion=self.x_canvas.bbox( tk.ALL)) # configure the canvas to scroll self.testlabel = tk.Label(self.x_frame, text='TEST') self.testlabel.grid(row=0, column=0) #---------Binds--------------------------------------------- self.bind_all("<MouseWheel>", self.mouse_scroll) # TORI TAB self.search_button.bind( "<Button-1>", lambda foo: self.TORI_search(self, self.isotope_input)) self.print_button.bind("<Button-1>", self.print_data) self.isotope_input.bind( "<Return>", lambda foo: self.TORI_search(self, self.isotope_input)) # CONVERSION TAB self.calc_conv_button.bind("<Button-1>", self.calculate_conversion) self.start_entry.bind("<Return>", self.calculate_conversion) # DECAY TAB self.decay_button.bind("<Button-1>", self.calculate_decay) self.iso_input.bind("<Return>", self.calculate_decay) # XRAY TAB self.xray_search_button.bind("<Button-1>", self.search_xrays) self.ele_input.bind("<Return>", self.search_xrays) # ---------Notebook------------------------------------------ self.notebook.pack(fill=tk.BOTH, expand=1) # ---------Functions----------------------------------------- def search_xrays(self, event=None): element = (self.ele_input.get(1.0, tk.END).strip('\n')).lower() self.ele_input.delete(1.0, tk.END) element = element[:1].upper() + element[1:] try: Z = nuclides[element] except KeyError: try: Z = nuclides_long[element] except KeyError: msg.askokcancel("Confirm", "Please enter a valid element") ref = str(Z) + '0000' # clear any existing radiation labels for xr in self.x_rads: xr.destroy() for lvl in self.x_level: lvl.destroy() self.x_rads = [] self.x_level = [] row = 0 for i in range(int(len(self.xray_db[ref]) / 2)): new_x = tk.Label(self.x_frame, text=self.xray_db[ref]['xray' + str(i + 1)], width=15) new_level = tk.Label(self.x_frame, text=self.xray_db[ref]['level' + str(i + 1)], width=15) new_x.grid(row=row, column=0) new_level.grid(row=row, column=1) self.x_rads.append(new_x) self.x_level.append(new_level) row += 1 # reconfigure canvas with updated radiations_frame self.x_canvas.create_window((0, 0), window=self.x_frame, anchor=tk.NW) self.x_frame.update_idletasks() self.x_canvas.configure(scrollregion=self.x_canvas.bbox(tk.ALL)) # Function used to calculate decay from start to end date with original activity # ---------------------------------------------------- def calculate_decay(self, event=None): unit_list = ['ns', 'us', 'ms', 's', 'm', 'd', 'y'] unit_conv_list = [ 1.16e-14, 1.16e-11, 1.15e-8, 1.16e-5, 6.94e-4, 1, 365 ] # Get activity input try: act = float(self.orig_act_input.get(1.0, tk.END).strip('\n')) test = False except ValueError: msg.askokcancel("Confirm", "Please enter a valid activity") #return time in days t = self.get_time(self, self.start_date_input, self.end_date_input) #translate isotope input isotope, A = self.search(self, self.iso_input) ref = self.translate_isotope(isotope, A) #delete any isotope values on screen and put new value on screen for i in self.iso: i.destroy() self.iso = [] iso = tk.Label(self.frame_four, text=isotope + "-" + A) iso.grid(row=0, column=1) self.iso.append(iso) #acquire half-life of isotope input halflife = self.parents1[ref]['halflife'] #delete any halflife values on screen and put new value on screen for h in self.hl: h.destroy() self.hl = [] half_life_label = tk.Label(self.frame_five, text=halflife) half_life_label.grid(row=0, column=1) self.hl.append(half_life_label) #split up num value and unit value of halflife for j in range(len(unit_list)): if unit_list[j] in halflife: halflife = halflife.replace(unit_list[j], "") hl_unit = unit_list[j] break #convert halflife unit to days and convert to decay constant halflife = float(halflife) * unit_conv_list[unit_list.index(hl_unit)] decay_constant = 0.693 / halflife #d^-1 #calculate decay factor and new activity after t passed try: decay_factor = math.exp(-decay_constant * t) new_act = decay_factor * act #delete any activity values ons creen and put new value on screen for a in self.act: a.destroy() self.act = [] new_act_label = tk.Label(self.frame_six, text='{:.2e}'.format(new_act)) new_act_label.grid(row=0, column=1) self.act.append(new_act_label) except (UnboundLocalError, TypeError): pass # Function used to calculate time difference between start and end date # ---------------------------------------------------- def get_time(self, event=None, start=None, end=None): #acquire start and end date, take the difference, return time passed try: start_date = start.get(1.0, tk.END).strip('\n') start_date = start_date.split('/') t1 = dt.datetime(int(start_date[2]), int(start_date[1]), int(start_date[0])) except IndexError: msg.askokcancel("Confirm", "Please enter a valid start date") try: end_date = end.get(1.0, tk.END).strip('\n') end_date = end_date.split('/') t2 = dt.datetime(int(end_date[2]), int(end_date[1]), int(end_date[0])) except IndexError: msg.askokcancel("Confirm", "Please enter a valid end date") try: t = t2 - t1 return t.days except UnboundLocalError: pass # Function used to calculate conversion from one unit to other # ---------------------------------------------------- def calculate_conversion(self, event=None): units = [ 'curies', 'millicuries', 'microcuries', 'nanocuries', 'bq', 'kbq', 'mbq', 'gbq', 'tbq' ] conv_list = [ [1E0, 1E3, 1E6, 1E9, 3.7E10, 3.7E7, 3.7E4, 3.7E1, 3.7E-2], [1E-3, 1E0, 1E3, 1E6, 3.7E7, 3.7E4, 3.7E1, 3.7E-2, 3.7E-5], [1E-6, 1e-3, 1e0, 1e3, 3.7e4, 3.7e1, 3.7e-2, 3.7e-5, 3.7e-8], [1e-9, 1e-6, 1e-3, 1, 3.7e1, 3.7e-2, 3.7e-5, 3.7e-8, 3.7e-11], [2.7e-11, 2.7e-8, 2.7e-5, 2.7e-2, 1, 1e-3, 1e-6, 1e-9, 1e-12], [2.7e-8, 2.7e-5, 2.7e-2, 2.7e1, 1e3, 1, 1e-3, 1e-6, 1e-9], [2.7e-5, 2.7e-2, 2.7e1, 2.7e4, 1e6, 1e3, 1, 1e-3, 1e-6], [2.7e-2, 2.7e1, 2.7e4, 2.7e7, 1e9, 1e6, 1e3, 1, 1e-3], [2.7e1, 2.7e4, 2.7e7, 2.7e10, 1e12, 1e9, 1e6, 1e3, 1], ] start_unit = self.start_var.get() end_unit = self.end_var.get() val = int(self.start_entry.get(1.0, tk.END).strip('\n')) unit_num_start = units.index(start_unit) unit_num_end = units.index(end_unit) conversion = conv_list[unit_num_start][unit_num_end] val = val * conversion self.new_value = tk.Label(self.frame_three, text='{:.2e}'.format(val), width=10) self.new_value.grid(row=0, column=1) # Function used to translate user input and add radiations to GUI # ---------------------------------------------------- def TORI_search(self, event=None, isotope_input=None): isotope, A = self.search(self, isotope_input) ref = self.translate_isotope(isotope, A) self.add_radiation(ref) # function used to acquire information from user input # passes input along to acquire radiation data from db # ---------------------------------------------------- def search(self, event=None, isotope_input=None): # pull data from user input isotope = isotope_input.get(1.0, tk.END).strip('\n') test = False # Logic to acquire formatting of isotope and separate name from A try: count = 0 A = "" # check all characters in isotope variable for char in isotope: try: value = int(char) A += char except ValueError: if char != "-": count += 1 # check if someone entered in a metastable state # includes error checking for miss-types try: if isotope[-1:].lower() == 'm': count -= 1 A += 'm' else: value = int(isotope[-1:]) except ValueError: msg.askokcancel("Confirm", "Please enter a nuclide") test = True # delete user input isotope_input.delete(1.0, tk.END) # if no errors with metastable entry, run if not test: isotope = isotope[:count] isotope = isotope[0].upper() + isotope[1:] return isotope, A self.isotope_print = isotope + A # add to global variable so that print_data can access for file name except IndexError: # if a blank is entered, show this error message msg.askokcancel("Confirm", "Please enter a nuclide") # function used to translate user input to isotope reference number in database # passes reference number onto add_radiation() function # ---------------------------------------------------- def translate_isotope(self, isotope=None, A=None): # test variable for error checking test = False try: # look up the Z from nuclides dictionary Z = str(nuclides[isotope]) except KeyError: # if the isotope isnt in the first dictionary, try the second try: Z = nuclides_long[isotope] except KeyError: # if not in the second, user entered invalid isotope msg.askokcancel("Error", "Valid Nuclide Not Entered:" + isotope) test = True # test to see if a metastable isotope was entered if not test: # if yes, add 300 to A and format appropriately if A[-1:] == 'm': A = str(int(A.replace('m', '')) + 300) ref = Z + "0" + A # if no, format appropriate according to # of decimal # places in A. else: if int(A) < 10: A = "00" + A elif int(A) >= 10 and int(A) < 100: A = "0" + A ref = Z + "0" + A try: return ref except UnboundLocalError: pass # Function used to translate a reference to isotope and atomic # # ---------------------------------------------------- def translate_reference(self, ref=None): isotope = ref.replace(ref[-4:], "") tmp = ref[-3:] if tmp[:2] == '00': A = ref[-1:] elif tmp[:1] == '0': A = ref[-2:] else: A = ref[-3:] return nuclides_rev[int(isotope)], A # add radiations to main screen of all 3 types from isotope # ---------------------------------------------------- def add_radiation(self, ref=None): # clear any existing radiation labels for rad in self.y_rads: rad.destroy() for i in self.y_I: i.destroy() self.y_rads = [] self.y_I = [] # clear any existing radiation labels for rad in self.b_rads: rad.destroy() for i in self.b_I: i.destroy() self.b_rads = [] self.b_I = [] # clear any existing radiation labels for rad in self.a_rads: rad.destroy() for i in self.a_I: i.destroy() self.a_rads = [] self.a_I = [] # add radiation energies of gamma rays count = 1 row = 0 try: r_num = int(len(self.gamma_db[ref]) / 2) #determine number of radiations of each type except KeyError: pass if r_num != 0: for i in range(r_num): new_rad = tk.Label(self.radiations_frame, text=self.gamma_db[ref]['gamma' + str(count)], width=10) new_rad_I = tk.Label(self.radiations_frame, text=self.gamma_db[ref]['I' + str(count)], width=9) new_rad.grid(row=row, column=0) new_rad_I.grid(row=row, column=1) self.y_rads.append(new_rad) self.y_I.append(new_rad_I) row += 1 count += 1 # if no radiations, add blank spaces to maintain width elif r_num == 0: new_rad = tk.Label(self.radiations_frame, text="", width=10) new_rad_I = tk.Label(self.radiations_frame, text="", width=9) new_rad.grid(row=0, column=0) new_rad_I.grid(row=0, column=1) self.y_rads.append(new_rad) self.y_I.append(new_rad_I) # add radiation energies of beta particles count = 1 row = 0 try: r_num = int(len(self.beta_db[ref]) / 2) # determine number of radiations of each type except KeyError: pass if r_num != 0: for i in range(r_num): new_rad = tk.Label(self.radiations_frame, text=self.beta_db[ref]['beta' + str(count)], width=10) new_rad_I = tk.Label(self.radiations_frame, text=self.beta_db[ref]['I' + str(count)], width=9) new_rad.grid(row=row, column=2) new_rad_I.grid(row=row, column=3) self.b_rads.append(new_rad) self.b_I.append(new_rad_I) row += 1 count += 1 # if no radiations, add blank spaces to maintain width elif r_num == 0: new_rad = tk.Label(self.radiations_frame, text="", width=10) new_rad_I = tk.Label(self.radiations_frame, text="", width=9) new_rad.grid(row=0, column=2) new_rad_I.grid(row=0, column=3) self.b_rads.append(new_rad) self.b_I.append(new_rad_I) # add radiation energies of alpha particles count = 1 row = 0 try: r_num = int(len(self.alpha_db[ref]) / 2) # determine number of radiations of each type except KeyError: pass if r_num != 0: for i in range(r_num): new_rad = tk.Label(self.radiations_frame, text=self.alpha_db[ref]['alpha' + str(count)], width=10) new_rad_I = tk.Label(self.radiations_frame, text=self.alpha_db[ref]['I' + str(count)], width=9) new_rad.grid(row=row, column=4) new_rad_I.grid(row=row, column=5) self.a_rads.append(new_rad) self.a_I.append(new_rad_I) row += 1 count += 1 # if no radiations, add blank spaces to maintain width elif r_num == 0: new_rad = tk.Label(self.radiations_frame, text="", width=10) new_rad_I = tk.Label(self.radiations_frame, text="", width=9) new_rad.grid(row=0, column=4) new_rad_I.grid(row=0, column=5) self.a_rads.append(new_rad) self.a_I.append(new_rad_I) # reconfigure canvas with updated radiations_frame self.canvas.create_window((0, 0), window=self.radiations_frame, anchor=tk.NW) self.radiations_frame.update_idletasks() self.canvas.configure(scrollregion=self.canvas.bbox(tk.ALL)) # Print all data # ---------------------------------------------------- def print_data(self, event=None): # Get data from labels in GUI to temporary lists ytmp = [] btmp = [] atmp = [] for i in range(len(self.y_rads)): new = [] new.append(self.y_rads[i].cget("text")) new.append(self.y_I[i].cget("text")) ytmp.append(new) for i in range(len(self.b_rads)): new = [] new.append(self.b_rads[i].cget("text")) new.append(self.b_I[i].cget("text")) btmp.append(new) for i in range(len(self.a_rads)): new = [] new.append(self.a_rads[i].cget("text")) new.append(self.a_I[i].cget("text")) atmp.append(new) # compile all 3 lists into a single two dimensional list # 6 columns across, i rows down for largest # of radiations present outputlist = [] for i in range(max(len(ytmp), len(btmp), len(atmp))): tmp = [] try: if str(ytmp[i][0]) != "": tmp.append(str(ytmp[i][0])) tmp.append(str(ytmp[i][1])) except IndexError: pass try: if str(btmp[i][0]) != "": tmp.append(str(btmp[i][0])) tmp.append(str(btmp[i][1])) except IndexError: pass try: if str(atmp[i][0]) != "": tmp.append(str(atmp[i][0])) tmp.append(str(atmp[i][1])) except IndexError: pass outputlist.append(tmp) # print data to a text file try: with open(self.isotope_print + '.txt', 'w') as f: f.write('Gamma-Rays' + ',' + '' + ',' + 'Beta-Particles' + ',' + '' + ',' + 'Alpha-Particles' + '\n') f.write('Energy(keV)' + ',' + 'Intensity%' + ',' + 'Energy(keV)' + ',' + 'Intensity%' + ',' + 'Energy(keV)' + ',' + 'Intensity%' + '\n') for line in outputlist: for i in range(len(line)): if i != len(line) - 1: f.write(line[i] + ",") else: f.write(line[i]) f.write('\n') except AttributeError: pass # allow the use of the mouse wheel to scroll # ---------------------------------------------------- def mouse_scroll(self, event): self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
################ ######## # Test code if __name__ == "__main__": from DnDReferenceBook.src.dbase_manager import DatabaseManager from tkinter.ttk import Notebook from simple_store import SimpleStoreView root = Tk() dbm = DatabaseManager("../data/dnd_ref_book.db") # dbm.reset("../src/tables.sql", "../src/real.sql") storeList = dbm.get_store_list() nb = Notebook(root) sv = StoreView(root) nb.add(sv, text="Default") for store in storeList: temp = StoreView(nb, dbm.get_store(store["name"], store["location"])) nb.add(temp, text="{} ({})".format(store["name"], store["location"])) nb.grid(row=0, column=0) top = Toplevel(root) ssv = SimpleStoreView(top) ssv.grid(row=0, column=0, sticky=W + E) for i in range(len(storeList)): temp = SimpleStoreView(top, storeList[i]) temp.grid(row=i + 1, column=0, sticky=W + E) root.mainloop()
def _gui(): try: from tkinter import Tk, ttk, filedialog, messagebox, StringVar, IntVar from tkinter.ttk import Button, Entry, Frame, Label, LabelFrame, Notebook, Radiobutton, Style except: sys.exit("Unable to load tkinter. Aborting.") def _check_single(): #check the input and accordingly give the output... for the f_single tab if txt_f_single_entry.get()=="": lbl_f_single_result.config(text="", style="TLabel") elif check_afm(txt_f_single_entry.get()): lbl_f_single_result.config(text="Έγκυρο ΑΦΜ.", style="valid.TLabel") else: lbl_f_single_result.config(text="Άκυρο ΑΦΜ.", style="invalid.TLabel") def _select_input_file(): strv_f_file_input.set(filedialog.askopenfilename(title="Άνοιγμα αρχείου")) if strv_f_file_input.get() != "" and strv_f_file_output.get() != "": btn_f_file_submit.config(state="normal") else: btn_f_file_submit.config(state="disabled") #TODO a much better mechanism to enable / disable btn_f_file_submit is needed. def _select_output_file(): strv_f_file_output.set(filedialog.asksaveasfilename(title="Αποθήκευση ως...")) if strv_f_file_input.get() != "" and strv_f_file_output.get() != "": btn_f_file_submit.config(state="normal") else: btn_f_file_submit.config(state="disabled") def _check_file():#TODO this could / should be merged with the TUI version... input_filepath = strv_f_file_input.get() output_filepath = strv_f_file_output.get() filter_output = intvar_filter_sel.get() try: input_file = open(input_filepath, "r") output_file = open(output_filepath, "w") except: messagebox.showerror(title="Σφάλμα", message="Αδυναμία διαχείρησης των αρχείων που ορίσατε.\n\nΠαρακαλώ επιβεβαιώστε πως το αρχείο με τα δεδομένα υπάρχει, πως έχετε δικαιώματα ανάγνωσης, και πως έχετε δικαιώματα εγγραφής στον κατάλογο εξαγωγής των αποτελεσμάτων.") return counter = {True:0, False:0} for entry in input_file: validation = check_afm(entry.strip()) counter[validation]+=1 if filter_output == 3 and validation == False: output_file.write(entry) elif filter_output == 2 and validation == True: output_file.write(entry) elif filter_output == 1: output_file.write(entry.strip() + "\t" + str(validation) + "\n\r") lbl_f_file_result.config(text="Σύνολο: "+str(counter[True]+counter[False])+"\nΈγκυρα: "+str(counter[True])+"\nΆκυρα: "+str(counter[False])) #create the window main_window = Tk() main_window.title("Έλεγχος εγκυρότητας Α.Φ.Μ. (v 2.0)") main_window.geometry("600x180") main_window.minsize(600,180) #fool arround with styling style = ttk.Style() style.configure("valid.TLabel", background="green") style.configure("empty.TLabel", background="white") style.configure("invalid.TLabel", background="red") style.configure("TNotebook", padding = 10) #create the Notebook tabs = Notebook(main_window) f_single = Frame(tabs) f_file = Frame(tabs) tabs.add(f_single, text="Μεμονομένα Α.Φ.Μ.") tabs.add(f_file, text="Λίστα από αρχείο")#add state="disabled" prior to git push until ready tabs.pack(anchor="nw") #add some widgets in f_single tab lbl_f_single_instructions = Label(f_single, text="Εισάγετε έναν ΑΦΜ για έλεγχο") lbl_f_single_instructions.grid(column=0, row=0) lbl_f_single_result = Label(f_single, text="", width=10, justify="center") lbl_f_single_result.grid(column=1, row=0, rowspan=2, sticky="ewns") txt_f_single_entry = Entry(f_single, width=11) txt_f_single_entry.focus() txt_f_single_entry.bind("<KeyRelease>", lambda e: _check_single() ) txt_f_single_entry.grid(column=0,row=1) #btn_f_single_submit = Button(f_single, text="Έλεγχος", command=_check_single) #btn_f_single_submit.grid(column=0,row=2) #add some widgets in f_file tab lbl_f_file_finput = Label(f_file, text="Άνοιγμα...") lbl_f_file_finput.grid(column=0, row=0) strv_f_file_input = StringVar() txt_f_file_finput = Entry(f_file, textvariable = strv_f_file_input) txt_f_file_finput.grid(column=1, row=0) btn_f_file_finput = Button(f_file, text="...", width=3, command=_select_input_file) btn_f_file_finput.grid(column=2, row=0, sticky="W") lbl_f_file_foutput = Label(f_file, text="Αποθήκευση ως...") lbl_f_file_foutput.grid(column=0, row=1) strv_f_file_output = StringVar() txt_f_file_foutput = Entry(f_file, textvariable = strv_f_file_output) txt_f_file_foutput.grid(column=1, row=1) btn_f_file_foutput = Button(f_file, text="...", width=3, command=_select_output_file) btn_f_file_foutput.grid(column=2, row=1, sticky="W") lf_filter = LabelFrame(f_file, text="Επιστροφή") lf_filter.grid(column=3, row=0, rowspan=2, sticky="ewns") intvar_filter_sel = IntVar() rb_filter_all = Radiobutton(lf_filter, text="Όλων", variable=intvar_filter_sel, value=1) #TODO maybe add command rb_filter_all.pack(anchor="w") rb_filter_all.invoke() rb_filter_true = Radiobutton(lf_filter, text="Έγκυρων", variable=intvar_filter_sel, value=2) rb_filter_true.pack(anchor="w") rb_filter_false = Radiobutton(lf_filter, text="Άκυρων", variable=intvar_filter_sel, value=3) rb_filter_false.pack(anchor="w") lf_result = LabelFrame(f_file, text="Σύνοψη") lf_result.grid(column=4, row=0, rowspan=2, sticky="ewns") lbl_f_file_result = Label(lf_result, text="", width=12)#TODO bring results lbl_f_file_result.pack() btn_f_file_submit = Button(f_file, text="Επεξεργασία", state="disabled", command=_check_file) btn_f_file_submit.grid(column=0, row=2, columnspan=3) btn_main_exit = Button(main_window, text="Έξοδος", command=sys.exit) btn_main_exit.pack(anchor="se") main_window.mainloop()
class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.master.title("Color Clusters") self.pack(fill=BOTH, expand=1) self.init_menu() self.input_image = Image.new("RGBA", _img_size, 0) photo = ImageTk.PhotoImage( img_utils.add_transparency_grid(self.input_image)) self.input_label = Label(self, image=photo) self.input_label.image = photo self.input_label.pack(side=LEFT) self.output_image = Image.new("RGBA", _img_size, 0) photo = ImageTk.PhotoImage( img_utils.add_transparency_grid(self.input_image)) self.out_label = Label(self, image=photo) self.out_label.image = photo self.out_label.pack(side=RIGHT) self.button_list = [] self.timerCount = 0 self.messageString = None self.timerString = None self.thread_queue = queue.Queue() self.algorithm_thread = None self.thread_run_flag = None self.algorithms = Notebook(self) self.algorithms.pack(fill=BOTH, expand=1) def init_menu(self): menu = Menu(self.master) self.master.config(menu=menu) file = Menu(menu) file.add_command(label="Load Image...", command=self.load_image) file.add_command(label="Save Image...", command=self.save_image) file.add_command(label="Exit", command=self.client_exit) menu.add_cascade(label="File", menu=file) ctrl = Menu(menu) ctrl.add_command(label="Suggest Stop", command=self.halt_thread) menu.add_cascade(label="Control", menu=ctrl) def load_image(self): filename = filedialog.askopenfilename(initialdir="../tests/images", title="Choose an image") if filename is "": return self.input_image = Image.open(filename) self.reload_image_label(self.input_image, self.input_label) def save_image(self): filename = filedialog.asksaveasfilename(parent=self, initialdir="../tests/images", initialfile="output.png", title="Save an image", defaultextension=".png", filetypes=(("PNG image", "*.png"), )) if filename is "": return self.output_image.save(filename) def reload_image_label(self, image, label): if image.size[0] > _img_size[0] or image.size[1] > _img_size[1]: img = ImageOps.scale( image, min((expected / actual for expected, actual in zip(_img_size, image.size)))) else: img = image if img.mode != "RGB": img = img_utils.add_transparency_grid(img) img_tk = ImageTk.PhotoImage(img) label.configure(image=img_tk) label.image = img_tk def set_button_state(self, state): for button in self.button_list: button.config(state=state) def run_algorithm(self, algorithm_runner, **kwargs): self.messageString.set("Running!") self.set_button_state(DISABLED) # set required arguments self.thread_run_flag = BooleanVar() self.thread_run_flag.set(True) if 'image' not in kwargs: kwargs['image'] = self.input_image if 'run_var' not in kwargs: kwargs['run_var'] = self.thread_run_flag if 'thread_queue' not in kwargs: kwargs['thread_queue'] = self.thread_queue # start the algorithm on a separate thread self.algorithm_thread = threading.Thread(target=algorithm_runner, kwargs=kwargs, daemon=True) self.algorithm_thread.start() self.after(_delay_time, self.listen_for_result) def halt_thread(self): if self.thread_run_flag is not None: self.thread_run_flag.set(False) def add_algorithm(self, name, algorithm, **kwargs): options = Frame(self.algorithms) options.pack(fill=BOTH, expand=1) message = StringVar() timer = StringVar() Label(options, textvariable=timer).pack(side=BOTTOM) Message(options, textvariable=message, width=_msg_width).pack(side=BOTTOM) arg_entries = {} for key in kwargs: if isinstance(kwargs[key][1], bool): var = BooleanVar() var.set(kwargs[key][1]) arg_entries[key] = var Checkbutton(options, text=kwargs[key][0], variable=var).pack(pady=5) else: Label(options, text=kwargs[key][0]).pack() var = StringVar() var.set(str(kwargs[key][1])) arg_entries[key] = var if key in _dist_param_names: OptionMenu(options, var, *_function_names).pack(pady=5) Label(options, text="Scale factor:").pack() var = StringVar() var.set("(1,1,1,1)") arg_entries[key + "_scale_"] = var Entry(options, textvariable=var).pack(pady=5) else: Entry(options, textvariable=var).pack(pady=5) # capture the algorithm. not sure if this is necessary to build the closure? algorithm_runner = algorithm def callback(): self.messageString = message self.timerString = timer self.timerCount = 0 args = {} for key in arg_entries: if key in _dist_param_names: scale = literal_eval(arg_entries[key + "_scale_"].get()) func = dist_func.decode_string(arg_entries[key].get()) if scale.count(1) != len(scale): print('using scale') func = dist_func.scaled_distance(func, scale) args[key] = func elif key.endswith("_scale_"): pass #ignore the internally used scale field else: args[key] = arg_entries[key].get() self.run_algorithm(algorithm_runner, **args) button = Button(options, text="Run %s" % name, command=callback) button.pack() self.button_list.append(button) self.algorithms.add(options, text=name) def listen_for_result(self): self.timerCount += 1 self.timerString.set("Time Elapsed: %.1f seconds" % (self.timerCount * _delay_time / 1000)) try: # empty the queue while True: result = self.thread_queue.get_nowait() if isinstance(result, str): self.messageString.set(result) elif isinstance(result, Image.Image): self.output_image = result self.messageString.set("Done!") self.set_button_state(NORMAL) self.reload_image_label(self.output_image, self.out_label) # wait for the thread to finish self.algorithm_thread.join() # clear the thread self.algorithm_thread = None self.thread_run_flag = None except queue.Empty: # continue waiting for an image result if self.algorithm_thread is not None and self.algorithm_thread.is_alive( ): self.master.after(_delay_time, self.listen_for_result) # if the thread stopped unexpectedly, stop checking for it elif self.algorithm_thread is not None: self.messageString.set("Error: Thread stopped unexpectedly.") self.set_button_state(NORMAL) self.algorithm_thread = None self.thread_run_flag = None def client_exit(self): if self.algorithm_thread is not None: # do we need to do anything with unfinished threads? pass exit()
def __init__(self, master): Toplevel.__init__(self, master) self.title(_("Delete")) self.grab_set() categories = CONFIG.options("Categories") categories.sort() self.im_moins = PhotoImage(file=IM_MOINS, master=self) self.notebook = Notebook(self) self.notebook.pack(fill='both', expand=True) self.texts = {} frames = {} self.notes = {} for cat in categories: frame = Frame(self.notebook) self.texts[cat] = Text(frame, width=1, height=1, bg=self.cget('bg'), relief='flat', highlightthickness=0, padx=4, pady=4, cursor='arrow') frame.columnconfigure(0, weight=1) frame.rowconfigure(0, weight=1) self.texts[cat].grid(row=0, column=0, sticky='ewsn', padx=(0, 2)) scrolly = Scrollbar(frame, orient='vertical', command=self.texts[cat].yview) scrolly.grid(row=0, column=1, sticky='ns') scrollx = Scrollbar(frame, orient='horizontal', command=self.texts[cat].xview) scrollx.grid(row=1, column=0, sticky='ew') self.texts[cat].configure(xscrollcommand=scrollx.set, yscrollcommand=scrolly.set) frames[cat] = Frame(self.texts[cat]) frames[cat].columnconfigure(0, weight=1, minsize=170) frames[cat].columnconfigure(1, weight=1, minsize=170) frames[cat].columnconfigure(2, minsize=20) self.texts[cat].window_create('1.0', window=frames[cat]) self.notebook.add(frame, text=cat.capitalize(), sticky="ewsn", padding=0) for key, note_data in self.master.note_data.items(): cat = note_data["category"] c, r = frames[cat].grid_size() self.notes[key] = [] title = note_data['title'][:20] title = title.replace('\t', ' ') + ' ' * (20 - len(title)) self.notes[key].append( Label(frames[cat], text=title, font='TkDefaultFont 10 bold')) txt = note_data['txt'].splitlines() if txt: txt = txt[0][:17] + '...' else: txt = '' txt = txt.replace('\t', ' ') + ' ' * (20 - len(txt)) self.notes[key].append(Label(frames[cat], text=txt)) self.notes[key].append( Button(frames[cat], image=self.im_moins, command=lambda iid=key: self.delete_note(iid))) for i, widget in enumerate(self.notes[key]): widget.grid(row=r, column=i, sticky='w', padx=4, pady=4) for txt in self.texts.values(): txt.configure(state='disabled') self.geometry('410x450') self.bind_all("<Button-4>", lambda e: self.scroll(-1)) self.bind_all("<Button-5>", lambda e: self.scroll(1))
def initialize(self): self.master.title("NENR DZ5 - Miljenko Šuflaj") self.pack(fill="both", expand=True) notebook = Notebook(self) notebook.pack() record_gestures_frame = Frame(self) classify_gestures_frame = Frame(self) notebook.add(record_gestures_frame, text="Zabilježi geste") notebook.add(classify_gestures_frame, text="Klasificiraj geste") notebook.enable_traversal() notebook.select(record_gestures_frame) gesture_classification_frame = Frame(classify_gestures_frame) gesture_record_frame_2 = Frame(classify_gestures_frame) gesture_classification_frame.pack(side="top", fill="x", expand=True) gesture_record_frame_2.pack(fill="both") # region Record gesture tab gesture_info_frame = Frame(record_gestures_frame) gesture_record_frame = Frame(record_gestures_frame) gesture_end_frame = Frame(record_gestures_frame) gesture_info_frame.pack(side="top", fill="x") gesture_record_frame.pack(fill="both") gesture_end_frame.pack(side="bottom", fill="x") gesture_name_menu = Menubutton(gesture_info_frame, text="Odaberi gestu za bilježenje...") gesture_name_menu.menu = Menu(gesture_name_menu, tearoff=0) gesture_name_menu["menu"] = gesture_name_menu.menu for i, label in enumerate(GestureWindow.labels): gesture_name_menu.menu.add_command(label=label, command=self.switch_record(i)) self.__recorded_gesture_label = Label(gesture_info_frame) gesture_record_canvas = Canvas(gesture_record_frame, width=700, height=475, bg="white") gesture_record_canvas.current_coords = None gesture_record_canvas.records = list() gesture_record_save_button = Button(gesture_end_frame, text="Pohrani u .tsv", command=self.save_data) gesture_record_delete_button = Button(gesture_end_frame, text="Zaboravi učitane podatke", command=self.delete_internal) gesture_name_menu.pack(side="left", fill="x", padx=5, pady=5, expand=True) self.__recorded_gesture_label.pack(side="left", fill="x", padx=5, pady=5) gesture_record_canvas.pack(fill="both", padx=5, pady=5, expand=True) gesture_record_delete_button.pack(side="left", fill="x", padx=5, pady=5) gesture_record_save_button.pack(side="right", fill="x", padx=5, pady=5) self.switch_record(self.__recorded_gesture_index)() # endregion # region Classify gesture tab gesture_classification_frame = Frame(classify_gestures_frame) gesture_record_frame_2 = Frame(classify_gestures_frame) gesture_classification_frame.pack(side="top", fill="x", expand=True) gesture_record_frame_2.pack(fill="both") classification_labels = list() self.__classification_outputs = list() for category in GestureWindow.labels: classification_labels.append( Label(gesture_classification_frame, text=category)) self.__classification_outputs.append( Label(gesture_classification_frame, text=f"{0.:.01f}%", font=("helvetica", 8))) classification_blank = Label(gesture_classification_frame) classification_labels[-1].pack(side="left", fill="x", padx=5, pady=5) self.__classification_outputs[-1].pack(side="left", fill="x", padx=5, pady=5) classification_blank.pack(side="left", fill="x", padx=50, pady=5) gesture_record_canvas_2 = Canvas(gesture_record_frame_2, width=700, height=525, bg="white") gesture_record_canvas_2.current_coords = None gesture_record_canvas_2.records = list() gesture_record_canvas_2.pack(side="left", fill="both", padx=5, pady=5, expand=True) # endregion # region Functionality for record_canvas in [gesture_record_canvas, gesture_record_canvas_2]: draw_function = self.get_draw_on_canvas_function(record_canvas) record_canvas.bind("<B1-Motion>", draw_function) record_canvas.bind("<ButtonRelease-1>", draw_function) self.__root_window.bind( "<BackSpace>", self.get_delete_currently_drawn(gesture_record_canvas)) self.__root_window.bind( "<Return>", self.get_record_gesture_function(gesture_record_canvas)) gesture_record_canvas_2.bind( "<Leave>", self.get_evaluate_gesture_function(gesture_record_canvas_2)) self.__root_window.bind( "<Delete>", self.get_delete_currently_drawn(gesture_record_canvas_2))
class GUI: ## GUI variables titleText = 'PyCX Simulator' # window title timeInterval = 0 # refresh time in milliseconds running = False modelFigure = None stepSize = 1 currentStep = 0 # Constructor def __init__(self, title='PyCX Simulator', interval=0, stepSize=1, parameterSetters=[]): self.titleText = title self.timeInterval = interval self.stepSize = stepSize self.parameterSetters = parameterSetters self.varEntries = {} self.statusStr = "" self.initGUI() # Initialization def initGUI(self): #create root window self.rootWindow = Tk() self.statusText = StringVar(value=self.statusStr) # at this point, statusStr = "" self.setStatusStr("Simulation not yet started") self.rootWindow.wm_title(self.titleText) # titleText = 'PyCX Simulator' self.rootWindow.protocol('WM_DELETE_WINDOW', self.quitGUI) self.rootWindow.geometry('450x300') self.rootWindow.columnconfigure(0, weight=1) self.rootWindow.rowconfigure(0, weight=1) self.notebook = Notebook(self.rootWindow) # self.notebook.grid(row=0,column=0,padx=2,pady=2,sticky='nswe') # commented out by toshi on 2016-06-21(Tue) 18:30:25 self.notebook.pack(side=TOP, padx=2, pady=2) self.frameRun = Frame() self.frameSettings = Frame() self.frameParameters = Frame() self.frameInformation = Frame() self.notebook.add(self.frameRun,text="Run") self.notebook.add(self.frameSettings,text="Settings") self.notebook.add(self.frameParameters,text="Parameters") self.notebook.add(self.frameInformation,text="Info") self.notebook.pack(expand=NO, fill=BOTH, padx=5, pady=5 ,side=TOP) # self.notebook.grid(row=0, column=0, padx=5, pady=5, sticky='nswe') # commented out by toshi on 2016-06-21(Tue) 18:31:02 self.status = Label(self.rootWindow, width=40,height=3, relief=SUNKEN, bd=1, textvariable=self.statusText) # self.status.grid(row=1,column=0,padx=5,pady=5,sticky='nswe') # commented out by toshi on 2016-06-21(Tue) 18:31:17 self.status.pack(side=TOP, fill=X, padx=5, pady=5, expand=NO) # ----------------------------------- # frameRun # ----------------------------------- # buttonRun self.runPauseString = StringVar() self.runPauseString.set("Run") self.buttonRun = Button(self.frameRun,width=30,height=2,textvariable=self.runPauseString,command=self.runEvent) self.buttonRun.pack(side=TOP, padx=5, pady=5) self.showHelp(self.buttonRun,"Runs the simulation (or pauses the running simulation)") # buttonStep self.buttonStep = Button(self.frameRun,width=30,height=2,text='Step Once',command=self.stepOnce) self.buttonStep.pack(side=TOP, padx=5, pady=5) self.showHelp(self.buttonStep,"Steps the simulation only once") # buttonReset self.buttonReset = Button(self.frameRun,width=30,height=2,text='Reset',command=self.resetModel) self.buttonReset.pack(side=TOP, padx=5, pady=5) self.showHelp(self.buttonReset,"Resets the simulation") # ----------------------------------- # frameSettings # ----------------------------------- can = Canvas(self.frameSettings) lab = Label(can, width=25,height=1,text="Step size ", justify=LEFT, anchor=W,takefocus=0) lab.pack(side='left') self.stepScale = Scale(can,from_=1, to=50, resolution=1,command=self.changeStepSize,orient=HORIZONTAL, width=25,length=150) self.stepScale.set(self.stepSize) self.showHelp(self.stepScale,"Skips model redraw during every [n] simulation steps\nResults in a faster model run.") self.stepScale.pack(side='left') can.pack(side='top') can = Canvas(self.frameSettings) lab = Label(can, width=25,height=1,text="Step visualization delay in ms ", justify=LEFT, anchor=W,takefocus=0) lab.pack(side='left') self.stepDelay = Scale(can,from_=0, to=max(2000,self.timeInterval), resolution=10,command=self.changeStepDelay,orient=HORIZONTAL, width=25,length=150) self.stepDelay.set(self.timeInterval) self.showHelp(self.stepDelay,"The visualization of each step is delays by the given number of milliseconds.") self.stepDelay.pack(side='left') can.pack(side='top') # -------------------------------------------- # frameInformation # -------------------------------------------- scrollInfo = Scrollbar(self.frameInformation) self.textInformation = Text(self.frameInformation, width=45,height=13,bg='lightgray',wrap=WORD,font=("Courier",10)) scrollInfo.pack(side=RIGHT, fill=Y) self.textInformation.pack(side=LEFT,fill=BOTH,expand=YES) scrollInfo.config(command=self.textInformation.yview) self.textInformation.config(yscrollcommand=scrollInfo.set) # -------------------------------------------- # ParameterSetters # -------------------------------------------- for variableSetter in self.parameterSetters: can = Canvas(self.frameParameters) lab = Label(can, width=25,height=1,text=variableSetter.__name__+" ",anchor=W,takefocus=0) lab.pack(side='left') ent = Entry(can, width=11) ent.insert(0, str(variableSetter())) if variableSetter.__doc__ != None and len(variableSetter.__doc__) > 0: self.showHelp(ent,variableSetter.__doc__.strip()) ent.pack(side='left') can.pack(side='top') self.varEntries[variableSetter]=ent if len(self.parameterSetters) > 0: self.buttonSaveParameters = Button(self.frameParameters,width=50,height=1, command=self.saveParametersCmd,text="Save parameters to the running model",state=DISABLED) self.showHelp(self.buttonSaveParameters, "Saves the parameter values.\nNot all values may take effect on a running model\nA model reset might be required.") self.buttonSaveParameters.pack(side='top',padx=5,pady=5) self.buttonSaveParametersAndReset = Button(self.frameParameters,width=50,height=1, command=self.saveParametersAndResetCmd,text="Save parameters to the model and reset the model") self.showHelp(self.buttonSaveParametersAndReset,"Saves the given parameter values and resets the model") self.buttonSaveParametersAndReset.pack(side='top',padx=5,pady=5) # <<<<< Init >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> def setStatusStr(self,newStatus): self.statusStr = newStatus self.statusText.set(self.statusStr) # model control functions for changing parameters def changeStepSize(self,val): self.stepSize = int(val) def changeStepDelay(self,val): self.timeInterval= int(val) def saveParametersCmd(self): for variableSetter in self.parameterSetters: variableSetter(float(self.varEntries[variableSetter].get())) self.setStatusStr("New parameter values have been set") def saveParametersAndResetCmd(self): self.saveParametersCmd() self.resetModel() # <<<< runEvent >>>>> # This event is envoked when "Run" button is clicked. def runEvent(self): self.running = not self.running if self.running: self.rootWindow.after(self.timeInterval,self.stepModel) self.runPauseString.set("Pause") self.buttonStep.configure(state=DISABLED) self.buttonReset.configure(state=DISABLED) if len(self.parameterSetters) > 0: self.buttonSaveParameters.configure(state=NORMAL) self.buttonSaveParametersAndReset.configure(state=DISABLED) else: self.runPauseString.set("Continue Run") self.buttonStep.configure(state=NORMAL) self.buttonReset.configure(state=NORMAL) if len(self.parameterSetters) > 0: self.buttonSaveParameters.configure(state=NORMAL) self.buttonSaveParametersAndReset.configure(state=NORMAL) def stepModel(self): if self.running: self.modelStepFunc() self.currentStep += 1 self.setStatusStr("Step "+str(self.currentStep)) self.status.configure(foreground='black') if (self.currentStep) % self.stepSize == 0: self.drawModel() self.rootWindow.after(int(self.timeInterval*1.0/self.stepSize),self.stepModel) def stepOnce(self): self.running = False self.runPauseString.set("Continue Run") self.modelStepFunc() self.currentStep += 1 self.setStatusStr("Step "+str(self.currentStep)) self.drawModel() if len(self.parameterSetters) > 0: self.buttonSaveParameters.configure(state=NORMAL) def resetModel(self): self.running = False self.runPauseString.set("Run") self.modelInitFunc() self.currentStep = 0; self.setStatusStr("Model has been reset") self.drawModel() def drawModel(self): PL.ion() # bug fix by Alex Hill in 2013 if self.modelFigure == None or self.modelFigure.canvas.manager.window == None: self.modelFigure = PL.figure() self.modelDrawFunc() self.modelFigure.canvas.manager.window.update() PL.show() # bug fix by Hiroki Sayama in 2016 def start(self,func=[]): if len(func)==3: self.modelInitFunc = func[0] self.modelDrawFunc = func[1] self.modelStepFunc = func[2] if (self.modelStepFunc.__doc__ != None and len(self.modelStepFunc.__doc__)>0): self.showHelp(self.buttonStep,self.modelStepFunc.__doc__.strip()) if (self.modelInitFunc.__doc__ != None and len(self.modelInitFunc.__doc__)>0): self.textInformation.config(state=NORMAL) self.textInformation.delete(1.0, END) self.textInformation.insert(END, self.modelInitFunc.__doc__.strip()) self.textInformation.config(state=DISABLED) self.modelInitFunc() self.drawModel() self.rootWindow.mainloop() def quitGUI(self): PL.close('all') self.rootWindow.quit() self.rootWindow.destroy() def showHelp(self, widget,text): def setText(self): self.statusText.set(text) self.status.configure(foreground='blue') def showHelpLeave(self): self.statusText.set(self.statusStr) self.status.configure(foreground='black') widget.bind("<Enter>", lambda e : setText(self)) widget.bind("<Leave>", lambda e : showHelpLeave(self))
class PylinacGUI(Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.notebook = Notebook(self) self.init_pf() self.init_vmat() self.init_catphan() self.init_logs() # self.init_tg51() self.init_star() self.init_planar_imaging() self.init_winstonlutz() self.init_watcher() self.init_help() for child in self.winfo_children(): child.grid_configure(padx=10, pady=10) def init_help(self): def upload(): webbrowser.open( 'https://www.dropbox.com/request/YKRu4AmuPsXu55uQq761') def gotoforum(): webbrowser.open('https://groups.google.com/forum/#!forum/pylinac') def gotogithub(): webbrowser.open('https://github.com/jrkerns/pylinac') def gotortd(): webbrowser.open('https://pylinac.readthedocs.io/en/latest/') self.help_tab = Frame(self.notebook) Label( self.help_tab, text= 'Having trouble?\nWant to donate your images for program improvement?\nUpload them below' ) Button(self.help_tab, text='Upload Files', command=upload) Label(self.help_tab, text='Complete documentation is available on ReadTheDocs') Button(self.help_tab, text='ReadTheDocs', command=gotortd) Label(self.help_tab, text='Help is also available in the Pylinac forum') Button(self.help_tab, text='Go to forum', command=gotoforum) Label( self.help_tab, text= 'The source code of this program and all analyses is available on Github' ) Button(self.help_tab, text='Github', command=gotogithub) self.notebook.add(self.help_tab, text='Help/Upload Images') for child in self.help_tab.winfo_children(): child.grid_configure(padx=10, pady=5) def init_watcher(self): def load_yaml(): f = filedialog.askopenfilename() self.watch_yaml.set(f) def load_dir(): f = filedialog.askdirectory() self.watch_dir.set(f) def process_dir(): watcher.process(directory=self.watch_dir.get(), config_file=self.watch_yaml.get(), force=self.watch_force.get()) def open_dir(): webbrowser.open(self.watch_dir.get()) self.watch_tab = Frame(self.notebook) self.watch_yaml = StringVar( value=osp.join(osp.dirname(__file__), 'watcher_config.yml')) self.watch_dir = StringVar() self.watch_force = BooleanVar(value=False) Button(self.watch_tab, text='Load YAML config file...', command=load_yaml).grid(column=1, row=1) Label(self.watch_tab, textvariable=self.watch_yaml).grid(column=1, row=2) Button(self.watch_tab, text='Select analysis directory...', command=load_dir).grid(column=1, row=3) Label(self.watch_tab, textvariable=self.watch_dir).grid(column=1, row=4) Checkbutton(self.watch_tab, text='Force analysis (even previously analysed files)?', variable=self.watch_force).grid(column=1, row=5) Button(self.watch_tab, text='Process directory', command=process_dir).grid(column=1, row=6) Button(self.watch_tab, text='Open analysis directory', command=open_dir).grid(column=1, row=7) self.notebook.add(self.watch_tab, text='Batch Processor') for child in self.watch_tab.winfo_children(): child.grid_configure(padx=10, pady=5) def init_vmat(self): def load_open(): f = filedialog.askopenfilename() self.vmat_openimg.set(f) def load_dmlc(): f = filedialog.askopenfilename() self.vmat_dmlcimg.set(f) def analyze_vmat(): images = (self.vmat_openimg.get(), self.vmat_dmlcimg.get()) if self.vmat_test.get() == 'DRGS': v = vmat.DRGS(image_paths=images) else: v = vmat.DRMLC(image_paths=images) v.analyze(tolerance=self.vmat_tol.get()) fname = osp.join(self.vmat_dmlcimg.get().replace('.dcm', '.pdf')) v.publish_pdf(fname) self.vmat_pdf.set(fname) utilities.open_path(fname) self.vmat_tab = Frame(self.notebook) self.vmat_openimg = StringVar() self.vmat_dmlcimg = StringVar() self.vmat_test = StringVar(value='DRGS') self.vmat_tol = DoubleVar(value=1.5) self.vmat_pdf = StringVar() Button(self.vmat_tab, text='Load Open Image...', command=load_open).grid(column=1, row=1) Button(self.vmat_tab, text='Load DMLC Image...', command=load_dmlc).grid(column=1, row=3) Label(self.vmat_tab, textvariable=self.vmat_openimg).grid(column=1, row=2) Label(self.vmat_tab, textvariable=self.vmat_dmlcimg).grid(column=1, row=4) Label(self.vmat_tab, text='Test type:').grid(column=1, row=5) Combobox(self.vmat_tab, values=('DRGS', 'DRMLC'), textvariable=self.vmat_test).grid(column=2, row=5) Label(self.vmat_tab, text='Tolerance (%):').grid(column=1, row=6) Entry(self.vmat_tab, width=7, textvariable=self.vmat_tol).grid(column=2, row=6) Button(self.vmat_tab, text='Analyze', command=analyze_vmat).grid(column=1, row=8) Label( self.vmat_tab, text= 'Analysis will analyze the file(s) according to the settings, \nsave a PDF in the same directory as the original file location and then open it.' ).grid(column=1, row=9) Label(self.vmat_tab, text='Save file:').grid(column=1, row=10) Label(self.vmat_tab, textvariable=self.vmat_pdf).grid(column=1, row=11) self.notebook.add(self.vmat_tab, text='VMAT') for child in self.vmat_tab.winfo_children(): child.grid_configure(padx=10, pady=5) def init_pf(self): def load_file(): f = filedialog.askopenfilename() self.pf_file.set(f) def analyze_pf(): if self.pf_filter.get(): pf = picketfence.PicketFence(self.pf_file.get(), filter=3) else: pf = picketfence.PicketFence(self.pf_file.get()) atol = self.pf_atol.get() if self.pf_atol.get() == 0 else None pickets = self.pf_pickets.get() if self.pf_pickets.get( ) == 0 else None hd = self.pf_hdmlc.get() pf.analyze( tolerance=self.pf_tol.get(), action_tolerance=atol, hdmlc=hd, num_pickets=pickets, ) fname = osp.join(self.pf_file.get().replace('.dcm', '.pdf')) pf.publish_pdf(fname) self.pf_pdf.set(fname) utilities.open_path(fname) self.pf_tab = Frame(self.notebook) self.pf_filter = BooleanVar(value=False) self.pf_file = StringVar() self.pf_tol = DoubleVar(value=0.5) self.pf_atol = DoubleVar(value=0.25) self.pf_pickets = IntVar(value=10) self.pf_hdmlc = BooleanVar(value=False) self.pf_pdf = StringVar() Checkbutton(self.pf_tab, text='Apply median filter', variable=self.pf_filter).grid(column=1, row=3) Button(self.pf_tab, text='Load File...', command=load_file).grid(column=1, row=1) Label(self.pf_tab, text='File:').grid(column=1, row=2) Label(self.pf_tab, textvariable=self.pf_file).grid(column=2, row=3) Label(self.pf_tab, text='Tolerance (mm):').grid(column=1, row=4) Entry(self.pf_tab, width=7, textvariable=self.pf_tol).grid(column=2, row=4) Label(self.pf_tab, text='Action Tolerance (mm):').grid(column=1, row=5) Entry(self.pf_tab, width=7, textvariable=self.pf_atol).grid(column=2, row=5) Label(self.pf_tab, text='Number of pickets:').grid(column=1, row=6) Entry(self.pf_tab, width=7, textvariable=self.pf_pickets).grid(column=2, row=6) Checkbutton(self.pf_tab, text='HD-MLC?', variable=self.pf_hdmlc).grid(column=1, row=7) Button(self.pf_tab, text='Analyze', command=analyze_pf).grid(column=1, row=8) Label( self.pf_tab, text= 'Analysis will analyze the file according to the settings, \nsave a PDF in the same directory as the original file location and then open it.' ).grid(column=1, row=9) self.notebook.add(self.pf_tab, text='Picket Fence') for child in self.pf_tab.winfo_children(): child.grid_configure(padx=10, pady=5) def init_catphan(self): def load_dir(): f = filedialog.askdirectory() self.ct_file.set(f) def load_zip(): f = filedialog.askopenfilename() self.ct_file.set(f) def analyze_cbct(): if osp.isdir(self.ct_file.get()): cat = getattr(ct, self.ct_catphantype.get())(self.ct_file.get()) fname = osp.join(self.ct_file.get(), 'CBCT Analysis.pdf') else: cat = getattr(ct, self.ct_catphantype.get()).from_zip( self.ct_file.get()) fname = self.ct_file.get().replace('.zip', '.pdf') cat.analyze(hu_tolerance=self.ct_hu.get(), thickness_tolerance=self.ct_thickness.get(), scaling_tolerance=self.ct_scaling.get()) cat.publish_pdf(fname) self.ct_pdf.set(fname) utilities.open_path(fname) self.ct_tab = Frame(self.notebook) self.ct_file = StringVar() self.ct_catphantype = StringVar() self.ct_hu = IntVar(value=40) self.ct_scaling = DoubleVar(value=1) self.ct_thickness = DoubleVar(value=0.2) self.ct_pdf = StringVar() Label(self.ct_tab, text='Load EITHER a directory or ZIP file').grid(column=2, row=1) Button(self.ct_tab, text='Load Directory...', command=load_dir).grid(column=2, row=2) Button(self.ct_tab, text='Load ZIP file...', command=load_zip).grid(column=2, row=3) Label(self.ct_tab, textvariable=self.ct_file).grid(column=2, row=4) Label(self.ct_tab, text='CatPhan type:').grid(column=2, row=5) Combobox(self.ct_tab, values=('CatPhan504', 'CatPhan503', 'CatPhan600', 'CatPhan604'), textvariable=self.ct_catphantype).grid(column=2, row=6) Label(self.ct_tab, text='HU Tolerance (HU):').grid(column=1, row=7) Entry(self.ct_tab, width=7, textvariable=self.ct_hu).grid(column=1, row=8) Label(self.ct_tab, text='Scaling tolerance (mm):').grid(column=2, row=7) Entry(self.ct_tab, width=7, textvariable=self.ct_scaling).grid(column=2, row=8) Label(self.ct_tab, text='Thickness tolerance (mm):').grid(column=3, row=7) Entry(self.ct_tab, width=7, textvariable=self.ct_thickness).grid(column=3, row=8) Button(self.ct_tab, text='Analyze', command=analyze_cbct).grid(column=2, row=9) Label( self.ct_tab, text= 'Analysis will analyze the file(s) according to the settings, \nsave a PDF in the same directory as the original file location and then open it.' ).grid(column=2, row=10) Label(self.ct_tab, text='Save file:').grid(column=2, row=11) Label(self.ct_tab, textvariable=self.ct_pdf).grid(column=2, row=12) self.notebook.add(self.ct_tab, text='CatPhan') for child in self.ct_tab.winfo_children(): child.grid_configure(padx=10, pady=5) def init_logs(self): def load_log(): f = filedialog.askopenfilename() self.log_file.set(f) def analyze_log(): log = log_analyzer.load_log(self.log_file.get()) name, _ = osp.splitext(self.log_file.get()) fname = name + '.pdf' log.publish_pdf(fname) self.log_pdf.set(fname) utilities.open_path(fname) self.log_tab = Frame(self.notebook) self.log_file = StringVar() self.log_pdf = StringVar() Button(self.log_tab, text='Load log file...', command=load_log).grid(column=1, row=1) Label(self.log_tab, textvariable=self.log_file).grid(column=1, row=2) Button(self.log_tab, text='Analyze', command=analyze_log).grid(column=1, row=9) Label( self.log_tab, text= 'Analysis will analyze the file(s) according to the settings, \nsave a PDF in the same directory as the original file location and then open it.' ).grid(column=1, row=10) Label(self.log_tab, text='Save file:').grid(column=1, row=11) Label(self.log_tab, textvariable=self.log_pdf).grid(column=1, row=12) self.notebook.add(self.log_tab, text='Machine Logs') for child in self.log_tab.winfo_children(): child.grid_configure(padx=10, pady=5) def init_star(self): def load_star(): f = filedialog.askopenfilename() self.star_file.set(f) def analyze_star(): star = starshot.Starshot(self.star_file.get(), sid=self.star_sid.get(), dpi=self.star_dpi.get()) star.analyze(radius=self.star_radius.get(), tolerance=self.star_tolerance.get(), recursive=self.star_recursive.get()) name, _ = osp.splitext(self.star_file.get()) fname = name + '.pdf' star.publish_pdf(fname) self.star_pdf.set(fname) utilities.open_path(fname) self.star_tab = Frame(self.notebook) self.star_file = StringVar() self.star_pdf = StringVar() self.star_dpi = DoubleVar() self.star_sid = DoubleVar() self.star_radius = DoubleVar(value=0.85) self.star_tolerance = DoubleVar(value=1) self.star_recursive = BooleanVar(value=True) Button(self.star_tab, text='Load starshot file...', command=load_star).grid(column=1, row=1) Label(self.star_tab, textvariable=self.star_file).grid(column=1, row=2) Label(self.star_tab, text='DPI (if file is not DICOM):').grid(column=1, row=3) Entry(self.star_tab, width=7, textvariable=self.star_dpi).grid(column=2, row=3) Label(self.star_tab, text='SID (mm; if file is not DICOM):').grid(column=1, row=4) Entry(self.star_tab, width=7, textvariable=self.star_sid).grid(column=2, row=4) Label(self.star_tab, text='Normalized analysis radius (0.2-1.0):').grid(column=1, row=5) Entry(self.star_tab, width=7, textvariable=self.star_radius).grid(column=2, row=5) Checkbutton(self.star_tab, text='Recursive analysis?', variable=self.star_recursive).grid(column=1, row=6) Label(self.star_tab, text='Tolerance (mm):').grid(column=1, row=7) Entry(self.star_tab, width=7, textvariable=self.star_tolerance).grid(column=2, row=7) Button(self.star_tab, text='Analyze', command=analyze_star).grid(column=1, row=9) Label( self.star_tab, text= 'Analysis will analyze the file(s) according to the settings, \nsave a PDF in the same directory as the original file location and then open it.' ).grid(column=1, row=10) Label(self.star_tab, text='Save file:').grid(column=1, row=11) Label(self.star_tab, textvariable=self.star_pdf).grid(column=1, row=12) self.notebook.add(self.star_tab, text='Starshot') for child in self.star_tab.winfo_children(): child.grid_configure(padx=10, pady=5) def init_planar_imaging(self): def load_phan(): f = filedialog.askopenfilename() self.phan_file.set(f) def analyze_phan(): phantom = getattr(planar_imaging, self.phan_type.get())(self.phan_file.get()) phantom.analyze() name, _ = osp.splitext(self.phan_file.get()) fname = name + '.pdf' phantom.publish_pdf(fname) self.phan_pdf.set(fname) utilities.open_path(fname) self.phan_tab = Frame(self.notebook) self.phan_file = StringVar() self.phan_pdf = StringVar() self.phan_locon = DoubleVar(value=0.1) self.phan_hicon = DoubleVar(value=0.5) self.phan_inver = BooleanVar(value=False) self.phan_type = StringVar(value='LeedsTOR') Button(self.phan_tab, text='Load planar phantom DICOM file...', command=load_phan).grid(column=1, row=1) Label(self.phan_tab, textvariable=self.phan_file).grid(column=1, row=2) Label(self.phan_tab, text='Phantom:').grid(column=1, row=3) Combobox(self.phan_tab, values=('LeedsTOR', 'LasVegas', 'StandardImagingQC3'), textvariable=self.phan_type).grid(column=2, row=3) Label(self.phan_tab, text='Low contrast threshold:').grid(column=1, row=4) Entry(self.phan_tab, width=7, textvariable=self.phan_locon).grid(column=2, row=4) Label(self.phan_tab, text='High contrast threshold:').grid(column=1, row=5) Entry(self.phan_tab, width=7, textvariable=self.phan_hicon).grid(column=2, row=5) Checkbutton(self.phan_tab, text='Force image inversion?', variable=self.phan_inver).grid(column=1, row=6) Button(self.phan_tab, text='Analyze', command=analyze_phan).grid(column=1, row=9) Label( self.phan_tab, text= 'Analysis will analyze the file(s) according to the settings, \nsave a PDF in the same directory as the original file location and then open it.' ).grid(column=1, row=10) Label(self.phan_tab, text='Save file:').grid(column=1, row=11) Label(self.phan_tab, textvariable=self.phan_pdf).grid(column=1, row=12) self.notebook.add(self.phan_tab, text='2D Phantoms') for child in self.phan_tab.winfo_children(): child.grid_configure(padx=10, pady=5) def init_winstonlutz(self): def load_dir(): f = filedialog.askdirectory() self.wl_file.set(f) def load_zip(): f = filedialog.askopenfilename() self.wl_file.set(f) def analyze_wl(): if osp.isdir(self.wl_file.get()): wl = winston_lutz.WinstonLutz(self.wl_file.get()) fname = osp.join(self.wl_file.get(), 'W-L Analysis.pdf') else: wl = winston_lutz.WinstonLutz.from_zip(self.wl_file.get()) fname = self.wl_file.get().replace('.zip', '.pdf') wl.publish_pdf(fname) self.wl_pdf.set(fname) utilities.open_path(fname) self.wl_tab = Frame(self.notebook) self.wl_file = StringVar() self.wl_pdf = StringVar() Label(self.wl_tab, text='Load EITHER a directory or ZIP file').grid(column=2, row=1) Button(self.wl_tab, text='Load Directory...', command=load_dir).grid(column=2, row=2) Button(self.wl_tab, text='Load ZIP file...', command=load_zip).grid(column=2, row=3) Label(self.wl_tab, textvariable=self.wl_file).grid(column=2, row=4) Button(self.wl_tab, text='Analyze', command=analyze_wl).grid(column=2, row=9) Label( self.wl_tab, text= 'Analysis will analyze the file(s) according to the settings, \nsave a PDF in the same directory as the original file location and then open it.' ).grid(column=2, row=10) Label(self.wl_tab, text='Save file:').grid(column=2, row=11) Label(self.wl_tab, textvariable=self.wl_pdf).grid(column=2, row=12) self.notebook.add(self.wl_tab, text='Winston-Lutz') for child in self.wl_tab.winfo_children(): child.grid_configure(padx=10, pady=5) def init_tg51(self): self.tg_tab = Frame(self.notebook) self.tg_pdf = StringVar() self.tg_temp = DoubleVar(value=22) self.tg_press = DoubleVar(value=760) r, r2 = itertools.count(), itertools.count() Label(self.tg_tab, text='Temperature (C):').grid(column=1, row=next(r)) Entry(self.tg_tab, width=7, textvariable=self.tg_temp).grid(column=2, row=next(r2)) Label(self.tg_tab, text='Pressure (mmHg):').grid(column=1, row=next(r)) Entry(self.tg_tab, width=7, textvariable=self.tg_press).grid(column=2, row=next(r2)) self.notebook.add(self.tg_tab, text='TG-51') for child in self.tg_tab.winfo_children(): child.grid_configure(padx=10, pady=5)
def init_project_frame( self ) : projframe = Frame(self) ###################### #The Project Entry Form # #Current design inherited from others #is very bad. It should have been made as #json or dictionary as is in this point #then the subsequent coding will be much #eaiser. #BK ###################### BS=StringVar() self.eprojectid = eprojectid= StringVar() self.eorganism = eorganism=StringVar() self.eanalyst = eanalyst=StringVar() self.epoc = epoc=StringVar() self.epi = epi=StringVar() self.euser = euser=StringVar() self.eflowcell = eflowcell=StringVar() self.eplatform = eplatform=StringVar() eplatform.set("Illumina") self.technique = technique=StringVar() self.pipehome = pipehome=StringVar() pipehome.set(PIPELINER_HOME) editframe = Frame( self ) editframe.grid( column=0, row=3, columnspan=3 ) projpanel1 = LabelFrame(editframe,text="Project Information") #,fg=textLightColor,bg=baseColor) projpanel1.pack( side = TOP, fill=X, padx=10, pady=5, expand=YES ) pipeline_panel = LabelFrame(editframe, text="Global Settings") pipeline_panel.pack( side=TOP, fill=X, padx=10, pady=5, expand=YES ) l=Label( pipeline_panel, text="Genome:" ) l.grid(row=1,column=3,sticky=W,padx=0,pady=5) l = Label( pipeline_panel, text="Pipeline Family:" ) l.grid(row=1,column=1,sticky=W,padx=0,pady=5) annotations=['hg19','mm10','mm9','hg38','GRCh38'] self.annotation = annotation = StringVar() annotation.set(annotations[0]) #annotation.trace('w', lambda *_ :settargets(annotation) ) om = OptionMenu(pipeline_panel, annotation, *annotations, command=self.set_pipeline) #, command=lambda _:makejson("refsets")) om.config() #bg = widgetBgColor,fg=widgetFgColor) om["menu"].config() #bg = widgetBgColor,fg=widgetFgColor) om.grid(row=1,column=4,sticky=W,padx=10,pady=10) pfamilys = ['exomeseq', 'rnaseq', 'genomeseq', 'mirseq', 'ChIPseq', 'scrnaseq'] self.pfamily = pfamily = StringVar() pfamily.set('Select a pipeline') om = OptionMenu(pipeline_panel, pfamily, *pfamilys, command=self.set_pipeline) #, command=lambda _:makejson(pfamily.get())) om.config() #bg = widgetBgColor,fg=widgetFgColor) om["menu"].config() #bg = widgetBgColor,fg=widgetFgColor) om.grid(row=1,column=2,sticky=W,padx=10,pady=5) #add_button = Button( pipeline_panel, # text="Set a pipeline", # command=self.add_pipeline # ) #add_button.grid(row=1, column=5, sticky=W, padx=10, pady=5) self.notebook = notebook = Notebook( editframe ) self.pipelineframe = None #the pipeline frame in the notebook frame! projpanel2 = Frame(notebook) #,fg=textLightColor,bg=baseColor) projpanel2.pack( side = LEFT, fill=BOTH, padx=10, pady=5, expand=YES ) notebook.add( projpanel2, text="Project Description" ) notebook.pack( side=LEFT, fill=BOTH, padx=10, pady=5, expand=YES ) Dscrollbar = Scrollbar(projpanel2) Dscrollbar.grid(row=2,column=4,rowspan=40) self.description =description= Text(projpanel2, width=75, height=28, #bg=commentBgColor, #fg=commentFgColor, font=("nimbus mono bold","10"), yscrollcommand = Dscrollbar.set) description.delete("1.0", END) description.insert(INSERT, "Enter CCBR Project Description and Notes here.") #description.bind('<FocusOut>',lambda _:makejson("none")) description.grid(row=2,column=3,sticky="e",padx=10,pady=5) Dscrollbar['command']=description.yview L=Label(projpanel1, text="Project Id", anchor="ne" ) #,bg=baseColor,fg=textLightColor) E = Entry(projpanel1, bd =2, width=20, #bg=entryBgColor, #fg=entryFgColor, textvariable=eprojectid ) #L.pack(pady=5,padx=5) #E.pack(pady=1,padx=5) L.grid(row=0, column=0, sticky=W, padx=10, pady=5) E.grid(row=0, column=2, sticky=W, padx=10, pady=5) eprojectid.set("project") #eprojectid.trace('w', makejson) L2=Label(projpanel1, text = "(Examples: CCBR-nnn,Labname or short project name)", anchor="ne" )#,bg="firebrick",fg="white") L2.grid(row=0, column=3, padx=10, pady=5, sticky="w") L=Label( projpanel1, text="Email address", anchor="ne")#,bg=baseColor,fg=textLightColor) E = Entry( projpanel1, bd =2, width=20, #bg=entryBgColor, #fg=entryFgColor, textvariable=euser) L3 = Label(projpanel1, text ="(Mandatory field: must use @nih.gov email address)", anchor="ne") L3.grid(row=1,column=3,padx=10,pady=5,sticky="w") L.grid(row=1,column=0,sticky=W,padx=10,pady=5) E.grid(row=1,column=2,sticky=W,padx=10,pady=5) #euser.trace('w', makejson) L=Label(projpanel1,text="Flow Cell ID",anchor="ne") E = Entry(projpanel1, bd =2, width=20, textvariable=eflowcell )#, bg=entryBgColor) L4=Label( projpanel1, text="(Examples: FlowCellID, Labname, date or short project name)", anchor="ne" )#,bg="firebrick",fg="white") L4.grid(row=2,column=3,padx=10,pady=5,sticky="w") L.grid(row=2,column=0,sticky=W,padx=10,pady=5) E.grid(row=2,column=2,sticky=W,padx=10,pady=5) eflowcell.set("stats") #eflowcell.trace('w', makejson) Projscrollbar = Scrollbar(projframe) Projscrollbar.grid(row=2,column=4,rowspan=30 ) self.jsonconf = jsonconf = Text( projframe, width=80, height=30, #bg=projectBgColor, #fg=projectFgColor, font=("nimbus mono bold","11"), yscrollcommand = Projscrollbar.set) Projscrollbar['command']=jsonconf.yview jsonconf.grid(row=3,column=0,sticky="e",padx=10,pady=5)
class PomodoroParams(Frame): def __init__(self, parent, **options): """ créer le Toplevel permettant de modifier les paramètres """ Frame.__init__(self, parent, **options) self.onglets = Notebook(self) self.onglets.pack(fill='both', expand=True) self.im_color = PhotoImage(master=self, file=IM_COLOR) self.im_plus = PhotoImage(master=self, file=IM_ADD) self.im_moins = PhotoImage(master=self, file=IM_DEL) self.okfct = self.register(only_nb) self.style = Style(self) self.nb_task = len(CONFIG.options("PomodoroTasks")) # --- Général (temps, police et langue) self.general = Frame(self.onglets, padding=10) self.general.columnconfigure(1, weight=1) self.onglets.add(self.general, text=_("General")) # --- --- Temps Label(self.general, text=_("Times (min)"), style='title.TLabel').grid(row=0, pady=4, padx=(2, 10), sticky="w") self.time_frame = Frame(self.general) self.time_frame.grid(row=0, column=1, sticky="w", padx=4) Label(self.time_frame, text=_("Work")).grid(row=0, padx=4, column=0) self.travail = Entry(self.time_frame, width=4, justify='center', validatecommand=(self.okfct, '%P'), validate='key') self.travail.insert(0, CONFIG.get("Pomodoro", "work_time")) self.travail.grid(row=0, column=1, padx=(0, 10)) Label(self.time_frame, text=_("Break")).grid(row=0, column=2, padx=4) self.pause = Entry(self.time_frame, width=4, justify='center', validatecommand=(self.okfct, '%P'), validate='key') self.pause.insert(0, CONFIG.get("Pomodoro", "break_time")) self.pause.grid(row=0, column=3, padx=(0, 10)) Label(self.time_frame, text=_("Rest")).grid(row=0, column=4, padx=4) self.rest = Entry(self.time_frame, width=4, justify='center', validatecommand=(self.okfct, '%P'), validate='key') self.rest.insert(0, CONFIG.get("Pomodoro", "rest_time")) self.rest.grid(row=0, column=5) Separator(self.general, orient='horizontal').grid(row=1, columnspan=2, sticky="ew", pady=10) # --- --- Police Label(self.general, text=_("Font"), style='title.TLabel').grid(row=2, sticky='nw', padx=(2, 10)) self.font = FontFrame(self.general, font=CONFIG.get('Pomodoro', 'font'), sample_text="02:17") self.font.grid(row=2, column=1, padx=4, sticky='w') Separator(self.general, orient='horizontal').grid(row=3, columnspan=2, sticky="ew", pady=10) # --- --- Opacity self.opacity = OpacityFrame(self.general) self.opacity.grid(row=5, columnspan=2, sticky='w', padx=(2, 4), pady=4) Separator(self.general, orient='horizontal').grid(row=6, columnspan=2, sticky="ew", pady=10) # --- --- Son self.sound = SoundFrame(self.general, CONFIG.get("Pomodoro", "beep"), mute=CONFIG.getboolean("Pomodoro", "mute"), label=_("Sound"), style='title.TLabel') self.sound.grid(row=7, columnspan=2, sticky='ew', pady=4) # --- Couleurs self.couleurs = Frame(self.onglets, padding=10) self.couleurs.columnconfigure(3, weight=1) self.onglets.add(self.couleurs, text=_("Colors")) self.bg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "background"), _("Background")) self.work_bg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "work_bg"), _("Background")) self.break_bg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "break_bg"), _("Background")) self.rest_bg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "rest_bg"), _("Background")) self.fg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "foreground"), _("Foreground")) self.work_fg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "work_fg"), _("Foreground")) self.break_fg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "break_fg"), _("Foreground")) self.rest_fg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "rest_fg"), _("Foreground")) Label(self.couleurs, text=_("General"), style='title.TLabel').grid(row=0, column=0, pady=4, padx=(2, 10), sticky="w") self.bg.grid(row=0, column=1, sticky='e', padx=8, pady=4) self.fg.grid(row=0, column=2, sticky='e', padx=8, pady=4) Separator(self.couleurs, orient='horizontal').grid(row=1, sticky="ew", pady=10, columnspan=4) Label(self.couleurs, text=_("Work"), style='title.TLabel').grid(row=2, column=0, pady=4, padx=(2, 10), sticky="w") self.work_bg.grid(row=2, column=1, sticky='e', padx=8, pady=4) self.work_fg.grid(row=2, column=2, sticky='e', padx=8, pady=4) Separator(self.couleurs, orient='horizontal').grid(row=3, sticky="ew", pady=10, columnspan=4) Label(self.couleurs, text=_("Break"), style='title.TLabel').grid(row=4, column=0, pady=4, padx=(2, 10), sticky="w") self.break_bg.grid(row=4, column=1, sticky='e', padx=8, pady=4) self.break_fg.grid(row=4, column=2, sticky='e', padx=8, pady=4) Separator(self.couleurs, orient='horizontal').grid(row=5, sticky="ew", pady=10, columnspan=4) Label(self.couleurs, text=_("Rest"), style='title.TLabel').grid(row=6, column=0, pady=4, padx=(2, 10), sticky="w") self.rest_bg.grid(row=6, column=1, sticky='e', padx=8, pady=4) self.rest_fg.grid(row=6, column=2, sticky='e', padx=8, pady=4) # --- Tasks self.stats = Frame(self.onglets, padding=10) self.stats.columnconfigure(0, weight=1) self.stats.rowconfigure(2, weight=1) self.onglets.add(self.stats, text=_("Tasks")) # graph legend legend_frame = Frame(self.stats) Label(legend_frame, style='title.TLabel', text=_('Maximum number of rows in the legend')).pack(side='left') self.legend_row_nb = Entry(legend_frame, width=4, justify='center', validatecommand=(self.okfct, '%P'), validate='key') self.legend_row_nb.insert( 0, CONFIG.get('Pomodoro', 'legend_max_height', fallback='6')) self.legend_row_nb.pack(side='left', padx=4) # task colors can = Canvas(self.stats, bg=self.style.lookup('TFrame', 'background'), highlightthickness=0, width=1, relief='flat') scroll = AutoScrollbar(self.stats, orient='vertical', command=can.yview) can.configure(yscrollcommand=scroll.set) self.task_frame = Frame(can) can.create_window(0, 0, anchor='nw', window=self.task_frame) tasks = CONFIG.options("PomodoroTasks") tasks.sort() cmap = [CONFIG.get("PomodoroTasks", task) for task in tasks] self.tasks = {} self._tasks_btns = {} for i, (coul, task) in enumerate(zip(cmap, tasks)): self.tasks[task] = ColorFrame(self.task_frame, coul, task.capitalize()) self.tasks[task].grid(row=i, column=0, sticky='e', padx=4, pady=4) b = Button(self.task_frame, image=self.im_moins, padding=2, command=lambda t=task: self.del_task(t)) b.grid(row=i, column=1, sticky='w', padx=4, pady=4) self._tasks_btns[task] = b if len(tasks) == 1: self._tasks_btns[tasks[0]].state(['disabled']) legend_frame.grid(row=0, columnspan=2, sticky='w', pady=4) Label(self.stats, text=_('Colors in the statistic graph'), style='title.TLabel').grid(row=1, column=0, sticky='w', pady=4) can.grid(row=2, column=0, sticky='ewns') scroll.grid(row=2, column=1, sticky='ns') Button(self.stats, image=self.im_plus, command=self.add_task).grid(row=3, column=0, sticky='w') self.update_idletasks() can.configure(width=self.task_frame.winfo_reqwidth()) can.configure(scrollregion=can.bbox('all')) can.bind('<4>', lambda e: self._scroll(e, -1)) can.bind('<5>', lambda e: self._scroll(e, 1)) self.task_frame.bind( '<Configure>', lambda e: can.configure(scrollregion=can.bbox('all'))) def _scroll(self, event, delta): if event.widget.yview() != (0, 1): event.widget.yview_scroll(delta, 'units') def choix_couleur(self, type_mode): """ sélection de la couleur du fond/texte pour chaque mode (travail/pause/repos) """ coul = askcolor(self.style.lookup(type_mode + ".TButton", 'background'), parent=self) if coul: self.style.configure(type_mode + ".TButton", background=coul) def coul_stat(self, i): """ choix des couleurs pour l'affichage des stats """ coul = askcolor(self.style.lookup("t%i.TButton" % i, "background"), parent=self) if coul: self.style.configure("t%i.TButton" % i, background=coul) def valide(self): """Update config and return whether the pomodor timer should be stopped.""" old_tpsw = CONFIG.getint("Pomodoro", "work_time") old_tpsp = CONFIG.getint("Pomodoro", "break_time") old_tpsr = CONFIG.getint("Pomodoro", "rest_time") try: tpsw = int(self.travail.get()) except ValueError: # empty entry tpsw = 0 if tpsw == 0: tpsw = old_tpsw try: tpsp = int(self.pause.get()) except ValueError: tpsp = 0 if tpsp == 0: tpsp = old_tpsp try: tpsr = int(self.rest.get()) except ValueError: tpsr = 0 if tpsr == 0: tpsr = old_tpsr sound, mute = self.sound.get() font_prop = self.font.get_font() font = "{} {}".format(font_prop['family'].replace(' ', '\ '), font_prop['size']) try: legend_rows = int(self.legend_row_nb.get()) except ValueError: legend_rows = 0 if legend_rows == 0: legend_rows = CONFIG.getint("Pomodoro", "legend_max_height") if not os.path.exists(sound): showerror( _("Error"), _("The file {filepath} does not exists, the old file will be used." ).format(filepath=sound)) sound = CONFIG.get("Pomodoro", "beep") CONFIG.set("Pomodoro", "alpha", str(self.opacity.get_opacity())) CONFIG.set("Pomodoro", "font", font) CONFIG.set("Pomodoro", "background", self.bg.get_color()) CONFIG.set("Pomodoro", "foreground", self.fg.get_color()) CONFIG.set("Pomodoro", "work_time", str(tpsw)) CONFIG.set("Pomodoro", "work_bg", self.work_bg.get_color()) CONFIG.set("Pomodoro", "work_fg", self.work_fg.get_color()) CONFIG.set("Pomodoro", "break_time", str(tpsp)) CONFIG.set("Pomodoro", "break_bg", self.break_bg.get_color()) CONFIG.set("Pomodoro", "break_fg", self.break_fg.get_color()) CONFIG.set("Pomodoro", "rest_time", str(tpsr)) CONFIG.set("Pomodoro", "rest_bg", self.rest_bg.get_color()) CONFIG.set("Pomodoro", "rest_fg", self.rest_fg.get_color()) CONFIG.set("Pomodoro", "beep", sound) CONFIG.set("Pomodoro", "mute", str(mute)) CONFIG.set("Pomodoro", "legend_max_height", str(legend_rows)) for task, widget in self.tasks.items(): CONFIG.set("PomodoroTasks", task, widget.get_color()) return old_tpsw != tpsw or old_tpsp != tpsp or old_tpsr != old_tpsr def del_task(self, task): """ Suppression de tâches """ rep = askyesno( _("Confirmation"), _("Are you sure you want to delete the task {task}? This action cannot be undone." ).format(task=task.capitalize())) if rep: CONFIG.remove_option("PomodoroTasks", task) # remove stats db = sqlite3.connect(PATH_STATS) cursor = db.cursor() try: cursor.execute('DROP TABLE {}'.format( scrub(task.lower().replace(' ', '_')))) db.commit() except sqlite3.OperationalError: pass # no stats yet db.close() self.tasks[task].destroy() self._tasks_btns[task].destroy() del self.tasks[task] del self._tasks_btns[task] if len(CONFIG.options("PomodoroTasks")) == 1: CONFIG.set("PomodoroTasks", _("Work"), CMAP[0]) self._tasks_btns[CONFIG.options("PomodoroTasks")[0]].state( ['disabled']) save_config() def add_task(self): def ajoute(event=None): task = nom.get().lower().strip() if task in self.tasks: showerror( _("Error"), _("The task {task} already exists.").format(task=task), parent=self) elif task: coul = CMAP[(len(self.tasks) + 1) % len(CMAP)] i = self.task_frame.grid_size()[1] + 1 self.tasks[task] = ColorFrame(self.task_frame, coul, task.capitalize()) self.tasks[task].grid(row=i, column=0, sticky='e', padx=4, pady=4) b = Button(self.task_frame, image=self.im_moins, padding=2, command=lambda t=task: self.del_task(t)) b.grid(row=i, column=1, sticky='w', padx=4, pady=4) self._tasks_btns[task] = b self._tasks_btns[CONFIG.options("PomodoroTasks")[0]].state( ['!disabled']) top.destroy() top = Toplevel(self) top.title(_("New task")) top.transient(self) top.grab_set() nom = Entry(top, width=20, justify='center') nom.grid(row=0, columnspan=2, sticky="ew") nom.focus_set() nom.bind('<Key-Return>', ajoute) Button(top, text=_("Cancel"), command=top.destroy).grid(row=1, column=0) Button(top, text=_("Ok"), command=ajoute).grid(row=1, column=1) top.wait_window(top)
class MainWindow(object): def __init__(self, root, options): ''' ----------------------------------------------------- | main button toolbar | ----------------------------------------------------- | < ma | in content area > | | | | | File list | File name | | | | ----------------------------------------------------- | status bar area | ----------------------------------------------------- ''' # Obtain and expand the current working directory. if options.path: base_path = os.path.abspath(options.path) else: base_path = os.path.abspath(os.getcwd()) self.base_path = os.path.normcase(base_path) # Create a filename normalizer based on the CWD. self.filename_normalizer = filename_normalizer(self.base_path) # Set up dummy coverage data self.coverage_data = {'lines': {}, 'total_coverage': None} # Root window self.root = root self.root.title('Duvet') self.root.geometry('1024x768') # Prevent the menus from having the empty tearoff entry self.root.option_add('*tearOff', tk.FALSE) # Catch the close button self.root.protocol("WM_DELETE_WINDOW", self.cmd_quit) # Catch the "quit" event. self.root.createcommand('exit', self.cmd_quit) # Setup the menu self._setup_menubar() # Set up the main content for the window. self._setup_button_toolbar() self._setup_main_content() self._setup_status_bar() # Now configure the weights for the root frame self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=0) self.root.rowconfigure(1, weight=1) self.root.rowconfigure(2, weight=0) ###################################################### # Internal GUI layout methods. ###################################################### def _setup_menubar(self): # Menubar self.menubar = tk.Menu(self.root) # self.menu_Apple = Menu(self.menubar, name='Apple') # self.menubar.add_cascade(menu=self.menu_Apple) self.menu_file = tk.Menu(self.menubar) self.menubar.add_cascade(menu=self.menu_file, label='File') self.menu_help = tk.Menu(self.menubar) self.menubar.add_cascade(menu=self.menu_help, label='Help') # self.menu_Apple.add_command(label='Test', command=self.cmd_dummy) # self.menu_file.add_command(label='New', command=self.cmd_dummy, accelerator="Command-N") # self.menu_file.add_command(label='Close', command=self.cmd_dummy) self.menu_help.add_command(label='Open Documentation', command=self.cmd_duvet_docs) self.menu_help.add_command(label='Open Duvet project page', command=self.cmd_duvet_page) self.menu_help.add_command(label='Open Duvet on GitHub', command=self.cmd_duvet_github) self.menu_help.add_command(label='Open BeeWare project page', command=self.cmd_beeware_page) # last step - configure the menubar self.root['menu'] = self.menubar def _setup_button_toolbar(self): ''' The button toolbar runs as a horizontal area at the top of the GUI. It is a persistent GUI component ''' # Main toolbar self.toolbar = tk.Frame(self.root) self.toolbar.grid(column=0, row=0, sticky=(tk.W, tk.E)) # Buttons on the toolbar self.refresh_button = tk.Button(self.toolbar, text='Refresh', command=self.cmd_refresh) self.refresh_button.grid(column=0, row=0) # Coverage summary for currently selected file. self.coverage_total_summary = tk.StringVar() self.coverage_total_summary_label = Label( self.toolbar, textvariable=self.coverage_total_summary, anchor=tk.E, padding=(5, 0, 5, 0), font=('Helvetica','20') ) self.coverage_total_summary_label.grid(column=1, row=0, sticky=(tk.W, tk.E)) self.toolbar.columnconfigure(0, weight=0) self.toolbar.columnconfigure(1, weight=1) self.toolbar.rowconfigure(0, weight=0) def _setup_main_content(self): ''' Sets up the main content area. It is a persistent GUI component ''' # Main content area self.content = PanedWindow(self.root, orient=tk.HORIZONTAL) self.content.grid(column=0, row=1, sticky=(tk.N, tk.S, tk.E, tk.W)) # Create the tree/control area on the left frame self._setup_left_frame() self._setup_project_file_tree() self._setup_global_file_tree() # Create the output/viewer area on the right frame self._setup_code_area() # Set up weights for the left frame's content self.content.columnconfigure(0, weight=1) self.content.rowconfigure(0, weight=1) self.content.pane(0, weight=1) self.content.pane(1, weight=4) def _setup_left_frame(self): ''' The left frame mostly consists of the tree widget ''' # The left-hand side frame on the main content area # The tabs for the two trees self.tree_notebook = Notebook( self.content, padding=(0, 5, 0, 5) ) self.content.add(self.tree_notebook) def _setup_project_file_tree(self): self.project_file_tree_frame = tk.Frame(self.content) self.project_file_tree_frame.grid(column=0, row=0, sticky=(tk.N, tk.S, tk.E, tk.W)) self.tree_notebook.add(self.project_file_tree_frame, text='Project') self.project_file_tree = FileView(self.project_file_tree_frame, normalizer=self.filename_normalizer, root=self.base_path) self.project_file_tree.grid(column=0, row=0, sticky=(tk.N, tk.S, tk.E, tk.W)) # # The tree's vertical scrollbar self.project_file_tree_scrollbar = tk.Scrollbar(self.project_file_tree_frame, orient=tk.VERTICAL) self.project_file_tree_scrollbar.grid(column=1, row=0, sticky=(tk.N, tk.S)) # # Tie the scrollbar to the text views, and the text views # # to each other. self.project_file_tree.config(yscrollcommand=self.project_file_tree_scrollbar.set) self.project_file_tree_scrollbar.config(command=self.project_file_tree.yview) # Setup weights for the "project_file_tree" tree self.project_file_tree_frame.columnconfigure(0, weight=1) self.project_file_tree_frame.columnconfigure(1, weight=0) self.project_file_tree_frame.rowconfigure(0, weight=1) # Handlers for GUI events self.project_file_tree.bind('<<TreeviewSelect>>', self.on_file_selected) def _setup_global_file_tree(self): self.global_file_tree_frame = tk.Frame(self.content) self.global_file_tree_frame.grid(column=0, row=0, sticky=(tk.N, tk.S, tk.E, tk.W)) self.tree_notebook.add(self.global_file_tree_frame, text='Global') self.global_file_tree = FileView(self.global_file_tree_frame, normalizer=self.filename_normalizer) self.global_file_tree.grid(column=0, row=0, sticky=(tk.N, tk.S, tk.E, tk.W)) # # The tree's vertical scrollbar self.global_file_tree_scrollbar = tk.Scrollbar(self.global_file_tree_frame, orient=tk.VERTICAL) self.global_file_tree_scrollbar.grid(column=1, row=0, sticky=(tk.N, tk.S)) # # Tie the scrollbar to the text views, and the text views # # to each other. self.global_file_tree.config(yscrollcommand=self.global_file_tree_scrollbar.set) self.global_file_tree_scrollbar.config(command=self.global_file_tree.yview) # Setup weights for the "global_file_tree" tree self.global_file_tree_frame.columnconfigure(0, weight=1) self.global_file_tree_frame.columnconfigure(1, weight=0) self.global_file_tree_frame.rowconfigure(0, weight=1) # Handlers for GUI events self.global_file_tree.bind('<<TreeviewSelect>>', self.on_file_selected) def _setup_code_area(self): self.code_frame = tk.Frame(self.content) self.code_frame.grid(column=1, row=0, sticky=(tk.N, tk.S, tk.E, tk.W)) # Label for current file self.current_file = tk.StringVar() self.current_file_label = Label(self.code_frame, textvariable=self.current_file) self.current_file_label.grid(column=0, row=0, sticky=(tk.W, tk.E)) # Code display area self.code = CodeView(self.code_frame) self.code.grid(column=0, row=1, sticky=(tk.N, tk.S, tk.E, tk.W)) # Set up weights for the code frame's content self.code_frame.columnconfigure(0, weight=1) self.code_frame.rowconfigure(0, weight=0) self.code_frame.rowconfigure(1, weight=1) self.content.add(self.code_frame) def _setup_status_bar(self): # Status bar self.statusbar = tk.Frame(self.root) self.statusbar.grid(column=0, row=2, sticky=(tk.W, tk.E)) # Coverage summary for currently selected file. self.coverage_file_summary = tk.StringVar() self.coverage_file_summary_label = Label(self.statusbar, textvariable=self.coverage_file_summary) self.coverage_file_summary_label.grid(column=0, row=0, sticky=(tk.W, tk.E)) self.coverage_file_summary.set('No file selected') # Main window resize handle self.grip = Sizegrip(self.statusbar) self.grip.grid(column=1, row=0, sticky=(tk.S, tk.E)) # Set up weights for status bar frame self.statusbar.columnconfigure(0, weight=1) self.statusbar.columnconfigure(1, weight=0) self.statusbar.rowconfigure(0, weight=0) ###################################################### # Utility methods for controlling content ###################################################### def show_file(self, filename, line=None, breakpoints=None): """Show the content of the nominated file. If specified, line is the current line number to highlight. If the line isn't currently visible, the window will be scrolled until it is. breakpoints is a list of line numbers that have current breakpoints. If refresh is true, the file will be reloaded and redrawn. """ # Set the filename label for the current file self.current_file.set(self.filename_normalizer(filename)) # Update the code view; this means changing the displayed file # if necessary, and updating the current line. if filename != self.code.filename: self.code.filename = filename missing = self.coverage_data['missing'].get(os.path.normcase(filename), []) executed = self.coverage_data['lines'].get(os.path.normcase(filename), []) n_executed = len(executed) n_missing = len(missing) self.code.highlight_missing(missing) self.coverage_file_summary.set('%s/%s lines executed' % (n_executed, n_executed + n_missing)) self.code.line = line def load_coverage(self): "Load and display coverage data" # Store the old list of files that have coverage data. # We do this so we can identify stale data on the tree. old_files = set(self.coverage_data['lines'].keys()) old_total_coverage = self.coverage_data['total_coverage'] loaded = False retry = True while not loaded and retry: try: # Load the new coverage data cov = coverage.coverage() cov.load() # Override precision for coverage reporting. coverage.results.Numbers.set_precision(1) if cov.data.measured_files(): self.coverage_data = { 'lines': {}, 'missing': {}, } totals = coverage.results.Numbers() # Update the coverage display of every file mentioned in the file. for filename in cov.data.measured_files(): filename = os.path.normcase(filename) node = nodify(filename) dirname, basename = os.path.split(filename) # If the normalized version of the filename is the same as the # filename, then the file *isn't* under the project root. if filename == self.filename_normalizer(filename): file_tree = self.global_file_tree else: file_tree = self.project_file_tree try: # # Make sure the file exists on the tree. file_tree.insert_filename(dirname, basename) # Compute the coverage percentage analysis = cov._analyze(filename) self.coverage_data['lines'][filename] = analysis.statements self.coverage_data['missing'][filename] = analysis.missing file_coverage = analysis.numbers.pc_covered totals = totals + analysis.numbers file_tree.set(node, 'coverage', analysis.numbers.pc_covered_str) # file_tree.set(node, 'branch_coverage', str(len(lines))) # Set the color of the tree node based on coverage if file_coverage < 70.0: file_tree.item(node, tags=['file', 'code', 'bad']) elif file_coverage < 80.0: file_tree.item(node, tags=['file', 'code', 'poor']) elif file_coverage < 90.0: file_tree.item(node, tags=['file', 'code', 'ok']) elif file_coverage < 99.9: file_tree.item(node, tags=['file', 'code', 'good']) else: file_tree.item(node, tags=['file', 'code', 'perfect']) except coverage.misc.NoSource: # could mean the file was deleted after running coverage file_tree.item(node, tags=['bad']) # We've updated the file, so we know it isn't stale. try: old_files.remove(filename) except KeyError: # File wasn't loaded before; ignore this. pass # Clear out any stale coverage data for filename in old_files: node = nodify(filename) if file_tree.exists(node): file_tree.set(node, 'coverage', '') file_tree.item(node, tags=['file', 'code']) # Compute the overall coverage total_coverage = totals.pc_covered self.coverage_data['total_coverage'] = total_coverage coverage_text = u'%.1f%%' % total_coverage # Update the text with up/down arrows to reflect change if old_total_coverage is not None: if total_coverage > old_total_coverage: coverage_text = coverage_text + u' ⬆' elif total_coverage < old_total_coverage: coverage_text = coverage_text + u' ⬇' self.coverage_total_summary.set(coverage_text) # Set the color based on coverage level. if total_coverage < 70.0: self.coverage_total_summary_label.configure(foreground='red') elif total_coverage < 80.0: self.coverage_total_summary_label.configure(foreground='orange') elif total_coverage < 90.0: self.coverage_total_summary_label.configure(foreground='blue') elif total_coverage < 99.9: self.coverage_total_summary_label.configure(foreground='cyan') else: self.coverage_total_summary_label.configure(foreground='green') # Refresh the file display current_file = self.code._filename if current_file: self.code._filename = None self.show_file(current_file) loaded = True else: retry = tkMessageBox.askretrycancel( message="Couldn't find coverage data file. Have you generated coverage data? Is the .coverage in your current working directory", title='No coverage data found' ) except Exception as e: retry = tkMessageBox.askretrycancel( message="Couldn't load coverage data -- data file may be corrupted (Error was: %s)" % e, title='Problem loading coverage data' ) return loaded ###################################################### # TK Main loop ###################################################### def mainloop(self): self.root.mainloop() ###################################################### # TK Command handlers ###################################################### def cmd_quit(self): "Quit the program" self.root.quit() def cmd_refresh(self, event=None): "Refresh the coverage data" self.load_coverage() def cmd_duvet_page(self): "Show the Duvet project page" webbrowser.open_new('http://pybee.org/duvet') def cmd_duvet_github(self): "Show the Duvet GitHub repo" webbrowser.open_new('http://github.com/pybee/duvet') def cmd_duvet_docs(self): "Show the Duvet documentation" # If this is a formal release, show the docs for that # version. otherwise, just show the head docs. if len(NUM_VERSION) == 3: webbrowser.open_new('https://duvet.readthedocs.io/en/v%s/' % VERSION) else: webbrowser.open_new('https://duvet.readthedocs.io/') def cmd_beeware_page(self): "Show the BeeWare project page" webbrowser.open_new('http://pybee.org/') ###################################################### # Handlers for GUI actions ###################################################### def on_file_selected(self, event): "When a file is selected, highlight the file and line" if event.widget.selection(): filename = event.widget.selection()[0] # Display the file in the code view if os.path.isfile(filename): self.show_file(filename=filename) else: self.code.filename = None
def __init__(self, parent, **options): """ créer le Toplevel permettant de modifier les paramètres """ Frame.__init__(self, parent, **options) self.onglets = Notebook(self) self.onglets.pack(fill='both', expand=True) self.im_color = PhotoImage(master=self, file=IM_COLOR) self.im_plus = PhotoImage(master=self, file=IM_ADD) self.im_moins = PhotoImage(master=self, file=IM_DEL) self.okfct = self.register(only_nb) self.style = Style(self) self.nb_task = len(CONFIG.options("PomodoroTasks")) # --- Général (temps, police et langue) self.general = Frame(self.onglets, padding=10) self.general.columnconfigure(1, weight=1) self.onglets.add(self.general, text=_("General")) # --- --- Temps Label(self.general, text=_("Times (min)"), style='title.TLabel').grid(row=0, pady=4, padx=(2, 10), sticky="w") self.time_frame = Frame(self.general) self.time_frame.grid(row=0, column=1, sticky="w", padx=4) Label(self.time_frame, text=_("Work")).grid(row=0, padx=4, column=0) self.travail = Entry(self.time_frame, width=4, justify='center', validatecommand=(self.okfct, '%P'), validate='key') self.travail.insert(0, CONFIG.get("Pomodoro", "work_time")) self.travail.grid(row=0, column=1, padx=(0, 10)) Label(self.time_frame, text=_("Break")).grid(row=0, column=2, padx=4) self.pause = Entry(self.time_frame, width=4, justify='center', validatecommand=(self.okfct, '%P'), validate='key') self.pause.insert(0, CONFIG.get("Pomodoro", "break_time")) self.pause.grid(row=0, column=3, padx=(0, 10)) Label(self.time_frame, text=_("Rest")).grid(row=0, column=4, padx=4) self.rest = Entry(self.time_frame, width=4, justify='center', validatecommand=(self.okfct, '%P'), validate='key') self.rest.insert(0, CONFIG.get("Pomodoro", "rest_time")) self.rest.grid(row=0, column=5) Separator(self.general, orient='horizontal').grid(row=1, columnspan=2, sticky="ew", pady=10) # --- --- Police Label(self.general, text=_("Font"), style='title.TLabel').grid(row=2, sticky='nw', padx=(2, 10)) self.font = FontFrame(self.general, font=CONFIG.get('Pomodoro', 'font'), sample_text="02:17") self.font.grid(row=2, column=1, padx=4, sticky='w') Separator(self.general, orient='horizontal').grid(row=3, columnspan=2, sticky="ew", pady=10) # --- --- Opacity self.opacity = OpacityFrame(self.general) self.opacity.grid(row=5, columnspan=2, sticky='w', padx=(2, 4), pady=4) Separator(self.general, orient='horizontal').grid(row=6, columnspan=2, sticky="ew", pady=10) # --- --- Son self.sound = SoundFrame(self.general, CONFIG.get("Pomodoro", "beep"), mute=CONFIG.getboolean("Pomodoro", "mute"), label=_("Sound"), style='title.TLabel') self.sound.grid(row=7, columnspan=2, sticky='ew', pady=4) # --- Couleurs self.couleurs = Frame(self.onglets, padding=10) self.couleurs.columnconfigure(3, weight=1) self.onglets.add(self.couleurs, text=_("Colors")) self.bg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "background"), _("Background")) self.work_bg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "work_bg"), _("Background")) self.break_bg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "break_bg"), _("Background")) self.rest_bg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "rest_bg"), _("Background")) self.fg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "foreground"), _("Foreground")) self.work_fg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "work_fg"), _("Foreground")) self.break_fg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "break_fg"), _("Foreground")) self.rest_fg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro", "rest_fg"), _("Foreground")) Label(self.couleurs, text=_("General"), style='title.TLabel').grid(row=0, column=0, pady=4, padx=(2, 10), sticky="w") self.bg.grid(row=0, column=1, sticky='e', padx=8, pady=4) self.fg.grid(row=0, column=2, sticky='e', padx=8, pady=4) Separator(self.couleurs, orient='horizontal').grid(row=1, sticky="ew", pady=10, columnspan=4) Label(self.couleurs, text=_("Work"), style='title.TLabel').grid(row=2, column=0, pady=4, padx=(2, 10), sticky="w") self.work_bg.grid(row=2, column=1, sticky='e', padx=8, pady=4) self.work_fg.grid(row=2, column=2, sticky='e', padx=8, pady=4) Separator(self.couleurs, orient='horizontal').grid(row=3, sticky="ew", pady=10, columnspan=4) Label(self.couleurs, text=_("Break"), style='title.TLabel').grid(row=4, column=0, pady=4, padx=(2, 10), sticky="w") self.break_bg.grid(row=4, column=1, sticky='e', padx=8, pady=4) self.break_fg.grid(row=4, column=2, sticky='e', padx=8, pady=4) Separator(self.couleurs, orient='horizontal').grid(row=5, sticky="ew", pady=10, columnspan=4) Label(self.couleurs, text=_("Rest"), style='title.TLabel').grid(row=6, column=0, pady=4, padx=(2, 10), sticky="w") self.rest_bg.grid(row=6, column=1, sticky='e', padx=8, pady=4) self.rest_fg.grid(row=6, column=2, sticky='e', padx=8, pady=4) # --- Tasks self.stats = Frame(self.onglets, padding=10) self.stats.columnconfigure(0, weight=1) self.stats.rowconfigure(2, weight=1) self.onglets.add(self.stats, text=_("Tasks")) # graph legend legend_frame = Frame(self.stats) Label(legend_frame, style='title.TLabel', text=_('Maximum number of rows in the legend')).pack(side='left') self.legend_row_nb = Entry(legend_frame, width=4, justify='center', validatecommand=(self.okfct, '%P'), validate='key') self.legend_row_nb.insert( 0, CONFIG.get('Pomodoro', 'legend_max_height', fallback='6')) self.legend_row_nb.pack(side='left', padx=4) # task colors can = Canvas(self.stats, bg=self.style.lookup('TFrame', 'background'), highlightthickness=0, width=1, relief='flat') scroll = AutoScrollbar(self.stats, orient='vertical', command=can.yview) can.configure(yscrollcommand=scroll.set) self.task_frame = Frame(can) can.create_window(0, 0, anchor='nw', window=self.task_frame) tasks = CONFIG.options("PomodoroTasks") tasks.sort() cmap = [CONFIG.get("PomodoroTasks", task) for task in tasks] self.tasks = {} self._tasks_btns = {} for i, (coul, task) in enumerate(zip(cmap, tasks)): self.tasks[task] = ColorFrame(self.task_frame, coul, task.capitalize()) self.tasks[task].grid(row=i, column=0, sticky='e', padx=4, pady=4) b = Button(self.task_frame, image=self.im_moins, padding=2, command=lambda t=task: self.del_task(t)) b.grid(row=i, column=1, sticky='w', padx=4, pady=4) self._tasks_btns[task] = b if len(tasks) == 1: self._tasks_btns[tasks[0]].state(['disabled']) legend_frame.grid(row=0, columnspan=2, sticky='w', pady=4) Label(self.stats, text=_('Colors in the statistic graph'), style='title.TLabel').grid(row=1, column=0, sticky='w', pady=4) can.grid(row=2, column=0, sticky='ewns') scroll.grid(row=2, column=1, sticky='ns') Button(self.stats, image=self.im_plus, command=self.add_task).grid(row=3, column=0, sticky='w') self.update_idletasks() can.configure(width=self.task_frame.winfo_reqwidth()) can.configure(scrollregion=can.bbox('all')) can.bind('<4>', lambda e: self._scroll(e, -1)) can.bind('<5>', lambda e: self._scroll(e, 1)) self.task_frame.bind( '<Configure>', lambda e: can.configure(scrollregion=can.bbox('all')))
def __init__(self, title): root = Tk() root.title(title) root.focus_set() root.rowconfigure(0, weight=0) root.columnconfigure(0, weight=1) root.rowconfigure(1, weight=1) self._root = root self.menubar = Frame(root) self.menubar.grid(row=0, column=0, sticky=(W, E)) self.menubar['takefocus'] = False quit_button = Button(self.menubar, text='Quit', command=self.quit) quit_button.grid(row=0, column=0) self._menucolumn = 1 self.views = list() self.paned_win = PanedWindow(root, orient=HORIZONTAL) self.paned_win.grid(row=1, column=0, sticky=(N, S, W, E)) self._query = None self._accept_func = None self.sidebar_views = dict() self.sidebar_count = 0 self.sidebar = PanedWindow(self.paned_win) self.paned_win.add(self.sidebar, weight=1) self.tabs = Notebook(self.paned_win) self.tabs.enable_traversal() self.paned_win.add(self.tabs, weight=5) self.root = self.tabs