def create_panel(self): """ this function shows two things, the tracker and a graph that shows the data tracked so far """ # Main Frame creation frame1 = Frame(self.window) frame1.pack(fill="both") tablayout = Notebook(frame1) ##### TRACKER ##### tab = Frame(tablayout) # creating 1st nested frame tab.pack(fill="both") table = Frame(tab) table.pack(fill="both") self.show_table(self.t.timeline["week" + str(self.week)], table) # Grids the week with data self.add_buttons(tab, table) tablayout.add(tab, text="Current Week") ##### STATS ##### tab = Frame(tablayout) # creating 2nd nested frame tab.pack(fill="both") self.stats.create_canvas(tab) # once its packed you can add it to the window object under a title tablayout.add(tab, text="Statistics") tablayout.pack( fill="both") # once everything is done now you pack the tablayout
def _create_settings_tab(self, nb: ttk.Notebook) -> None: """widgets to be displayed on 'Settings'""" settings_frame = ttk.Frame(nb, name='settings') settings_frame.rowconfigure(1, weight=1) settings_frame.columnconfigure((0, 1), weight=1, uniform=1) nb.add(settings_frame, text='Settings', underline=0, padding=2) # underline = shortcut char index msg = [ "Please change settings and click save. To return to default settings, click reset. \nSettings will be applied to File and Batch plots" ] # settingslbl = ttk.Label(settings_frame, wraplength='4i', justify=LEFT, anchor=N, text=''.join(msg)) settingslbl.grid(row=0, column=0, columnspan=2, sticky='new', pady=5) loadbtn = ttk.Button(settings_frame, text='Load Settings', underline=0, command=None) loadbtn.grid(row=3, column=3, pady=(2, 4)) savebtn = ttk.Button(settings_frame, text='Save Settings', underline=0, command=None) savebtn.grid(row=4, column=3, pady=(2, 4)) resetbtn = ttk.Button(settings_frame, text='Reset', underline=0, command=None) resetbtn.grid(row=5, column=3, pady=(2, 4))
def ui(): w = 0 c = 0 k = 0 root = Tk() root.title("Product Details") root.geometry("700x450+0+0") frame2 = Frame(root) frame2.pack(fill="both") tablayout = Notebook(frame2) tab1 = Frame(tablayout) tab1.pack(fill="both") for w in range(1, r + 2): newrow = customer.row_values(w) k = 1 for c in newrow: Label(tab1, text=c, width=15, bg="white", fg="black", padx=3, pady=3).grid(row=w, column=k, sticky="nsew", padx=1, pady=1) # Entry(tab1, bg=c, width=10).grid(row=r,column=1) k = k + 1 Label(tab1, text="Total Amount", width=15, bg="white", fg="black", padx=3, pady=3).grid(row=w + 1, column=k - 6, sticky="nsew", padx=1, pady=1) Label(tab1, text=sum, width=15, bg="white", fg="black", padx=3, pady=3).grid(row=w + 1, column=k - 5, sticky="nsew", padx=1, pady=1) tablayout.add(tab1) tablayout.pack(fill="both") root.mainloop()
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 init(): """ Creates a root window which contains a notebook 'notebook' with three frames: 'introduction', 'input_output', and 'image_diagram'. Returns the root window along with the three frames. """ root = Tk() root.resizable(width=False, height=False) root.title(WINDOW_TITLE) root.geometry("+0+0") notebook = Notebook(root) introduction = Frame(notebook, bg=tkcolour_from_rgb(WHITE)) introduction.pack() notebook.add(introduction, text="Introduction") input_output = Frame(notebook) input_output.pack() notebook.add(input_output, text="Input and Output") image_diagram = Frame(notebook) image_diagram.pack() notebook.add(image_diagram, text="Images and Diagrams") hist_calculation = Frame(notebook, bg=tkcolour_from_rgb(BACKGROUND)) hist_calculation.pack() notebook.add(hist_calculation, text="Histogram Calculation") spec_calculation = Frame(notebook, bg=tkcolour_from_rgb(BACKGROUND)) spec_calculation.pack() notebook.add(spec_calculation, text="Optical Spectrum Calculation") notebook.pack() return root, introduction, input_output, image_diagram, hist_calculation, spec_calculation
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 main(): # window setup root = Tk() root.title("ZACH_CHAD_EDITOR") menubar = Menu(root) root["menu"] = menubar file_menu = Menu(menubar) menubar.add_cascade(label="File", menu=file_menu) file_menu.add_command(label="Save", command=lambda: save_helper(textbox1)) file_menu.add_command(label="Open", command=lambda: open_helper(textbox1)) # editor setup tab_control = Notebook(root) tab1 = Frame(tab_control) tab2 = Frame(tab_control) tab_control.add(tab1, text='Test_Tab 1') tab_control.add(tab2, text="Test_Tab 2") textbox1 = Text(tab1, width=80, height=40, undo=True) textbox2 = Text(tab2, width=80, height=40, undo=True) tab_control.pack(expand=True, fill=BOTH) textbox1.pack(expand=True, fill=BOTH) textbox2.pack(expand=True, fill=BOTH) # start the GUI root.mainloop()
def Checkpoints_STD(): topic = ["Room","Student Id","Name","Score"] ptr = 0 show = Toplevel(root) show.geometry("625x250+800+50") show.title("Show Student list and score") frame1 = Frame(show,bg='#FDF5E6') frame1.pack(fill="both") tablelayout = Notebook(frame1) tab1 = Frame(tablelayout,bg='#FDF5E6') tab1.pack(fill="both") checker(show) file=open("d:\\UserData\\STD_DATA.txt", "r") many = file.read() many = many.split(":") j = len(many) j = j//4 for row in range(0,j+1): for column in range(0,4): if row == 0: label = Label(tab1,text=topic[column],bg="#FDF5E6",padx=3,pady=3) label.grid(row=row,column=column,sticky="nsew",padx=1,pady=1) tab1.grid_columnconfigure(column,weight=1) else: label = Label(tab1,text=str(many[ptr]),bg="white",padx=3,pady=3) label.grid(row=row,column=column,sticky="nsew",padx=1,pady=1) tab1.grid_columnconfigure(column,weight=1) ptr += 1 tablelayout.add(tab1,text="Student Data") tablelayout.pack(fill="both")
def create_gui(): window = Tk() window.title("ACC Race Direction") window.iconphoto(True, PhotoImage(file=resource_path('flag.png'))) window.geometry("600x400") window.wm_resizable(False, False) window.maxsize(height=0, width=590) conn_label = Label(window, text="Connecting...") conn_label.pack(anchor='ne') tablayout = Notebook(window) # tab1 accidents_tab = Frame(tablayout) tablayout.add(accidents_tab, text='Accidents') # tab2 vsc_tab = Frame(tablayout) tablayout.add(vsc_tab, text='VSC') tablayout.pack(fill="both") window.protocol("WM_DELETE_WINDOW", disconnect) return window, accidents_tab, vsc_tab
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 __initialize_gui__(self): notebook = Notebook(self.window) notebook.grid(row=0, column=0, rowspan=14, columnspan=4, sticky=EW) gmail_frame, nalanda_frame = Frame(notebook), Frame(notebook) notebook.add(gmail_frame, text='Gmail') notebook.add(nalanda_frame, text='Nalanda') # GMAIL Label(gmail_frame, text='Username:'******'W') Label(gmail_frame, text='Password:'******'W') Entry(gmail_frame, textvariable=self.username_variable, bd=5, relief=SUNKEN, width=30)\ .grid(row=0, columnspan=3, column=1) Entry(gmail_frame, textvariable=self.password_variable, show='*', bd=5, relief=SUNKEN, width=30)\ .grid(row=1, columnspan=3, column=1) self.submit_gmail_button = Button(gmail_frame, text='Submit', bd=5, relief=RAISED, width=10) self.submit_gmail_button.grid(row=10, sticky=E, columnspan=4) self.captcha_image = Label(gmail_frame, bd=5, relief=RAISED) self.captcha_entry = Entry(gmail_frame, textvariable=self.captcha_variable, bd=5, relief=SUNKEN) self.captcha_button = Button(gmail_frame, text='[R]', bd=2, relief=RAISED) # NALANDA Label(nalanda_frame, text='Username:'******'W') Label(nalanda_frame, text='Password:'******'W') Entry(nalanda_frame, textvariable=self.username_variable, bd=5, relief=SUNKEN, width=30) \ .grid(row=0, columnspan=3, column=1) Entry(nalanda_frame, textvariable=self.password_variable, show='*', bd=5, relief=SUNKEN, width=30) \ .grid(row=1, columnspan=3, column=1) self.submit_nalanda_button = Button(nalanda_frame, text='Submit', bd=5, relief=RAISED, width=10) self.submit_nalanda_button.grid(row=10, sticky=E, columnspan=4) # Attach the status bar self.busy_status.grid(row=15, column=3, sticky=EW) self.status_bar.grid(row=15, column=0, columnspan=3, sticky=EW) self.update_status('Enter Nalanda Login Details.') self.window.title('Authentication Window')
class InsGui(tk.Tk): def __init__(self): super().__init__() self.title("Batch Runs of py files") self.geometry("800x500") self.menu = tk.Menu(self, bg="lightgrey", fg="black") self.notebook = Notebook(self) main_tab = tk.Frame(self.notebook) self.notebook.add(main_tab, text="Main Page") self.notebook.pack(fill=tk.NONE, expand=1) self.list_of_scripts = tk.Text(main_tab, bg="white", fg="black") self.list_of_scripts.pack(side=tk.BOTTOM) self.select_button = tk.Button(self, text="SELECT THE PY FILES TO RUN", command=self.select) self.select_button.pack(side=tk.TOP) def select(self): global filez filez = askopenfilenames(title='Choose files') self.tk.splitlist(filez) for i in filez: runFiles(i) msg.showinfo("Execution Successful", "The Python script has ran successfully")
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 _setup_manage_tab(self, note: Notebook, model: ManageUIModel): frm_manage_tab = Frame(note, padding=10) frm_manage_tab.pack(fill=BOTH, expand=True) TreeFrame(frm_manage_tab, model) ManageActionFrame(frm_manage_tab, model) note.add(frm_manage_tab, text="Folder Manager")
def body(self,master): self.rootFrame = master n = Notebook(self.rootFrame) self.propertiesFrame = Frame(n) self.firewallFrame = Frame(n) self.commandsFrame = Frame(n) n.add(self.propertiesFrame, text="Propriedades") n.add(self.firewallFrame, text="Firewall") n.add(self.commandsFrame, text="Comandos") n.pack() print("@@@@@@@@@@@@@@@@@@@") print(self.prefDefaults) print("@@@@@@@@@@@@@@@@@@@") """ Aba 1: Propriedades """ # Hostname Label(self.propertiesFrame, text="Hostname:").grid(row=0,sticky='E') self.hostnameEntry = Entry(self.propertiesFrame, width=25) self.hostnameEntry.grid(row=0, column=1) if 'hostname' in self.prefDefaults: self.hostnameEntry.insert(0,self.prefDefaults['hostname']) # Endereço IP Label(self.propertiesFrame, text="Endereço IPV4:").grid(row=1,sticky="E") self.ipAddr = Entry(self.propertiesFrame,width=25) self.ipAddr.grid(row=1,column=1) if 'ip' in self.prefDefaults: self.ipAddr.insert(0, self.prefDefaults['ip']) # Máscara de rede Label(self.propertiesFrame, text="Máscara de rede:").grid(row=2,sticky="E") self.mask = Entry(self.propertiesFrame, width=25) self.mask.grid(row=2,column=1) if 'mask' in self.prefDefaults: self.mask.insert(0, self.prefDefaults['mask']) # Rota Padrão Label(self.propertiesFrame, text="Rota Padrão:").grid(row=3,sticky="E") self.defaultGW = Entry(self.propertiesFrame, width=25) self.defaultGW.grid(row=3,column=1) if 'defaultRoute' in self.prefDefaults: self.defaultGW.insert(0, self.prefDefaults['defaultRoute']) """ Aba 3: Comandos""" # Comando inicial Label(self.commandsFrame, text="Comando Inicial:").grid(row=0,sticky="NE") self.startCommand = Text(self.commandsFrame, height=5, width=28) self.startCommand.grid(row=0,column=1) if 'startCommand' in self.prefDefaults: self.startCommand.insert(1.0, self.prefDefaults['startCommand']) # Comando final Label(self.commandsFrame, text="Comando Final:").grid(row=1,sticky="NE") self.finalCommand = Text(self.commandsFrame, height=5, width=28) self.finalCommand.grid(row=1,column=1) if 'finalCommand' in self.prefDefaults: self.finalCommand.insert(1.0, self.prefDefaults['finalCommand'])
def buildTabs(self, parent: ttk.Notebook) -> None: """ Builds the individual tabs inside the tabbed layout design. Parameters ---------- parent : ttk.Notebook A tkinter object that can have tabs applied to it. Returns ------- None """ # For some reason, icons need to be member variables to display self.inputTabIcon = tk.PhotoImage(file='images/input-data-1.png') self.viewTabIcon = tk.PhotoImage(file='images/three-dim-graph.png') # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Tab 1: Data Input # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - inputTab = ttk.Frame(parent, ) inputTab_kwargs = { 'text': 'Data Input', 'image': self.inputTabIcon, 'compound': tk.LEFT } parent.add(inputTab, **inputTab_kwargs) eb.buildInputElements( self, inputTab, ) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Tab 2: Visualizer # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - viewTab = ttk.Frame(parent, ) viewTab_kwargs = { 'text': 'Viewer', 'image': self.viewTabIcon, 'compound': tk.LEFT } parent.add(viewTab, **viewTab_kwargs) # - - - - - - - - - - - - - - - - # Holder for editor/viewer graphPanes = ttk.Panedwindow(viewTab, orient=tk.HORIZONTAL) graphPanes.pack(fill=tk.BOTH, expand=True) self.editPane, self.viewPane = eb.buildEditAndViewPanes(graphPanes) eb.buildEditorElements(self, self.editPane, self.plotCols, self.availableRuns, self.waitToPlot, self.startPlot) # Setting the starting run options cf.setRunOptions(self, )
def _create_misc_tab(self, nb: ttk.Notebook) -> None: """widgets to be displayed on 'Misc'""" frame = ttk.Frame(nb) nb.add(frame, text='Misc', underline=0) some_mathButton = ttk.Button(frame, text='Random Math', command=self.print_somecython) some_mathButton.grid(row=2, column=3)
def GUI(): #Main Notebook global root tabs = Notebook(root) #Add Tabs tabs.add(BPM_GUI(tabs)) tabs.pack(fill="both", expand=1)
def __init__(self, master): super().__init__() self._appTitle = "Layered Mask Painter" self.master = master self.master.title(self._appTitle) # vars used for widget sizes and root geometry canvas_width = 640 # 259 canvas_height = 360 # 255 # the only 2 supported systems are Windows 7 and Windows 10 # tkinter widgets in the control panel render at different widths on Windows 7 and Windows 10 # so change the panel width to accommodate the widgets if platform.system() == "Windows" and platform.release() == "7": self.control_panel_width = 200 else: self.control_panel_width = 226 # model must be initialized before widgets and controllers model = Model(master) model.subject.save.attach(self._update_save) model.subject.load.attach(self._update_load) model.subject.project.attach(self._update_project) self.model = model # set the widgets status_label = Label(self.master, text="status label...", bd=1, relief=SUNKEN, anchor=W) canvas = Canvas(self.master, width=canvas_width, height=canvas_height, highlightthickness=0, bg="gray50", relief=RAISED) notebook = Notebook(self.master, width=self.control_panel_width) brush_frame = Frame(notebook) layer_frame = Frame(notebook) notebook.add(brush_frame, text="Brush") notebook.add(layer_frame, text="Layers") # pack the widgets status_label.pack(side=BOTTOM, fill=X) notebook.pack(side=LEFT, fill=Y) canvas.pack(side=LEFT, fill=BOTH, expand=True) # canvas painter painter = CanvasPainter(canvas, model) # delegate controllers self.menuBar = MenuBar(self.master, model, painter, self) self.statusPanel = StatusPanel(status_label, model) self.brushControl = BrushControl(brush_frame, model) self.layerControl = LayerControl(layer_frame, model) self.canvasControl = CanvasControl(canvas, model, painter) # set the geometry of the Tk root self._set_geometry(canvas_width, canvas_height) # to initialize the views, force a subject project notification model.subject.project.notify()
def _create_text_tab(self, nb: ttk.Notebook) -> None: """populate the third frame with a text widget""" frame = ttk.Frame(nb) txt = tk.Text(frame, wrap=WORD, width=40, height=10) vscroll = ttk.Scrollbar(frame, orient=VERTICAL, command=txt.yview) txt['yscroll'] = vscroll.set vscroll.pack(side=RIGHT, fill=Y) txt.pack(fill=BOTH, expand=Y) nb.add(frame, text='Text Editor', underline=0 ) # add to notebook (underline = index for short-cut character)
class SQLiteReader(Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.master.option_add('*tearOff', False) self.master.title('SQLite Reader') self.master.geometry('800x400+10+10') self.grid(column=0, row=0, sticky=(N, W, E, S)) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.create_menu() self.create_widget() self.tabs = [] def create_widget(self): self.tab_parent = Notebook(self) self.tab_parent.grid(column=0, row=0, sticky=(N, W, S, E)) def create_menu(self): self._menu = Menu(self.master) self.master.config(menu=self._menu) self.file_menu = Menu(self._menu) self.file_menu.add_command(label='Open', command=self.open_database) self.file_menu.add_command(label='Query', command=self.run_query, state='disabled') self._menu.add_cascade(label='File', menu=self.file_menu) self._menu.add_command(label='Reload', command=self.reload_current_table, state='disabled') self._menu.add_command(label='Exit', command=self.master.destroy) def open_database(self, new_folder=True): for item in self.tab_parent.winfo_children(): item.destroy() if new_folder: self.file_name = filedialog.askopenfilename() self.db = SQLiteConnector(self.file_name) for idx, table in enumerate(self.db.tables): new_tab = SQLTableFrame(self.tab_parent, table, self.db) self.tab_parent.add(new_tab, text=table) self.tab_query = SQLTableFrameQuery(self.tab_parent) self.tab_parent.add(self.tab_query, text='queries') self._menu.entryconfig('Reload', state='normal') self.file_menu.entryconfig('Query', state='normal') def reload_current_table(self): if hasattr(self, 'query_window'): self.query_window.destroy() self.open_database(new_folder=False) def run_query(self): self.tab_parent.select(self.tab_query) self.query_window = SQLQueryWindow(self.master, db=self.db, query_tab=self.tab_query)
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)
class TranslateBook(tk.Tk): def __init__(self): super().__init__() self.title("Translation Book 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="Translate", 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="Copy to Clipboard", 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="English") self.notebook.add(italian_tab, text="Italian") 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) except Exception as e: msg.showerror("Translation Failed", 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 __initUI(self): self.pack(side=LEFT, fill="both", expand=True) tabControl = Notebook(self) tabControl.pack(side=LEFT, fill="both", expand=True) tab1 = graph.GraphFrame(self._parent) tab2 = matrix.MatrixFrame(self._parent) tabControl.add(tab1, text="Cây") tabControl.add(tab2, text="Ma trận") set_variable("matrix", tab2) set_variable("tabControl", tabControl)
def __hide_window_log(self, tab_widget: ttk.Notebook): """ Close log window and show log tab instead Parameters ---------- tab_widget : tk.Notebook widget Returns ------- void """ self._window.withdraw() tab_widget.add(self)
def frame_4_(): global frame_list frame_des() frame_4_1 = Notebook(frame, width=261, height=240) frame_4_1.place(x=10, y=63) frame_4_2 = Frame(frame_4_1) frame_4_3 = Frame(frame_4_1) frame_4_1.add(frame_4_2, text="One player", padding=2) frame_4_1.add(frame_4_3, text="Two player", padding=2) frame_4_8 = Scrollbar(frame_4_2) frame_4_8.pack(fill="y", side=RIGHT) frame_4_9 = Scrollbar(frame_4_3) frame_4_9.pack(fill="y", side=RIGHT) frame_4_6 = Text(frame_4_2, font='arial 14', width=24, height=11) frame_4_6.pack() frame_4_7 = Text(frame_4_3, font='arial 14', width=24, height=11) frame_4_7.pack() frame_4_8.config(command=frame_4_6.yview) frame_4_6.config(yscrollcommand=frame_4_8.set) frame_4_9.config(command=frame_4_7.yview) frame_4_7.config(yscrollcommand=frame_4_9.set) with open('data\\one player.txt', mode='r') as f: obj = f.read() frame_4_6.insert('end', obj) with open('data\\two player.txt', mode='r') as f: obj = f.read() frame_4_7.insert('end', obj) frame_4_6.config(state='disable') frame_4_7.config(state='disable') frame_4_10 = Label(frame, text='Score Board', bg='#01CBC6', fg='#000000', font='arial 22 bold underline') frame_4_10.place(x=20, y=335) frame_4_5 = Button(frame, image=image, relief='flat', bg='#01CBC6', fg='#000000', activebackground='#01CBC6', cursor='hand2', command=frame_1_) frame_4_5.place(x=220, y=335) frame_list = [ frame_4_6, frame_4_7, frame_4_2, frame_4_3, frame_4_1, frame_4_5, frame_4_10 ]
def initUI(self): self.parent.title("Backup by Ginkgo") self.style = Style() self.style.theme_use("alt") Style().configure("TFrame", background="white") # frame = Frame(self, relief=RAISED, borderwidth=0.5) # frame.pack(fill=BOTH, expand=True) # self.pack(fill=BOTH, expand=True) # quitButton = Button(self, text="Quit", command=self.quit) # quitButton.pack(side=RIGHT, padx=5, pady=5) # bakupButton = Button(self, text="Backup", command=lambda: sub.call('python "E:\\Huyen Trang\\project\\djangows\\client\\windows\\background_task.py"')) # bakupButton.pack(side=RIGHT) nb = Notebook(root, height=240, width=480) tabs = {"Backup": [], "Restore": []} for tabname in tabs: tab = Text(nb) tabs[tabname] = tab nb.add(tab, text=tabname) nb.pack() frame1 = Frame(tabs["Restore"], relief=RAISED, borderwidth=0, height=240, width=580) frame1.pack(fill=BOTH, side=BOTTOM, expand=False) restoreButton = Button(frame1, text="Restore", command=lambda: self.addTest(tabs["Restore"])) restoreButton.pack(side=RIGHT, padx=5, pady=5) rStopButton = Button(frame1, text="Stop", command=lambda: self.stopRestore(tabs["Restore"])) rStopButton.pack(side=RIGHT, padx=0, pady=0) frame2 = Frame(tabs["Backup"], relief=RAISED, borderwidth=0, height=240, width=580) frame2.pack(fill=BOTH, side=BOTTOM, expand=False) bakupButton = Button(frame2, text="Backup", command=lambda: self.addText(tabs["Backup"])) bakupButton.pack(fill=BOTH, side=BOTTOM, padx=0, pady=0)
def __init__(self, master): self.master = master tabControl = Notebook(self.master) self.tab1 = Frame(tabControl) tabControl.add(self.tab1, text='501') #tabControl.pack(expand=1, fill="both") tab2 = Frame(tabControl) tabControl.add(tab2, text='Round The Board') tabControl.pack(expand=1, fill="both") self.configure_gui() self.create_widgets() self.start_window()
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)
def main(): """Main function of the program.""" main = tk.Tk() # Add Title main.title("Space Craft Creator") # Disable Resizing main.resizable(False, False) data = Data() spacecraft = Spacecraft(data) notebook = Notebook(main) spacecraft_tab = spacecraft.make_tab(notebook) notebook.add(spacecraft_tab, text="Spacecraft") for key, subsystem in spacecraft.subsections.items(): notebook.add(subsystem.make_tab(notebook), text=key) notebook.add(spacecraft.sizes.make_tab(notebook), text="Sizes") notebook.add(spacecraft.velocities.make_tab(notebook), text="Velocity Profiles") notebook.grid(column=0, row=0) notebook.enable_traversal() button = Button(main, text="Caclulate", command=spacecraft.calculate) button.grid(column=0, row=1) main.mainloop()
def __init__(self,fen): tkinter.Frame.__init__(self,bg = "#%02x%02x%02x" % (71,86,82)) self.grid() #Header self.title = tkinter.Label(self, text="Le-Mayzeur", fg="white", font=("bauhaus 93",22), bg = "#%02x%02x%02x" % (71,86,82)) self.title.grid(row=0, column = 0) #Body onglet=Notebook(self, width=380, height=380) self.convert=tkinter.ttk.Panedwindow(orient=tkinter.VERTICAL) self.iso=tkinter.ttk.Panedwindow(orient=tkinter.VERTICAL) self.shutdown=tkinter.ttk.Panedwindow(orient=tkinter.VERTICAL) self.bootable=tkinter.ttk.Panedwindow(orient=tkinter.VERTICAL) onglet.add(self.iso,text='ISO file') onglet.add(self.convert,text='Convert') onglet.add(self.shutdown, text="Shutdown") onglet.add(self.bootable,text='Boot drive') onglet.grid(row=2, column=0) #Links --. inherit classes Convert.__init__(self) Shutd.__init__(self,fen) IsoFile.__init__(self,fen) Bootable.__init__(self) #footer self.footer = tkinter.Label(fen, width=480, bg="#%02x%02x%02x" % (71,86,82)) self.footer.place(x=0,y=447) self.footer = tkinter.Label(fen, text="*****@*****.**", fg="white", bg="#%02x%02x%02x" % (71,86,82)) self.footer.place(x=130,y=447)
class GUI(): def __init__(self) -> None: # setup the gui self.root = setup(Tk()) self.gui = Notebook(self.root) # Setup the posting page page1 = Frame(self.gui) self.posting_frame = PostingPage(page1) self.gui.add(page1, text='Posting') # Setup the scheduling ppage page2 = Frame(self.gui) self.scheduling_frame = SchedulingPage(page2) self.gui.add(page2, text='Scheduling') # Setup the analytics page page3 = Frame(self.gui) self.analytics_frame = AnalyticsPage(page3) self.gui.add(page3, text='Analytics') # Setup the config parser page page4 = Frame(self.gui) self.gui.add(page4, text='Config') # Pack out gui self.gui.pack(expand=1, fill='both')
class Timer(tk.Tk): def __init__(self): super().__init__() self.title(config.title) self.geometry(config.geometry) self.notebook = Notebook(self) running_tab = RunTag(self.notebook) images_tab = ImagesTab(self.notebook) self.notebook.add(running_tab, text="运行中的容器") self.notebook.add(images_tab, text="镜像管理") self.notebook.pack(fill=tk.BOTH, expand=1)
def init_selexseq_gui(self): self.clear() row_gen = NumGenerator() logo = Label(self, image=self.logoimage) logo.grid_columnconfigure(0, weight=1) logo.grid(row=row_gen.get()) note = Notebook(self) main = Frame(note) motif_scan = Frame(note) topkmer = Frame(note) kmer_query = Frame(note) note.add(main, text="SELEX-SEQ Main") note.add(motif_scan, text="Motif Scan") note.add(topkmer, text='Top kmer') note.add(kmer_query, text='Kmer query') self.init_selexseq_gui_tabmain_step0(main) self.init_motifscan_guitab(motif_scan) self.init_topkmer_guitab(topkmer) self.init_kmerquery_guitab(kmer_query) note.grid(row=row_gen.get(), column=0) # self.columnconfigure(0,weight=1) self.master.grid_columnconfigure(0, weight=1) self.master.grid_rowconfigure(0, weight=1) self.master.grid_rowconfigure(1, weight=5)
def init_chipseq_gui(self): self.clear() logo = Label(self, image=self.logoimage) logo.grid(row=0, column=0) note = Notebook(self) main = Frame(note) motif_scan = Frame(note) topkmer = Frame(note) kmer_query = Frame(note) note.add(main, text="Chip-Seq Main") note.add(motif_scan, text="Motif Scan") note.add(topkmer, text='Top kmer') note.add(kmer_query, text='Kmer query') self.init_chipseq_gui_tabmain(main) self.init_motifscan_guitab(motif_scan) self.init_topkmer_guitab(topkmer) self.init_kmerquery_guitab(kmer_query) note.grid(row=1, column=0) self.master.grid_columnconfigure(0, weight=1) self.master.grid_rowconfigure(0, weight=1) self.master.grid_rowconfigure(1, weight=5)
class baseInterface(Tk): def __init__(self): Tk.__init__(self) self._controller = ArduinoController() self._controller.nbLeds = 21 self._controller.clear() self._notebook = Notebook(self) self._notebook.grid(sticky=(E, W)) self.__modules = {} self.__defaultSpeed = 60 self._updateSpeed = self.__defaultSpeed self.protocol("WM_DELETE_WINDOW", self._handleClose) self.__update() def setSpeed(self, speed): if 5 <= speed <= 500: self._updateSpeed = speed else: self._updateSpeed = self.__defaultSpeed def getSpeed(self): return self._updateSpeed def resetSpeed(self): self._updateSpeed = self.__defaultSpeed def registerModule(self, name, obj): self.__modules[name] = obj(self) self.__modules[name].linkController(self._controller) self._notebook.add(self.__modules[name].mainFrame, text=name) def _handleClose(self): self._controller.clear() self._controller.send() self._controller.destroy() self.destroy() def _getCurrentTabName(self): return self._notebook.tab(self._notebook.select(), "text") def __update(self): if len(self.__modules) > 0: self.__modules[self._getCurrentTabName()].update() self.after(self._updateSpeed, self.__update)
def _setup_backup_tab(self, note: Notebook, model: ConfigUIModel): frm_backup_tab = Frame(note, padding=10) frm_backup_tab.pack(fill=BOTH, expand=True) frm_config = Frame(frm_backup_tab, padding=10) frm_config.pack(side=TOP, fill=BOTH, expand=True) SourceFrame(frm_config, model) ExclusionFrame(frm_config, model) DestinationFrame(frm_config, model) ActionFrame(frm_backup_tab, model) frm_backup_tab.pack(fill=BOTH, expand=True) note.add(frm_backup_tab, text="Backup Configurer")
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')
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()
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()
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)
filenameLabel = Label(fileFrame, text="No file selected") filenameLabel.pack(side=LEFT) selectFileButton = Button(fileFrame, text = 'Select File', command = load_file) selectFileButton.pack(side=RIGHT, padx=5) bodyFrame = Frame(root, width = 600, height=400) bodyFrame.pack(expand=True, fill=X, padx=10, anchor=W) view3DFrame = Frame(width=300, height=300) viewLayerFrame = LayerPreview(root, width=300, height=300) viewFrame = Notebook(bodyFrame) #viewFrame.add(view3DFrame, text="3D View") viewFrame.add(viewLayerFrame, text="Layer View") viewFrame.pack(expand=True, side=LEFT, anchor=NW) settingsFrame = Notebook(bodyFrame) settingsFrame.pack(expand=True, side=LEFT, anchor=NW) setupFrame = Frame() setupFrame.pack(padx=10, pady=10) printerFrame = Frame(setupFrame) printerFrame.pack(side=TOP) zMoveFrame = ZMove(printerFrame) zMoveFrame.pack(side=RIGHT, anchor=E, padx=(50, 0))
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 _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 Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.lastdir = os.getcwd() self.op_sys = platform.platform() #Check for path to FEBio executable try: if "windows" in self.op_sys.lower(): home = os.getenv("HOMEPATH") else: home = os.getenv("HOME") fid = open(os.path.join(home, ".pyCellAnalystFEA.pth"), "r") self._FEBIO_BIN = os.path.abspath(fid.readline()) fid.close() try: p = subprocess.Popen(self._FEBIO_BIN) p.terminate() except: self.getFEBioLocation("File indicated as the FEBio executable is incorrect. Please reselect.", home) except: self.getFEBioLocation("Please select the FEBio executable file.", home) self.notebook = Notebook(self) self.tab1 = Frame(self.notebook) self.tab2 = Frame(self.notebook) self.notebook.add(self.tab1, text="Analysis") self.notebook.add(self.tab2, text="Material Model") self.notebook.grid(row=0, column=0, sticky=NW) self.pickles = [] self.data = {} self.vtkMeshes = {} self.volumes = {} self.outputs = OrderedDict( [("Effective Strain (von Mises)", IntVar(value=1)), ("Maximum Compressive Strain", IntVar(value=1)), ("Maximum Tensile Strain", IntVar(value=1)), ("Maximum Shear Strain", IntVar(value=1)), ("Volumetric Strain", IntVar(value=1)), ("Effective Stress (von Mises)", IntVar(value=0)), ("Maximum Compressive Stress", IntVar(value=0)), ("Maximum Tensile Stress", IntVar(value=0)), ("Maximum Shear Stress", IntVar(value=0)), ("Pressure", IntVar(value=0))]) self.analysis = OrderedDict( [("Generate Histograms", IntVar(value=1)), ("Tukey Boxplots", IntVar(value=1)), ("Calculate Differences", IntVar(value=1)), ("Convert to VTK", IntVar(value=1))]) self.groundSubstance = IntVar(value=1) self.groundSubstances = ('neoHookean', 'Mooney-Rivlin', 'Transversely Isotropic') self.tensileNetwork = IntVar(value=1) self.tensileNetworks = ('None', 'Continuous Fibre Distribution') self.compressiveNetwork = IntVar(value=1) self.groundParameters = [ OrderedDict([("Young's Modulus", DoubleVar(value=1.0e-9)), ("Poisson's Ratio", DoubleVar(value=0.1))]), OrderedDict([("C_1", DoubleVar(value=2.3e-10)), ("C_2", DoubleVar(value=0.0)), ("Bulk Modulus", DoubleVar(value=4.17e-10))]), OrderedDict([ ("Young's Modulus (radial)", DoubleVar(value=1.45e-6)), ("Young's Modulus (tangential)", DoubleVar(value=1.0e-9)), ("Poisson's Ratio (radial:tangential)", DoubleVar(value=0.4)), ("Poisson's Ratio (tangential:radial)", DoubleVar(value=0.0)), ("Shear Modulus (radial planes)", DoubleVar(value=5.0e-10))])] self.tensileParameters = [ None, OrderedDict([("ksi1", DoubleVar(value=1.0e-7)), ("ksi2=ksi3", DoubleVar(value=1.45e-6)), ("beta1", DoubleVar(value=2.0)), ("beta2=beta3", DoubleVar(value=2.0)), ("Distance Cutoff [0, 1]", DoubleVar(value=0.5)), ("Cutoff Grade (0, 1]", DoubleVar(value=0.1))])] self.results = {"Effective Strain (von Mises)": {}, "Maximum Compressive Strain": {}, "Maximum Tensile Strain": {}, "Maximum Shear Strain": {}, "Volumetric Strain": {}, "Effective Stress (von Mises)": {}, "Maximum Compressive Stress": {}, "Maximum Tensile Stress": {}, "Maximum Shear Stress": {}, "Pressure": {}, "Displacement": {}} self.histograms = {"Effective Strain (von Mises)": {}, "Maximum Compressive Strain": {}, "Maximum Tensile Strain": {}, "Maximum Shear Strain": {}, "Volumetric Strain": {}, "Effective Stress (von Mises)": {}, "Maximum Compressive Stress": {}, "Maximum Tensile Stress": {}, "Maximum Shear Stress": {}, "Pressure": {}} self.boxwhiskers = {"Effective Strain (von Mises)": {}, "Maximum Compressive Strain": {}, "Maximum Tensile Strain": {}, "Maximum Shear Strain": {}, "Volumetric Strain": {}, "Effective Stress (von Mises)": {}, "Maximum Compressive Stress": {}, "Maximum Tensile Stress": {}, "Maximum Shear Stress": {}, "Pressure": {}} self.differences = {"Effective Strain (von Mises)": {}, "Maximum Compressive Strain": {}, "Maximum Tensile Strain": {}, "Maximum Shear Strain": {}, "Volumetric Strain": {}, "Effective Stress (von Mises)": {}, "Maximum Compressive Stress": {}, "Maximum Tensile Stress": {}, "Maximum Shear Stress": {}, "Pressure": {}} self.grid() self.createWidgetsTab1() self.createWidgetsTab2() def getFEBioLocation(self, msg, home): filename = tkinter.filedialog.askopenfilename( parent=root, initialdir=home, title=msg) if filename: try: p = subprocess.Popen(filename) p.terminate() self._FEBIO_BIN = filename fid = open(os.path.join(home, ".pyCellAnalystFEA.pth"), "wt") fid.write(self._FEBIO_BIN) fid.close() except: self.getFEBioLocation("Incorrect FEBio executable file was selected. Please reselect.", home) else: raise SystemExit("You must indicate the location of the FEBio executable. Exiting...") def createWidgetsTab1(self): #pickles to load self.pickleFrame = LabelFrame( self.tab1, text="Pickles from which to generate models") self.pickleFrame.grid(row=0, column=0, columnspan=3, rowspan=2, padx=5, pady=5, sticky=NW) self.buttonAddFile = Button( self.pickleFrame, text="Add", bg='green', command=self.addPickle) self.buttonAddFile.grid(row=0, column=0, padx=5, pady=5, sticky=E + W) self.buttonRemoveFile = Button( self.pickleFrame, text="Remove", bg='red', command=self.removePickle) self.buttonRemoveFile.grid(row=1, column=0, padx=5, pady=5, sticky=E + W) self.listPickles = Listbox(self.pickleFrame, width=80, selectmode=MULTIPLE) self.listPickles.grid(row=0, column=1, columnspan=2, rowspan=2, padx=5, pady=5, sticky=E + W) #outputs self.outputsFrame = LabelFrame(self.tab1, text="Outputs") self.outputsFrame.grid(row=2, column=0, rowspan=4, columnspan=2, padx=5, pady=5, sticky=NW) for i, t in enumerate(self.outputs.keys()): if i < 5: Checkbutton(self.outputsFrame, text=t, variable=self.outputs[t]).grid(row=i, column=0, padx=5, pady=5, sticky=NW) else: Checkbutton(self.outputsFrame, text=t, variable=self.outputs[t]).grid(row=i - 5, column=1, padx=5, pady=5, sticky=NW) #analysis settings self.analysisSettingsFrame = LabelFrame(self.tab1, text="Analysis Options") self.analysisSettingsFrame.grid(row=2, column=2, padx=5, pady=5, sticky=E + W) for i, t in enumerate(self.analysis.keys()): Checkbutton(self.analysisSettingsFrame, text=t, variable=self.analysis[t]).grid(row=i, column=2, padx=5, pady=5, sticky=NW) #run analysis self.buttonExecute = Button(self.tab1, bg='green', font=('Helvetica', '20', 'bold'), text='Perform Simulation', command=self.performFEA) self.buttonExecute.grid(row=7, column=0, columnspan=3, padx=5, pady=5, sticky=E + W) self.buttonAnalyze = Button(self.tab1, bg='blue', font=('Helvetica', '20', 'bold'), text='Analyze Results', command=self.analyzeResults) self.buttonAnalyze.grid(row=8, column=0, columnspan=3, padx=5, pady=5, sticky=E + W) def createWidgetsTab2(self): self.groundSubstanceFrame = LabelFrame(self.tab2, text="Ground Substance") self.groundSubstanceFrame.grid( row=0, column=0, padx=5, pady=5, sticky=NW) self.tensileFibreNetworkFrame = LabelFrame( self.tab2, text="Tensile Fibres") self.tensileFibreNetworkFrame.grid( row=0, column=1, padx=5, pady=5, sticky=NW) self.compressiveFibreNetworkFrame = LabelFrame( self.tab2, text="Compressive Fibres") self.compressiveFibreNetworkFrame.grid( row=0, column=3, padx=5, pady=5, sticky=NW) # Ground substance for i, t in enumerate(self.groundSubstances): Radiobutton(self.groundSubstanceFrame, text=t, indicatoron=0, padx=5, width=20, command=self.populateGroundSubstance, variable=self.groundSubstance, value=i + 1).pack(anchor=NW) self.groundSubstanceSettingsFrame = LabelFrame( self.tab2, text="Ground Substance Parameters") self.groundSubstanceSettingsFrame.grid( row=1, column=0, padx=5, pady=5, sticky=NW) for i, (t, v) in enumerate( self.groundParameters[self.groundSubstance.get() - 1].items()): Label(self.groundSubstanceSettingsFrame, text=t).grid(row=i, column=0, sticky=NW) Entry(self.groundSubstanceSettingsFrame, textvariable=v, width=10).grid(row=i, column=1, sticky=NW) # Tensile Network for i, t in enumerate(self.tensileNetworks): Radiobutton(self.tensileFibreNetworkFrame, text=t, indicatoron=0, padx=5, width=25, command=self.populateTensileNetwork, variable=self.tensileNetwork, value=i + 1).pack(anchor=NW) self.tensileNetworkSettingsFrame = LabelFrame( self.tab2, text="Tensile Network Parameters") self.tensileNetworkSettingsFrame.grid( row=1, column=1, padx=5, pady=5, sticky=NW) if self.tensileNetwork.get() == 1: Label(self.tensileNetworkSettingsFrame, text="No tensile network will be modeled").grid(row=0, column=0, sticky=NW) else: for i, (t, v) in enumerate( self.tensileParameters[self.tensileNetwork.get() - 1].items()): Label(self.tensileNetworkSettingsFrame, text=t).grid(row=i, column=0, sticky=NW) Entry(self.tensileNetworkSettingsFrame, textvariable=v, width=10).grid(row=i, column=1, sticky=NW) def populateGroundSubstance(self): for child in self.groundSubstanceSettingsFrame.grid_slaves(): child.destroy() for i, (t, v) in enumerate( self.groundParameters[self.groundSubstance.get() - 1].items()): Label(self.groundSubstanceSettingsFrame, text=t).grid(row=i, column=0, sticky=NW) Entry(self.groundSubstanceSettingsFrame, textvariable=v, width=10).grid(row=i, column=1, sticky=NW) def populateTensileNetwork(self): for child in self.tensileNetworkSettingsFrame.grid_slaves(): child.destroy() if self.tensileNetwork.get() == 1: Label(self.tensileNetworkSettingsFrame, text="No tensile network will be modeled").grid(row=0, column=0, sticky=NW) else: for i, (t, v) in enumerate( self.tensileParameters[self.tensileNetwork.get() - 1].items()): Label(self.tensileNetworkSettingsFrame, text=t).grid(row=i, column=0, sticky=NW) Entry( self.tensileNetworkSettingsFrame, textvariable=v, width=10).grid(row=i, column=1, sticky=NW) Button( self.tensileNetworkSettingsFrame, text='Plot', width=10, command=self.plotWeight).grid(row=i + 1, column=0, sticky=NW) def plotWeight(self): f = Figure() a = f.add_subplot(111) x = np.arange(0.0, 1.0, 0.01) d = self.tensileParameters[1][ "Distance Cutoff [0, 1]"].get() k = self.tensileParameters[1][ "Cutoff Grade (0, 1]"].get() if k <= 0: k = 0.01 print(("Cutoff Grade must be greater than zero" " Using a value of 0.01.")) s = 0.5 * (1 - np.tanh(old_div((x - d), k))) a.plot(x, s) a.set_xlabel("Normalized distance from object surface") a.set_ylabel("Tensile Network Weight") canvas = FigureCanvasTkAgg(f, master=self.tensileNetworkSettingsFrame) canvas.show() (cols, rows) = self.tensileNetworkSettingsFrame.grid_size() slaves = self.tensileNetworkSettingsFrame.grid_slaves() if rows == 7: canvas.get_tk_widget().grid(row=rows + 1, column=0, columnspan=2, sticky=NW) else: slaves[0].destroy() canvas.get_tk_widget().grid(rows=rows, column=0, columnspan=2, sticky=NW) def addPickle(self): filenames = tkinter.filedialog.askopenfilenames( parent=root, initialdir=self.lastdir, title="Please choose pickle file(s) for analysis.") filenames = root.tk.splitlist(filenames) for f in filenames: if '.pkl' in f: self.listPickles.insert(END, f) self.pickles.append(f) else: print(("WARNING - {:s} does not contain the .pkl extension." " Ignoring this file.")) def removePickle(self): index = self.listPickles.curselection() if index: for i in index[::-1]: self.listPickles.delete(i) del self.pickles[i] def performFEA(self): for filename in self.pickles: fid = open(filename, 'rb') self.data[filename] = pickle.load(fid) fid.close() mesh = febio.MeshDef() # would be good to vectorize these for i, e in enumerate(self.data[filename]['elements']): mesh.elements.append(['tet4', i + 1] + e) for i, n in enumerate(self.data[filename]['nodes']): mesh.nodes.append([i + 1] + n) mesh.addElementSet(setname='cell', eids=list(range(1, len(mesh.elements) + 1))) modelname = filename.replace('.pkl', '.feb') model = febio.Model(modelfile=modelname, steps=[{'Displace': 'solid'}]) #lookup table for proper FEBio keyword vs GUI text keywords = { "neoHookean": "neo-Hookean", "Young's Modulus": "E", "Poisson's Ratio": "v", "Mooney-Rivlin": "Mooney-Rivlin", "C_1": "c1", "C_2": "c2", "Bulk Modulus": "k", "Transversely Isotropic": "orthotropic elastic", "Young's Modulus (radial)": "E1", "Young's Modulus (tangential)": ["E2", "E3"], "Poisson's Ratio (radial:tangential)": "v12", "Poisson's Ratio (tangential:radial)": ["v23", "v31"], "Shear Modulus (radial planes)": ["G12", "G23", "G31"], "Continuous Fibre Distribution": "ellipsoidal fiber distribution"} #Ground Substance gtype = keywords[ self.groundSubstances[self.groundSubstance.get() - 1]] gattributes = {} for (k, v) in list(self.groundParameters[ self.groundSubstance.get() - 1].items()): # transversely isotropic case if isinstance(keywords[k], list): for a in keywords[k]: # G12 = E2 / (2 * (1 + v12)) if a == "G12": gattributes[a] = str( old_div(float(gattributes["E2"]), (2.0 * (1 + float(gattributes["v12"]))))) else: gattributes[a] = str(v.get()) # any other case else: gattributes[keywords[k]] = str(v.get()) if self.tensileNetwork.get() == 1: mat = febio.MatDef(matid=1, mname='cell', mtype=gtype, elsets='cell', attributes=gattributes) model.addMaterial(mat) model.addGeometry(mesh=mesh, mats=[mat]) #With a tensile network else: self.makeVTK(filename) self.findLocalCsys(filename) ind = self.tensileNetwork.get() - 1 ttype = keywords[self.tensileNetworks[ind]] ksi = [self.tensileParameters[ind][k].get() for k in ("ksi1", "ksi2=ksi3", "ksi2=ksi3")] beta = [self.tensileParameters[ind][k].get() for k in ("beta1", "beta2=beta3", "beta2=beta3")] mats = [] I1n2 = np.eye(3)[0:2, :] distances = numpy_support.vtk_to_numpy( self.vtkMeshes[filename].GetCellData().GetArray( "Signed Distances")) maxd = np.max(np.abs(distances)) for i, e in enumerate(self.data[filename]['elements']): normal = self.vtkMeshes[filename].GetCellData().GetArray( "LevelSet Normals").GetTuple3(i) # cross with both e1 and e2 to ensure linearly independent crossed = np.cross(normal, I1n2) norms = np.linalg.norm(crossed, axis=1) # get the index of the maximum norm; so never zero ind2 = np.argmax(norms) b = old_div(crossed[ind, :], norms[ind2]) normal = list(map(str, list(normal))) b = list(map(str, list(b))) d = self.tensileParameters[ind]["Distance Cutoff [0, 1]"].get() k = self.tensileParameters[ind]["Cutoff Grade (0, 1]"].get() x = old_div(np.abs(distances[i]), maxd) w = 0.5 * (1 - np.tanh(old_div((x - d), k))) if w < 0.05: w = 0.05 tmp_ksi = [w * v for v in ksi] tattributes = {"ksi": ",".join(map(str, tmp_ksi)), "beta": ",".join(map(str, beta))} mesh.addElementSet(setname='e{:d}'.format(i + 1), eids=[i + 1]) mats.append(febio.MatDef( matid=i + 1, mname='cell', mtype="solid mixture", elsets='e{:d}'.format(i + 1), attributes={ 'mat_axis': ['vector', ','.join(normal), ','.join(b)]})) mats[-1].addBlock(branch=1, btype='solid', mtype=gtype, attributes=gattributes) mats[-1].addBlock(branch=1, btype='solid', mtype=ttype, attributes=tattributes) model.addMaterial(mats[-1]) model.addGeometry(mesh=mesh, mats=mats) ctrl = febio.Control() ctrl.setAttributes({'title': 'cell', 'max_ups': '0'}) model.addControl(ctrl, step=0) boundary = febio.Boundary(steps=1) for i, bc in enumerate(self.data[filename]['boundary conditions']): boundary.addPrescribed( step=0, nodeid=self.data[filename]['surfaces'][i], dof='x', lc='1', scale=str(bc[0])) boundary.addPrescribed( step=0, nodeid=self.data[filename]['surfaces'][i], dof='y', lc='1', scale=str(bc[1])) boundary.addPrescribed( step=0, nodeid=self.data[filename]['surfaces'][i], dof='z', lc='1', scale=str(bc[2])) model.addBoundary(boundary=boundary) model.addLoadCurve(lc='1', lctype='linear', points=[0, 0, 1, 1]) model.writeModel() subprocess.call(self._FEBIO_BIN + " -i " + modelname, shell=True) def analyzeResults(self): self.matched = [] # for paired comparisons for i, f in enumerate(self.pickles): s = f.split(os.sep)[-1] if not(fnmatch.filter( itertools.chain.from_iterable(self.matched), "*" + s)): self.matched.append(fnmatch.filter(self.pickles, "*" + s)) plotname = f.replace('.pkl', '.xplt') print("\n... Analyzing results for {:s}".format(plotname)) results = febio.FebPlt(plotname) stress = np.zeros((len(self.data[f]['elements']), 3, 3), float) strain = np.copy(stress) #material element volumes mvolumes = np.zeros(len(self.data[f]['elements']), float) #spatial element volumes svolumes = np.copy(mvolumes) nnodes = len(list(results.NodeData.keys())) displacement = np.zeros((nnodes, 3)) for j, n in enumerate(self.data[f]['nodes']): tmp = results.NodeData[j + 1]['displacement'][-1, :] displacement[j, :] = [tmp[0], tmp[1], tmp[2]] pstress = [] pstressdir = [] pstrain = [] pstraindir = [] for j, e in enumerate(self.data[f]['elements']): tmp = results.ElementData[j + 1]['stress'][-1, :] stress[j, :, :] = [[tmp[0], tmp[3], tmp[5]], [tmp[3], tmp[1], tmp[4]], [tmp[5], tmp[4], tmp[2]]] #material coordinates X = np.zeros((4, 3), float) #spatial coordinates x = np.zeros((4, 3), float) for k in range(4): X[k, :] = self.data[f]['nodes'][e[k] - 1] x[k, :] = (X[k, :] + results.NodeData[e[k]]['displacement'][-1, :]) #set up tangent space W = np.zeros((6, 3), float) w = np.zeros((6, 3), float) for k, c in enumerate( [(0, 1), (0, 2), (0, 3), (1, 3), (2, 3), (1, 2)]): W[k, :] = X[c[1], :] - X[c[0], :] w[k, :] = x[c[1], :] - x[c[0], :] dX = np.zeros((6, 6), float) ds = np.zeros((6, 1), float) for k in range(6): for l in range(3): dX[k, l] = 2 * W[k, l] ** 2 dX[k, 3] = 4 * W[k, 0] * W[k, 1] dX[k, 4] = 4 * W[k, 1] * W[k, 2] dX[k, 5] = 4 * W[k, 0] * W[k, 2] ds[k, 0] = (np.linalg.norm(w[k, :]) ** 2 - np.linalg.norm(W[k, :]) ** 2) #solve for strain E = np.linalg.solve(dX, ds) #get volumes mvolumes[j] = old_div(np.abs( np.dot(W[0, :], np.cross(W[1, :], W[2, :]))), 6.0) svolumes[j] = old_div(np.abs( np.dot(w[0, :], np.cross(w[1, :], w[2, :]))), 6.0) strain[j, :, :] = [[E[0], E[3], E[5]], [E[3], E[1], E[4]], [E[5], E[4], E[2]]] #eigenvalues and eigenvectors of stress and strain tensors #eigenvectors are normalized eigstrain, eigstraindir = np.linalg.eigh(strain[j, :, :]) order = np.argsort(eigstrain) eigstrain = eigstrain[order] eigstraindir /= np.linalg.norm(eigstraindir, axis=0, keepdims=True) eigstraindir = eigstraindir[:, order] pstrain.append(eigstrain) pstraindir.append(eigstraindir) eigstress, eigstressdir = np.linalg.eigh(stress[j, :, :]) order = np.argsort(eigstress) eigstress = eigstress[order] eigstressdir /= np.linalg.norm(eigstressdir, axis=0, keepdims=True) eigstressdir = eigstressdir[:, order] pstress.append(eigstress) pstressdir.append(eigstressdir) pstress = np.array(pstress) pstressdir = np.array(pstressdir) pstrain = np.array(pstrain) pstraindir = np.array(pstraindir) #save reference volumes self.volumes.update({f: mvolumes}) self.results['Effective Strain (von Mises)'].update( {f: np.sqrt(old_div(((pstrain[:, 2] - pstrain[:, 1]) ** 2 + (pstrain[:, 1] - pstrain[:, 0]) ** 2 + (pstrain[:, 2] - pstrain[:, 0]) ** 2), 2.0))}) self.results['Maximum Compressive Strain'].update( {f: np.outer(pstrain[:, 0], [1 , 1, 1]) * pstraindir[:, :, 0]}) self.results['Maximum Tensile Strain'].update( {f: np.outer(pstrain[:, 2], [1, 1, 1]) * pstraindir[:, :, 2]}) self.results['Maximum Shear Strain'].update( {f: 0.5 * (pstrain[:, 2] - pstrain[:, 0])}) self.results['Volumetric Strain'].update( {f: old_div(svolumes, mvolumes) - 1.0}) self.results['Effective Stress (von Mises)'].update( {f: np.sqrt(old_div(((pstress[:, 2] - pstress[:, 1]) ** 2 + (pstress[:, 1] - pstress[:, 0]) ** 2 + (pstress[:, 2] - pstress[:, 0]) ** 2), 2.0))}) self.results['Maximum Compressive Stress'].update( {f: np.outer(pstress[:, 0], [1 , 1, 1]) * pstressdir[:, :, 0]}) self.results['Maximum Tensile Stress'].update( {f: np.outer(pstress[:, 2], [1, 1, 1]) * pstressdir[:, :, 2]}) self.results['Maximum Shear Stress'].update( {f: 0.5 * (pstress[:, 2] - pstress[:, 0])}) self.results['Pressure'].update( {f: old_div(np.sum(pstress, axis=1), 3.0)}) self.results['Displacement'].update({f: displacement}) for i, k in enumerate(self.outputs.keys()): if self.outputs[k].get(): for m in self.matched: weights = old_div(self.volumes[m[0]], np.sum(self.volumes[m[0]])) for j, f in enumerate(m): if len(self.results[k][f].shape) > 1: dat = np.ravel(np.linalg.norm(self.results[k][f], axis=1)) else: dat = np.ravel(self.results[k][f]) if self.analysis['Generate Histograms'].get(): IQR = np.subtract(*np.percentile(dat, [75, 25])) nbins = (int(old_div(np.ptp(dat), (2 * IQR * dat.size ** (old_div(-1., 3.)))))) h = histogram(dat, numbins=nbins, weights=weights) bins = np.linspace(h[1], h[1] + h[2] * nbins, nbins, endpoint=False) self.histograms[k][f] = {'bins': bins, 'heights': h[0], 'width': h[2]} if self.analysis['Tukey Boxplots'].get(): quantiles = np.zeros(3, float) for n, q in enumerate([0.25, 0.5, 0.75]): quantiles[n] = quantile_1D(dat, weights, q) self.boxwhiskers[k][f] = {'quantiles': quantiles, 'data': dat} if self.analysis['Calculate Differences'].get(): for c in itertools.combinations(m, 2): if len(self.results[k][c[0]].shape) > 1: dat1 = np.ravel(np.linalg.norm(self.results[k][c[0]], axis=1)) dat2 = np.ravel(np.linalg.norm(self.results[k][c[1]], axis=1)) else: dat1 = np.ravel(self.results[k][c[0]]) dat2 = np.ravel(self.results[k][c[1]]) difference = dat2 - dat1 wrms = np.sqrt(np.average(difference ** 2, weights=weights)) self.differences[k][c[1] + "MINUS" + c[0]] = { 'difference': difference, 'weighted RMS': wrms} self.saveResults() print("... ... Analysis Complete") def saveResults(self): top_dir = self.pickles[0].rsplit(os.sep, 2)[0] ts = datetime.datetime.fromtimestamp( time.time()).strftime("%Y-%m-%d_%H-%M-%S") output_dir = os.sep.join([top_dir, "FEA_analysis_" + ts]) os.mkdir(output_dir) for output in list(self.histograms.keys()): if self.histograms[output] and self.analysis["Generate Histograms"].get(): try: os.mkdir(os.sep.join([output_dir, "histograms"])) except: pass for m in self.matched: fig = Figure() FigureCanvasTkAgg(fig, self) ax = fig.add_subplot(111) #fig.set_size_inches(2.5, 2.5) for f in m: trunc_name = f.rsplit(os.sep, 2) ax.bar(self.histograms[output][f]['bins'], self.histograms[output][f]['heights'], self.histograms[output][f]['width'], label=trunc_name[1]) object_name = trunc_name[2].replace("cellFEA", "Cell ") object_name = object_name.replace(".pkl", "") ax.set_title(output + ' ' + object_name) cell_directory = os.path.join(output_dir, "histograms", object_name.replace(" ", "_")) try: os.mkdir(cell_directory) except: pass fig.savefig( os.path.join(cell_directory, output.replace(" ", "_") + ".svg"), bbox_inches='tight') fig.clear() del fig for output in list(self.boxwhiskers.keys()): if self.boxwhiskers[output] and self.analysis["Tukey Boxplots"].get(): try: os.mkdir(os.path.join(output_dir, "boxplots")) except: pass for m in self.matched: fig = Figure() FigureCanvasTkAgg(fig, self) ax = fig.add_subplot(111) x = [] q = [] labels = [] for f in m: trunc_name = f.rsplit(os.sep, 2) x.append(self.boxwhiskers[output][f]['data']) q.append(self.boxwhiskers[output][f]['quantiles']) labels.append(trunc_name[1]) q = np.array(q) a = ax.boxplot(x) object_name = trunc_name[2].replace("cellFEA", "Cell ") object_name = object_name.replace(".pkl", "") for i in range(q.shape[0]): a['medians'][i].set_ydata(q[i, 1]) a['boxes'][i]._xy[[0, 1, 4], 1] = q[i, 0] a['boxes'][i]._xy[[2, 3], 1] = q[i, 2] iqr = q[i, 2] - q[i, 0] y = x[i] top = np.max(y[y < q[i, 2] + 1.5 * iqr]) bottom = np.min(y[y > q[i, 0] - 1.5 * iqr]) a['whiskers'][2 * i].set_ydata( np.array([q[i, 0], bottom])) a['whiskers'][2 * i + 1].set_ydata( np.array([q[i, 2], top])) a['caps'][2 * i].set_ydata(np.array([bottom, bottom])) a['caps'][2 * i + 1].set_ydata(np.array([top, top])) low_fliers = y[y < bottom] high_fliers = y[y > top] fliers = np.concatenate((low_fliers, high_fliers)) a['fliers'][2 * i].set_ydata(fliers) a['fliers'][2 * i].set_xdata([i + 1] * fliers.size) object_name = trunc_name[2].replace("cellFEA", "Cell ") object_name = object_name.replace(".pkl", "") ax.set_title(object_name) ax.set_ylabel(output) ax.set_xticklabels(labels, rotation=45) cell_directory = os.path.join(output_dir, "boxplots", object_name.replace(" ", "_")) try: os.mkdir(cell_directory) except: pass fig.savefig( os.path.join(cell_directory, output.replace(" ", "_") + ".svg"), bbox_inches="tight") fig.clear() del fig for output in list(self.differences.keys()): if self.differences[output] and self.analysis["Calculate Differences"].get(): try: os.mkdir(os.sep.join([output_dir, "paired_differences"])) except: pass for m in self.matched: labels = [] for f in m: trunc_name = f.rsplit(os.sep, 2) labels.append(trunc_name[1]) N = len(m) grid = np.zeros((N, N), float) combos = list(itertools.combinations(m, 2)) enum_combos = list(itertools.combinations(list(range(N)), 2)) for c, e in zip(combos, enum_combos): grid[e[0], e[1]] = (self.differences[output] ["".join([c[1], 'MINUS', c[0]])] ['weighted RMS']) grid[e[1], e[0]] = grid[e[0], e[1]] fig = Figure() FigureCanvasTkAgg(fig, self) ax = fig.add_subplot(111) high = np.max(np.ravel(grid)) low = np.min(np.ravel(grid)) if abs(low - high) < 1e-3: high += 0.001 heatmap = ax.pcolormesh( grid, cmap=cm.Blues, edgecolors='black', vmin=low, vmax=high) ax.set_xticks(np.arange(N) + 0.5, minor=False) ax.set_yticks(np.arange(N) + 0.5, minor=False) ax.invert_yaxis() ax.xaxis.tick_top() ax.set_xticklabels(labels, minor=False) ax.set_yticklabels(labels, minor=False) fig.colorbar(heatmap) object_name = trunc_name[2].replace("cellFEA", "Cell ") object_name = object_name.replace(".pkl", "") ax.set_title(object_name, y=1.08) cell_directory = os.path.join( output_dir, "paired_differences", object_name.replace(" ", "_")) try: os.mkdir(cell_directory) except: pass fig.savefig( os.path.join(cell_directory, output.replace( " ", "_") + ".svg"), bbox_inches="tight") fig.clear() del fig if self.analysis['Convert to VTK'].get(): try: os.mkdir(os.path.join(output_dir, "vtk")) except: pass for m in self.matched: try: self.vtkMeshes[m[0]] except: self.makeVTK(m[0]) for output in list(self.outputs.keys()): if self.outputs[output].get(): for f in m: trunc_name = f.rsplit(os.sep, 2) vtkArray = numpy_support.numpy_to_vtk( np.ravel(self.results[output][f]).astype('f'), deep=True, array_type=vtk.VTK_FLOAT) shape = self.results[output][f].shape if len(shape) == 2: vtkArray.SetNumberOfComponents(shape[1]) elif len(shape) == 1: vtkArray.SetNumberOfComponents(1) else: print(("WARNING: {:s} has rank {:d}".format(f, len(shape)))) continue vtkArray.SetName(trunc_name[1] + ' ' + output) self.vtkMeshes[m[0]].GetCellData().AddArray( vtkArray) for f in m: arr = numpy_support.numpy_to_vtk(np.ravel(self.results['Displacement'][f]).astype('f'), deep=True, array_type=vtk.VTK_FLOAT) arr.SetName(trunc_name[1] + ' ' + 'Displacement') arr.SetNumberOfComponents(3) self.vtkMeshes[m[0]].GetPointData().AddArray(arr) object_name = trunc_name[2].replace("cellFEA", "Cell") object_name = object_name.replace(".pkl", ".vtu") idWriter = vtk.vtkXMLUnstructuredGridWriter() idWriter.SetFileName(os.path.join(output_dir, 'vtk', object_name)) idWriter.SetInputData(self.vtkMeshes[m[0]]) idWriter.Write() def makeVTK(self, filename): nelements = len(self.data[filename]['elements']) n = np.array(self.data[filename]['nodes']) arr = numpy_support.numpy_to_vtk( n.ravel(), deep=True, array_type=vtk.VTK_DOUBLE) arr.SetNumberOfComponents(3) tetraPoints = vtk.vtkPoints() tetraPoints.SetData(arr) vtkMesh = vtk.vtkUnstructuredGrid() vtkMesh.Allocate(nelements, nelements) vtkMesh.SetPoints(tetraPoints) e = np.array(self.data[filename]['elements'], np.uint32) - 1 e = np.hstack((np.ones((e.shape[0], 1), np.uint32) * 4, e)) arr = numpy_support.numpy_to_vtk(e.ravel(), deep=True, array_type=vtk.VTK_ID_TYPE) tet = vtk.vtkCellArray() tet.SetCells(old_div(e.size, 5), arr) vtkMesh.SetCells(10, tet) centroids = (n[e[:, 1]] + n[e[:, 2]] + n[e[:, 3]] + n[e[:, 4]]) centroids /= 4.0 arr = numpy_support.numpy_to_vtk( centroids.ravel(), deep=True, array_type=vtk.VTK_FLOAT) arr.SetName("Centroids") arr.SetNumberOfComponents(3) vtkMesh.GetCellData().AddArray(arr) self.vtkMeshes[filename] = vtkMesh def findLocalCsys(self, filename): poly = vtk.vtkGeometryFilter() poly.SetInputData(self.vtkMeshes[filename]) poly.Update() distanceFilter = vtk.vtkImplicitPolyDataDistance() distanceFilter.SetInput(poly.GetOutput()) gradients = vtk.vtkFloatArray() gradients.SetNumberOfComponents(3) gradients.SetName("LevelSet Normals") distances = vtk.vtkFloatArray() distances.SetNumberOfComponents(1) distances.SetName("Signed Distances") N = self.vtkMeshes[filename].GetCellData().GetArray( "Centroids").GetNumberOfTuples() for i in range(N): g = np.zeros(3, np.float32) p = self.vtkMeshes[filename].GetCellData().GetArray( "Centroids").GetTuple3(i) d = distanceFilter.EvaluateFunction(p) distanceFilter.EvaluateGradient(p, g) g = old_div(np.array(g), np.linalg.norm(np.array(g))) gradients.InsertNextTuple(g) distances.InsertNextValue(d) self.vtkMeshes[filename].GetCellData().AddArray(gradients) self.vtkMeshes[filename].GetCellData().AddArray(distances)
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)
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')) fname = utilities.file_exists(fname) 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')) fname = utilities.file_exists(fname) 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()) fname = utilities.file_exists(fname) 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' fname = utilities.file_exists(fname) 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' fname = utilities.file_exists(fname) 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' fname = utilities.file_exists(fname) phantom.publish_pdf(utilities.file_exists(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') fname = utilities.file_exists(fname) 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)
class CimApp(Frame): def __init__(self): Frame.__init__(self) self.file = None; self.master.title("Tiborcim") self.master.iconphoto(True, PhotoImage(file=ICON_PNG)) self.files = [] self.current_tab = StringVar() self.pack(expand=1, fill="both") self.master.minsize(300,300) self.master.geometry("500x500") self.menubar = Menu(self.master) self.fileMenu = Menu(self.master, tearoff=0) self.fileMenu.add_command(label="New", command=self.new_file, underline=0, accelerator="Ctrl+N") self.fileMenu.add_command(label="Open...", command=self.load_file, underline=0, accelerator="Ctrl+O") self.fileMenu.add_command(label="Save", command=self.file_save, underline=0, accelerator="Ctrl+S") self.fileMenu.add_command(label="Save As...", command=self.file_save_as, underline=5, accelerator="Ctrl+Alt+S") self.fileMenu.add_command(label="Close", command=self.close_file, underline=0, accelerator="Ctrl+W") self.fileMenu.add_separator() self.fileMenu.add_command(label="Exit", command=self.file_quit, underline=1) self.menubar.add_cascade(label="File", menu=self.fileMenu, underline=0) self.edit_program = Menu(self.master, tearoff=0) self.edit_program.add_command(label="Undo", command=self.edit_undo, underline=0, accelerator="Ctrl+Z") self.edit_program.add_command(label="Redo", command=self.edit_redo, underline=0, accelerator="Ctrl+Y") self.edit_program.add_separator() self.edit_program.add_command(label="Cut", command=self.edit_cut, underline=2, accelerator="Ctrl+X") self.edit_program.add_command(label="Copy", command=self.edit_copy, underline=0, accelerator="Ctrl+C") self.edit_program.add_command(label="Paste", command=self.edit_paste, underline=0, accelerator="Ctrl+V") self.menubar.add_cascade(label="Edit", menu=self.edit_program, underline=0) self.menu_program = Menu(self.master, tearoff=0) self.menu_program.add_command(label="Convert", command=self.convert_file, underline=0, accelerator="Ctrl+T") self.menu_program.add_command(label="Flash", command=self.flash_file, underline=0, accelerator="Ctrl+B") self.menu_program.add_separator() self.menubar.add_cascade(label="Program", menu=self.menu_program, underline=0) self.menu_view = Menu(self.master, tearoff=0) self.viewmode = StringVar() self.viewmode.set("tiborcim") self.menu_view.add_radiobutton(label="Tiborcim", command=self.view_tiborcim, variable=self.viewmode, value="tiborcim", underline=0) self.menu_view.add_radiobutton(label="Python", command=self.view_python, variable=self.viewmode, value="python", underline=0) self.menubar.add_cascade(label="View", menu=self.menu_view, underline=0) self.menu_help = Menu(self.master, tearoff=0) self.menu_samples = Menu(self.master, tearoff=0) samples = tiborcim.resources.samples_list() def add_sample (sample): self.menu_samples.add_command(label=sample, command=lambda: self.help_sample(sample)) for sample in samples: add_sample(sample) self.menu_help.add_cascade(label="Samples", menu=self.menu_samples, underline=0) self.menu_help.add_separator() self.menu_help.add_command(label="README", command=self.help_readme, underline=0) self.menu_help.add_separator() self.menu_help.add_command(label="About", command=self.help_about, underline=0) self.menubar.add_cascade(label="Help", menu=self.menu_help, underline=0) self.master.config(width=450, height=400, menu=self.menubar) self.bind_all("<Control-o>", self.load_file) self.bind_all("<Control-s>", self.file_save) self.bind_all("<Control-Alt-s>", self.file_save_as) self.bind_all("<Control-t>", self.convert_file) self.bind_all("<Control-b>", self.flash_file) self.bind_all("<Control-w>", self.close_file) self.master.protocol("WM_DELETE_WINDOW", self.file_quit) self.file_tabs = Notebook(self) self.file_tabs.bind_all("<<NotebookTabChanged>>", self.file_changed) self.file_tabs.pack(expand=1, fill="both") def file_changed(self, event): if len(self.file_tabs.tabs()) <= 0: self.add_file() return title = str(event.widget.tab(event.widget.index("current"),"text")).upper().strip() self.menu_program.delete(3, END) for tab in self.file_tabs.tabs(): tabtext = self.file_tabs.tab(self.file_tabs.index(tab),"text") if tabtext.upper().strip() == title: self.current_tab.set(tab) self.menu_program.add_radiobutton(label=tabtext, command=self.program_switch, underline=1, value=tab, variable=self.current_tab) if title != "PYTHON" or title != "TIBORCIM": if self.current_file().filename is not None: self.master.title(self.current_file().get_file() + " - Tiborcim") else: self.master.title("Tiborcim") if str(self.current_file().tab(self.current_file().index("current"),"text")).upper().strip() == "TIBORCIM": self.menubar.entryconfig("Edit", state=NORMAL) else: self.menubar.entryconfig("Edit", state=DISABLED) self.viewmode.set(self.current_file().viewmode) if title == "PYTHON": self.menubar.entryconfig("Edit", state=DISABLED) self.current_file().viewmode = "python"; self.viewmode.set("python"); if title == "TIBORCIM": self.menubar.entryconfig("Edit", state=NORMAL) self.current_file().viewmode = "tiborcim"; self.viewmode.set("tiborcim"); def add_file(self, file=None): filepage = CimFilePage(self.file_tabs) if file is None: self.file_tabs.add(filepage, text="Unsaved Program") else: filepage.load_file(file) self.file_tabs.add(filepage, text=filepage.get_file()) self.files.append(filepage) self.file_tabs.select(filepage) def view_tiborcim(self, event=None): self.current_file().view_tiborcim() def view_python(self, event=None): self.current_file().view_python() def program_switch(self): self.file_tabs.select(self.current_tab.get()) def new_file(self, event=None): self.add_file() def load_file(self, event=None): fname = askopenfilename(filetypes=(("Tiborcim", "*.tibas"),("All files", "*.*") ), parent=self.master) if fname: self.add_file(fname) def file_save(self, event=None): self.current_file().save_file() self.file_tabs.tab(self.current_file(), text=self.current_file().get_file()) def file_save_as(self, event=None): self.current_file().save_file_as() self.file_tabs.tab(self.current_file(), text=self.current_file().get_file()) def convert_file(self, event=None): self.current_file().convert_file() def current_file(self, event=None): return self.files[int(self.file_tabs.index(self.file_tabs.select()))] def flash_file(self, event=None): from tiborcim.tibc import compiler as tibc from tiborcim.tibc import flash from tiborcim.tibc import TibcStatus as status com = tibc(self.current_file().text_tiborcim.get("1.0", "end")) res = flash(''.join(com.output)) if res is status.SUCCESS: showinfo(title='Success', message='File Flashed', parent=self.master) else: showerror(title='Failure', message='An Error Occured. Code: %s' % res, parent=self.master) def close_file(self, event=None): logging.debug("Close File") file = self.current_file() if file.close(): self.file_tabs.forget(file) self.files.remove(file) def edit_cut(self, event=None): self.current_file().text_tiborcim.event_generate('<Control-x>') def edit_copy(self, event=None): self.current_file().text_tiborcim.event_generate('<Control-c>') def edit_paste(self, event=None): self.current_file().text_tiborcim.event_generate('<Control-v>') def edit_redo(self, event=None): self.current_file().text_tiborcim.edit_redo() def edit_undo(self, event=None): self.current_file().text_tiborcim.edit_undo() def help_about(self, event=None): CimAbout.show(self) def help_readme(self, event=None): CimReadme.show(self) def help_sample(self, sam): print(sam) filepage = CimFilePage(self.file_tabs) filepage.load_file(tiborcim.resources.sample_path(sam)) filepage.filename = None self.file_tabs.add(filepage, text="Unsaved Program") self.files.append(filepage) self.file_tabs.select(filepage) def file_quit(self, event=None): for ndx, member in enumerate(self.files): logging.debug(self.files[ndx].saved) if not self.files[ndx].close(): return self.quit()
class DeviceSelector: BASE_DIR = os.path.abspath(os.path.dirname(__file__)) devices = None local = LocalConnector() grid = GridConnector() sauce = SauceConnector() mc = MCConnector() def __init__(self, parallel=False, platform="mobile"): self.parallel = parallel self.platform = platform def start(self): parallel = self.parallel platform = self.platform # Create Window self.root = Tk() win = self.root self.note = Notebook(self.root) # Set Window Properties win.wm_title("Test Runner") win.minsize(width=500, height=500) # Create Listbox scrollbar = Scrollbar(win) scrollbar.pack(side=RIGHT, fill=Y) # Add Mustard Checkbox and Instructions Label frame = Frame(win) self.mustard = GetConfig("SKIP_MUSTARD").lower() == "false" c = Checkbutton(frame, text="Add Mustard?", command=self._toggleMustard) if self.mustard: c.select() c.pack(side=RIGHT) mobileFrame = Frame(win) if parallel: label = Label(frame, text="Please Select one or more devices to run") label.pack(side=LEFT) self.listboxMobile = Listbox(mobileFrame, selectmode=EXTENDED) else: label = Label(frame, text="Please Select one device to run") label.pack(side=LEFT) self.listboxMobile = Listbox(mobileFrame, selectmode=SINGLE) frame.pack(fill=X) self.listboxMobile.pack(fill=BOTH, expand=1) # Attach Scrollbar to Listbox self.listboxMobile.config(yscrollcommand=scrollbar.set) scrollbar.config(command=self.listboxMobile.yview) # Generate Listbox Data mobileData = [] mobileNodes = self.grid.mobileNodes for node in mobileNodes: mobileData.append(node) self.listboxMobile.insert(END, node.displayString()) sauceNodes = self.sauce.mobileNodes for node in sauceNodes: mobileData.append(node) self.listboxMobile.insert(END, node.displayString()) mcNodes = self.mc.mobileNodes for node in mcNodes: mobileData.append(node) self.listboxMobile.insert(END, node.displayString()) self.mobileData = mobileData self.listboxMobile.insert(END, "Local Device") desktopFrame = Frame(win) if parallel: self.listboxDesktop = Listbox(desktopFrame, selectmode=EXTENDED) else: self.listboxDesktop = Listbox(desktopFrame, selectmode=SINGLE) frame.pack(fill=X) self.listboxDesktop.pack(fill=BOTH, expand=1) # Attach Scrollbar to Listbox self.listboxDesktop.config(yscrollcommand=scrollbar.set) scrollbar.config(command=self.listboxDesktop.yview) # Generate Listbox Data webData = [] webDisplay = [] localNodes = self.local.webNodes for node in localNodes: webData.append(node) self.listboxDesktop.insert(END, node.displayString()) webNodes = self.grid.webNodes for node in webNodes: ds = node.displayString() if ds not in webDisplay: webDisplay.append(ds) webData.append(node) self.listboxDesktop.insert(END, ds) sauceNodes = self.sauce.webNodes for node in sauceNodes: webData.append(node) self.listboxDesktop.insert(END, node.displayString()) sauceNodes = self.sauce.mobileWebNodes for node in sauceNodes: webData.append(node) self.listboxDesktop.insert(END, node.displayString()) mcNodes = self.mc.webNodes for node in mcNodes: webData.append(node) self.listboxDesktop.insert(END, node.displayString()) self.webData = webData self.frame = Frame(win) self.frame.pack(fill=X) # Create Buttons Button(mobileFrame, text="Cancel", fg="red", command=self.frame.quit, width=50, height=5).pack( side=RIGHT, fill=Y ) Button(mobileFrame, text="Run Test", fg="green", command=self._saveDevices, width=50).pack(side=LEFT, fill=Y) # Create Buttons Button(desktopFrame, text="Cancel", fg="red", command=self.frame.quit, width=50, height=5).pack( side=RIGHT, fill=Y ) Button(desktopFrame, text="Run Test", fg="green", command=self._saveDevicesDesktop, width=50).pack( side=LEFT, fill=Y ) if platform.lower() == "mobile": self.note.add(mobileFrame, text="Mobile") self.note.add(desktopFrame, text="Web") else: self.note.add(desktopFrame, text="Web") self.note.add(mobileFrame, text="Mobile") self.note.pack(fill=BOTH, expand=1) # allow double clicking in listbox to select a browser self.listboxMobile.bind("<Double-1>", lambda x: self._saveDevices()) self.listboxDesktop.bind("<Double-1>", lambda x: self._saveDevicesDesktop()) def _toggleMustard(self): self.mustard = not self.mustard def getDevice(self, filter=None, mustard=True): if filter: # webNodes = self.grid.webNodes # mobileNodes = self.grid.mobileNodes if self.platform: if self.platform == "desktop": nodes = self.grid.webNodes + self.sauce.webNodes + self.sauce.mobileWebNodes elif self.platform == "mobile": nodes = self.grid.mobileNodes + self.sauce.mobileNodes else: nodes = self.grid.webNodes + self.grid.mobileNodes + self.sauce.webNodes + self.sauce.mobileWebNodes output = [] for node in nodes: if re.search(filter, node.displayString()): dc = node.desiredCaps(mustard=mustard) output.append(dc) return output else: self.start() # for osx bring selector window to the front if sys.platform.lower() == "darwin": # Mac OS self.root.lift() self.root.attributes("-topmost", True) self.root.mainloop() self.root.destroy() output = [] for x in range(len(self.devices)): dc = self.devices[x].desiredCaps(mustard=self.mustard) output.append(dc) return output def _saveDevicesDesktop(self): selected = self.listboxDesktop.curselection() output = [] for selection in selected: output.append(self.webData[int(selection)]) self.frame.quit() self.devices = output def _saveDevices(self): selected = self.listboxMobile.curselection() output = [] for selection in selected: output.append(self.mobileData[int(selection)]) self.frame.quit() self.devices = output
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")
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): Tk.__init__(self) pwd = os.path.dirname(__file__) # ico = PhotoImage(file=os.path.join(pwd, "icon.png")) # self.call('wm', 'iconphoto', self._w, ico) self.title("Spectacuplot!") left_frame = Frame(self) control_frame = Frame(left_frame) left_frame.pack(side=LEFT, fill=Y) control_frame.pack(anchor=N,fill=BOTH,expand=1) # Menu bar mb = Menu(self) file_menu = Menu(mb) file_menu.add_command(label='Open...', command=self.open_dialog, accelerator='Ctrl-O') file_menu.add_command(label='Close All Files', command=self.close_files) # Get recent files self.recent = [] self.recent_commands = [] try: recent_files = open(os.path.expanduser("~/spectacuplot_recent"), "r") for f in recent_files: self.recent.append(f.strip()) self.recent_commands.append(functools.partial(self.open, f.strip())) recent_files.close() except: print("no recent files") self.recent_cascade = Menu(file_menu) for (f, c) in zip(self.recent, self.recent_commands): self.recent_cascade.add_command(label=f, command=c) file_menu.add_cascade(label="Recent Files", menu=self.recent_cascade) # Set up stuff for quitting Spectacuplot file_menu.add_command(label='Exit', command=self.quit) self.protocol("WM_DELETE_WINDOW", self.quit) self.bind_all("<Control-o>", self.open_dialog) self.config(menu=mb) mb.add_cascade(label="File", menu=file_menu) # Notebook nb = Notebook(control_frame, name="controls") nb.enable_traversal() nb.pack(expand=1, fill=BOTH) # Plot Area self.plot_frame = PlotArea(self) self.plot_frame.pack(side=LEFT, fill=BOTH, expand=1) # This will be used as the notbook tab for plotting individual datasets self.plot_set_tab = OpSetPlot(nb, self.opened_files, self.plot_frame) # This will be used as the notebook tab for plotting dataset diffs self.diff_tab = OpDiffPlot(nb, self.opened_files, self.plot_frame) nb.add(self.plot_set_tab, text="Plot Set") nb.add(self.diff_tab, text="Diff Sets")