def createCanvas(self): f = Frame(self) canvas = Canvas(f, width=self.canvasH, height=self.canvasH, bg='white') xbar = Scrollbar( f, orient='horizontal', command=canvas.xview ) ybar = Scrollbar( f, orient='vertical', command=canvas.yview ) canvas.configure( xscrollcommand=xbar.set, yscrollcommand=ybar.set ) # Resize box resize = Label( f, bg='white' ) # Layout canvas.grid( row=0, column=1, sticky='nsew') ybar.grid( row=0, column=2, sticky='ns') xbar.grid( row=1, column=1, sticky='ew' ) resize.grid( row=1, column=2, sticky='nsew' ) # Resize behavior f.rowconfigure( 0, weight=1 ) f.columnconfigure( 1, weight=1 ) f.grid( row=0, column=0, sticky='nsew' ) f.bind( '<Configure>', lambda event: self.updateScrollRegion() ) # Mouse bindings canvas.bind( '<ButtonPress-1>', self.clickCanvas ) canvas.bind( '<B1-Motion>', self.dragCanvas ) canvas.bind( '<ButtonRelease-1>', self.releaseCanvas ) return f, canvas
def configureLabelFrame(self, frame: tk.Frame, mainLabel: tk.Label, labels): frame.columnconfigure(0, weight=1) mainLabel.grid(row=0, columnspan=2, column=1) for i in range(labels.__len__()): #tk.Label(frame, text=labels[i], font=self.lightFont).grid(row=i+1, column=0, columnspan=2) frame.rowconfigure(i, weight=1) frame.rowconfigure(labels.__len__(), weight=1)
def collectValues(self): self.draw_acc_plot() frameScatPlot = Frame(self) frameScatPlot.grid(column=0, row=60, columnspan=100, sticky=Tkconstants.NSEW) frameScatPlot.rowconfigure(50, weight=100) frameScatPlot.columnconfigure(1, weight=1) frameFeatHist = Frame(self) frameFeatHist.grid(column=0, row=30, columnspan=100, sticky=Tkconstants.NSEW) frameFeatHist.rowconfigure(50, weight=100) frameFeatHist.columnconfigure(1, weight=1) n = 8 myG = Main2.FeatureSelect() myG.read_Data_Method2() idx = myG.F_SCORE() featureList, featName = myG.get_Feature_List(idx, n) self.draw_Feat_Hist(frameFeatHist, featureList, n, featName) self.draw_Scatt_Plot(frameScatPlot, featureList, n, featName)
def addPathFrame(self): frame=Frame(self) frame.pack(fill=tk.X,expand=0,side=tk.TOP,padx=8,pady=5) frame.columnconfigure(1,weight=1) #------------------Database file------------------ label=tk.Label(frame,text=dgbk('ting.sqlite文件:'),\ bg='#bbb') label.grid(row=0,column=0,\ sticky=tk.W,padx=8) self.db_entry=tk.Entry(frame) self.db_entry.grid(row=0,column=1,sticky=tk.W+tk.E,padx=8) self.db_button=tk.Button(frame,text=dgbk('打开'),command=self.openFile) self.db_button.grid(row=0,column=2,padx=8,sticky=tk.E) #--------------------Output dir-------------------- label2=tk.Label(frame,text=dgbk('导出到文件夹:'),\ bg='#bbb') label2.grid(row=2,column=0,\ sticky=tk.W,padx=8) self.out_entry=tk.Entry(frame) self.out_entry.grid(row=2,column=1,sticky=tk.W+tk.E,padx=8) self.out_button=tk.Button(frame,text=dgbk('选择'),command=self.openDir) self.out_button.grid(row=2,column=2,padx=8,sticky=tk.E)
def testScrollableFrame(): root = Tk() root.geometry("300x280+300+300") root.rowconfigure(0, weight=1) root.columnconfigure(0, weight=1) f = Frame(root, background="#ffffff") f.rowconfigure(1, weight=1) f.columnconfigure(0, weight=1) f.grid(row=0, column=0, sticky="nswe", padx=3, pady=3) ttk.Label(f, text="TableView Development").grid(row=0, column=0, sticky="nwe", padx=3, pady=3) body = TableBody(f) body.grid(row=1, column=0, sticky='nswe', padx=3, pady=3) for i in range(10): x = i * 53 + 5 f1 = Frame(body.canvas, background="#000000") #f1.place(x=x, y=5, width=50, height=50) #body.canvas.create_window((x, 5), window=f1, anchor="nw", width=50, height=50) #body.addWidget((x, 5), window=f1, anchor="nw", width=50, height=50) #body.addWidgetNW( f1, x, 5, 50, 50 ) body.addColumn(80) root.mainloop()
def __init__(self, root, title): self.root = root self.root.title(title) # Variable that stores file handle (may be unnecessary) self.file_handle = "" master_frame = Frame(root) master_frame.pack(expand="yes", fill="both") # Create left button frame and buttons button_frame = Frame(master_frame) self.open_button = Button(button_frame, text="Choose File", command=self.load_file) self.open_button.pack(expand="yes", fill="both") self.apply_button = Button(button_frame, text="Apply", command=self.apply_consistent, state="disabled") self.apply_button.pack(expand="yes", fill="both") self.save_button = Button(button_frame, text="Save File", command=self.save_file, state="disabled") self.save_button.pack(expand="yes", fill="both") # Create text frame and initialize text widget text_frame = Frame(master_frame) self.text_box = Text(text_frame, height=10, width=50, state="disabled") self.text_box.pack(side="top", expand="yes", fill="both") # Configure weights for grid elements master_frame.columnconfigure(0, weight=1) master_frame.columnconfigure(1, weight=5) for i in range(3): master_frame.rowconfigure(i, weight=1) # Position button and text frames button_frame.grid(row=0, column=0, rowspan=3, sticky="nsew") text_frame.grid(row=0, column=1, rowspan=3, sticky="nsew") self.root.minsize(500, 200)
def showPlotTools(self): f2= Frame(self.frame, relief=FLAT,bg='#FADC46') f2.grid(row=1,column=0,rowspan=2,columnspan=3,sticky=N+S+E+W,padx=10,pady =10) b1 = Button(f2,text='3D K',relief=RAISED,command= lambda:self.plotButtonPressed(1)) b1.grid(row=0, column=0,sticky=N+S+E+W,padx=5,pady =5) b2 = Button(f2,text='3D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(2)) b2.grid(row=0, column=1,sticky=N+S+E+W,padx=5,pady =5) b3 = Button(f2,text='3D DP',relief=RAISED,command=lambda:self.plotButtonPressed(3)) b3.grid(row=0, column=2,sticky=N+S+E+W,padx=5,pady =5) b4 = Button(f2,text='2D K',relief=RAISED,command=lambda:self.plotButtonPressed(4)) b4.grid(row=1, column=0,sticky=N+S+E+W,padx=5,pady =5) b5 = Button(f2,text='2D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(5)) b5.grid(row=1, column=1,sticky=N+S+E+W,padx=5,pady =5) b6 = Button(f2,text='2D DP',relief=RAISED,command=lambda:self.plotButtonPressed(6)) b6.grid(row=1, column=2,sticky=N+S+E+W,padx=5,pady =5) f2.columnconfigure(0, weight=1) f2.columnconfigure(1, weight=1) f2.columnconfigure(2, weight=1) f2.rowconfigure(0, weight=1) f2.rowconfigure(1, weight=1)
def addPathFrame(self): frame = Frame(self) frame.pack(fill=tk.X, expand=0, side=tk.TOP, padx=8, pady=5) frame.columnconfigure(1, weight=1) #------------------Database file------------------ label=tk.Label(frame,text=dgbk('ting.sqlite文件:'),\ bg='#bbb') label.grid(row=0,column=0,\ sticky=tk.W,padx=8) self.db_entry = tk.Entry(frame) self.db_entry.grid(row=0, column=1, sticky=tk.W + tk.E, padx=8) self.db_button = tk.Button(frame, text=dgbk('打开'), command=self.openFile) self.db_button.grid(row=0, column=2, padx=8, sticky=tk.E) #--------------------Output dir-------------------- label2=tk.Label(frame,text=dgbk('导出到文件夹:'),\ bg='#bbb') label2.grid(row=2,column=0,\ sticky=tk.W,padx=8) self.out_entry = tk.Entry(frame) self.out_entry.grid(row=2, column=1, sticky=tk.W + tk.E, padx=8) self.out_button = tk.Button(frame, text=dgbk('选择'), command=self.openDir) self.out_button.grid(row=2, column=2, padx=8, sticky=tk.E)
def __init__(self, parent): super().__init__(parent) self.attributes('-topmost', 'true') self.resizable(width=False, height=False) self.minsize(750, 500) self.maxsize(750, 550) mainFrame = Frame(self, width=500, height=500) mainFrame.grid(row=0, column=0, columnspan=2) mainFrame.columnconfigure(0, weight=1) mainFrame.columnconfigure(1, weight=1) mainFrame.columnconfigure(0, pad=20) sideBar = Frame(mainFrame) slides = Frame(mainFrame) sideBar.grid(row=0, column=0) slides.grid(row=0, column=1) lbl = Label(slides) lbl.grid(row=0, column=1, columnspan=1, sticky=N, padx=50, pady=20) ScrollBar(sideBar, lbl, self).pack(side="top", fill="both", expand=True) self.protocol('WM_DELETE_WINDOW', self.onClose)
class ScrolledFrame(Frame): def __init__(self, master, **kw): self.frame = Frame(master) self.canvas = Canvas(self.frame, bd=0, highlightthickness=0) yscrollbar = AutoScrollbar(self.frame, command=self.canvas.yview) Frame.__init__(self, self.canvas, **kw) self.canvas.config(yscrollcommand=yscrollbar.set) self.id = self.canvas.create_window(0, 0, window=self, anchor="nw") self.frame.columnconfigure(0, weight=1) self.frame.rowconfigure(0, weight=1) self.canvas.grid(column=0, row=0, sticky="NSEW") yscrollbar.grid(column=1, row=0, rowspan=2, sticky="NSEW") self.frame.bind("<Configure>", self.canvas_config) self.bind_all("<MouseWheel>", self.on_mousewheel) self.bind_all("<KeyPress-Up>", lambda e: self.canvas.yview_scroll(-1, "units")) self.bind_all("<KeyPress-Down>", lambda e: self.canvas.yview_scroll(1, "units")) def canvas_config(self, event): frameWidth = self.frame.winfo_width() canvas = self.canvas canvas.itemconfig(self.id, width=frameWidth) canvas.configure(scrollregion=canvas.bbox(self.id), width=frameWidth) def on_mousewheel(self, event): direction = -1 if event.delta > 0 else 1 self.canvas.yview_scroll(direction, "units") def grid(self, **kw): self.frame.grid(**kw)
class Test(Tk): def __init__(self): Tk.__init__(self, None) self.frame = Frame(None) self.frame.columnconfigure(0, weight=1) self.frame.rowconfigure(0, weight=1) self.frame.grid(row=0, column=0, sticky=W + E + N + S) fig = Figure() xval = arange(500) / 10. yval = sin(xval) ax1 = fig.add_subplot(111) ax1.plot(xval, yval) self.hbar = Scrollbar(self.frame, orient=HORIZONTAL) self.vbar = Scrollbar(self.frame, orient=VERTICAL) self.canvas = FigureCanvasTkAgg(fig, master=self.frame) self.canvas.get_tk_widget().config(bg='#FFFFFF', scrollregion=(0, 0, 500, 500)) self.canvas.get_tk_widget().config(width=800, height=500) self.canvas.get_tk_widget().config(xscrollcommand=self.hbar.set, yscrollcommand=self.vbar.set) self.canvas.get_tk_widget().grid(row=0, column=0, sticky=W + E + N + S) self.hbar.grid(row=1, column=0, sticky=W + E) self.hbar.config(command=self.canvas.get_tk_widget().xview) self.vbar.grid(row=0, column=1, sticky=N + S) self.vbar.config(command=self.canvas.get_tk_widget().yview) self.frame.config(width=100, height=100) # this has no effect
def drop_down(): '''''' root = Tk() root.title("Tk dropdown example") # Add a grid mainframe = Frame(root) mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) mainframe.pack(pady=100, padx=100) # Create a Tkinter variable tkvar = StringVar(root) # Dictionary with options choices = {'Pizza', 'Lasagne', 'Fries', 'Fish', 'Potatoe'} tkvar.set('Pizza') # set the default option popupMenu = OptionMenu(mainframe, tkvar, *choices) Label(mainframe, text="Choose a dish").grid(row=1, column=1) popupMenu.grid(row=2, column=1) # on change dropdown value def change_dropdown(*args): print(tkvar.get()) # link function to change dropdown tkvar.trace('w', change_dropdown) root.mainloop()
def Affichage_bandeau(fenetre): #On cree la Frame bandeau Bandeau = Frame(fenetre, bd=5, relief='raised') #On ajoute les noms Label_text_Neurodrop = Label(Bandeau, text='Neurodrop', foreground='#e7feff', font="Baskerville 45 italic", background='#318ce7') Label_text_iGEM = Label(Bandeau, text='iGEM Grenoble 2019', background='#006b3c', font="Arial 30 bold", foreground='#ffffff') Label_text_version = Label(Bandeau, text='version 01.000', background='#ffdead', font="Baskerville 12 italic", foreground='#191970') #On positionne les noms Label_text_Neurodrop.grid(column=0, row=0, sticky='wens') Label_text_iGEM.grid(column=1, row=0, sticky='wens') Label_text_version.grid(column=2, row=0, sticky='wens') #On définit l'apparence du bandeau Bandeau.columnconfigure(0, weight=1) Bandeau.columnconfigure(1, weight=1) Bandeau.columnconfigure(2, weight=1)
class NotaForm(Toplevel): """ A form to display/save notes. param: var: Any a variable to store the data in the form. param: initial_data: dict a dictinary with the data to fill the form. """ def __init__(self, var=None, initial_data=None, *args, **kwargs): super().__init__(*args, **kwargs) self.title("Agregar Nota") self.geometry("350x450") self.resizable(False, False) self.grab_set() if var is not None: self.data = var else: self.data = {} self.make_widgets() if initial_data is not None: self.title("Modificar Nota") self.data['id'] = initial_data['id'] self.load_data(initial_data) self.wait_window(self) def make_widgets(self): self.top_container = Frame(self) self.title_label = ttk.Label(self.top_container, text='Título:') self.title_entry = ttk.Entry(self.top_container) self.body_text = Text(self) self.save_btn = ttk.Button(self, text='Guardar', command=self.on_guardar) self.cancel_btn = ttk.Button(self, text='Cancelar', command=self.on_cancel) self.top_container.grid(row=0, column=0, sticky='ew', columnspan=2) self.top_container.columnconfigure(1, weight=1) self.title_label.grid(row=0, column=0, sticky='w') self.title_entry.grid(row=0, column=1, sticky='ew') self.body_text.grid(row=1, column=0, columnspan=2, sticky='nsew') self.save_btn.grid(row=2, column=0) self.cancel_btn.grid(row=2, column=1) # configuring columns and rows self.rowconfigure(1, weight=1) self.columnconfigure((0, 1), weight=1) def load_data(self, data): self.title_entry.insert(0, data['title']) self.body_text.insert(0.0, data['body']) def on_cancel(self): self.destroy() def on_guardar(self): self.data['title'] = self.title_entry.get().strip() self.data['body'] = self.body_text.get(0.0, END).strip() self.destroy()
class GUI: def __init__(self, root, halloween): self.halloween = halloween self.root = root self.initialize() self.loop() def initialize(self): self.days = StringVar() self.initialize_window() self.initialize_mainframe() def initialize_mainframe(self): self.mainframe = Frame(root, bg="#FA8E0F") self.mainframe.grid(column=0, row=0, sticky="NEWS") self.mainframe.columnconfigure(0, weight=1) self.mainframe.rowconfigure(0, weight=1) self.headingFont = font.Font( family="TkHeadingFont", size=32, weight="bold", ) self.label = Label(self.mainframe, textvariable=self.days, anchor="center", font=self.headingFont, foreground="#9601D4", bg="#05CD1D") self.label.grid(column=0, row=0, sticky="NEWS") for child in self.mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) def initialize_window(self): self.set_icon() self.root.resizable(0, 0) self.root.title("Silver Shamrock") self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) def set_icon(self): if getattr(sys, 'frozen', False): icon = path.join(sys._MEIPASS, 'pumpkin.ico') else: icon = path.join( path.dirname(path.abspath(__file__)), 'pumpkin.ico', ) self.root.iconbitmap(icon) def loop(self): until = self.halloween.until days = until.days minutes, seconds = divmod(until.seconds, 60) hours, minutes = divmod(minutes, 60) fmt = "{} Days\n{} Hours\n{} Minutes\n{} Seconds\n\n'Til Halloween!" self.days.set(fmt.format(days, hours, minutes, seconds)) self.root.after(1000, self.loop)
class Titlebar: def __init__(self, root, title="Titlebar"): self.title = title self.root = root self.root.update() self.geometry = self.root.wm_geometry() #Widgets: self.bar = Frame(self.root, bg="blue") self.body = Frame(self.root, bg="red") self.label = Label(self.bar, text=self.title) self.close_btn = Button(self.bar, text="X", command=self.root.destroy) self.max_btn = Button(self.bar, text="[]") self.min_btn = Button(self.bar, text="_") #Layout self.root.rowconfigure(1, weight=1) self.root.columnconfigure(0, weight=1) self.bar.columnconfigure(0, weight=1) self.bar.grid(row=0, column=0, sticky="new") self.body.grid(row=1, column=0, sticky="nsew") self.label.grid(row=0, column=0, sticky="w") self.min_btn.grid(row=0, column=1) self.max_btn.grid(row=0, column=2) self.close_btn.grid(row=0, column=3) # Geometry / Bindings self.delta_x, self.delta_y = 0, 0 self.bar.bind("<Button-1>", self.get_position) self.bar.bind("<B1-Motion>", self.move_window) self.titlebar() def titlebar(self): self.root.overrideredirect(True) self.root.geometry(self.geometry) def get_position(self, event): window_x = self.root.winfo_x() window_y = self.root.winfo_y() cursor_x = event.x_root cursor_y = event.y_root self.delta_x = cursor_x - window_x self.delta_y = cursor_y - window_y def move_window(self, event): self.root.geometry( f"+{event.x_root - self.delta_x}+{event.y_root - self.delta_y}")
def init( frm: tk.Frame, refresh_cback: Callable[[Optional[Set[Tuple[str, int]]]], None]) -> None: """Initialise the UI objects. The callback is triggered whenever the UI changes, passing along the visible items. """ global _type_cback def on_type(*args): """Re-search whenever text is typed.""" text = search_var.get().casefold() words = text.split() if not words: refresh_cback(None) return found: Set[Tuple[str, int]] = set() *words, last = words for word in words: try: found |= word_to_ids[word] except KeyError: pass if last: for match in database.iterkeys(last): found |= word_to_ids[match] # Calling the callback deselects us, so save and restore. insert = searchbar.index('insert') refresh_cback(found) def later(): searchbar.focus_set() searchbar.icursor(insert) searchbar.after_idle(later) frm.columnconfigure(1, weight=1) ttk.Label( frm, text=_('Search:'), ).grid(row=0, column=0) search_var = tk.StringVar() search_var.trace_add('write', on_type) searchbar = ttk.Entry(frm, textvariable=search_var) searchbar.grid(row=0, column=1, sticky='EW') _type_cback = on_type
def addActionFrame(self): frame = Frame(self, relief=tk.RAISED, borderwidth=1) frame.pack(fill=tk.X,side=tk.TOP,\ expand=0,padx=8,pady=5) #label=tk.Label(frame,text='Actions:',bg='#bbb') #label.grid(row=0,column=0,sticky=tk.W,padx=8) #---------------Action checkbuttons--------------- frame.columnconfigure(0, weight=1) #---------------------2nd row--------------------- subframe = Frame(frame) subframe.grid(row=1,column=0,columnspan=6,sticky=tk.W+tk.E,\ pady=5) #-------------------Album options------------------- albumlabel=tk.Label(subframe,text=dgbk('专辑:'),\ bg='#bbb') albumlabel.pack(side=tk.LEFT, padx=8) self.album = tk.StringVar() self.albumnames = [ 'All', ] self.albummenu=Combobox(subframe,textvariable=\ self.album,values=self.albumnames,state='readonly') self.albummenu.current(0) self.albummenu.bind('<<ComboboxSelected>>', self.setAlbum) self.albummenu.pack(side=tk.LEFT, padx=8) #-------------------Quit button------------------- quit_button=tk.Button(subframe,text=dgbk('退出'),\ command=self.quit) quit_button.pack(side=tk.RIGHT, padx=8) #-------------------Stop button------------------- ''' self.stop_button=tk.Button(subframe,text='Stop',\ command=self.stop) self.stop_button.pack(side=tk.RIGHT,padx=8) ''' #-------------------Start button------------------- self.start_button=tk.Button(subframe,text=dgbk('开始'),\ command=self.start,state=tk.DISABLED) self.start_button.pack(side=tk.RIGHT, pady=8) #-------------------Help button------------------- self.help_button=tk.Button(subframe,text=dgbk('帮助'),\ command=self.showHelp) self.help_button.pack(side=tk.RIGHT, padx=8)
def _addUpperTemplate(self) : lblFrame = LabelFrame(self,text=" Documents ") lblFrame.grid(row=0,column=0,sticky="new",padx=15,pady=15,columnspan=2); frame = Frame(lblFrame); Label(frame,text="Limit Documents").grid(row=0,column=0,sticky="w",pady=5,padx=10); self.combo = ttk.Combobox(frame,values=["None"] + [i for i in range(1,20)] , state="readonly"); def chooseLim(event) : self.combo.config(state="disabled");self.docsLim=self.combo.get();print(self.docsLim); self.combo.bind("<<ComboboxSelected>>", chooseLim); self.combo.grid(row=0,column=1,sticky="w") self.combo.current(0) frame.grid(row=0,column=0,sticky="w") frame = Frame(lblFrame) xscrollbar = Scrollbar(frame , orient="horizontal") xscrollbar.grid(row=1, column=0, sticky="snew") yscrollbar = Scrollbar(frame) yscrollbar.grid(row=0, column=1, sticky="snew") self.text = Text(frame , height=10 , font=("Consolas",12) , wrap="none" , xscrollcommand=xscrollbar.set , yscrollcommand=yscrollbar.set) self.text.grid(row=0,column=0,sticky="snew") xscrollbar.config(command=self.text.xview) yscrollbar.config(command=self.text.yview) frame.grid(row=1,column=0,sticky="snew",padx=10,pady=(5,0)) self.fileChoose = Label(lblFrame,text="Import from a text file",font=("consolas",10),fg="blue",cursor="hand2"); self.fileChoose.grid(row=2,column=0,sticky="w",padx=10) self.fileChoose.bind("<Button-1>",lambda event : self._importText()); rightFrame = Frame(lblFrame); Button(rightFrame,text="Add as a Document",relief="groove",command=self._addDoc).grid(row=0,column=0,ipady=4,padx=(5,15),pady=2,sticky="we") Button(rightFrame,text="Remove all Documents",relief="groove",command=self._removeDocs).grid(row=1,column=0,ipady=4,padx=(5,15),pady=2,sticky="we") Button(rightFrame,text="Past a Document",relief="groove",command=self._pastDoc).grid(row=2,column=0,ipady=4,padx=(5,15),pady=2,sticky="we") Button(rightFrame,text="Show Documents",relief="groove",command=self._showDocs).grid(row=3,column=0,ipady=4,padx=(5,15),pady=2,sticky="we"); rightFrame.grid(row=1,column=1) frame2 = Frame(lblFrame); Label(frame2,text="Search Engine Mode").grid(row=0,column=0,sticky="w",pady=5,padx=10); self.combo2 = ttk.Combobox(frame2,values=["Boolean Retrival Model","Inverted Index Model","Vector Space Model"] , state="readonly"); self.combo2.grid(row=0,column=1,sticky="we",columnspan=2,padx=(10,10)) self.combo2.current(0) frame2.grid(row=3,column=0,sticky="snew",pady=15); frame2.columnconfigure(2,weight=1) frame.columnconfigure(0,weight=1); self.columnconfigure(0,weight=1); self.rowconfigure(0,weight=1); frame.rowconfigure(0,weight=1); lblFrame.rowconfigure(0,weight=4); lblFrame.columnconfigure(0,weight=1);
def fillInfo(self, curRow: int, path: Path, name: str = None) -> None: rowLbl = zerofrmt(curRow) bg = self.litBg if (curRow % 2) else self.defBg # create container frm = Frame(master=self.scrFrm, bg=bg, relief='sunken', bd=1) frm.columnconfigure(1, weight=1) frm.grid(column=0, row=curRow, sticky='ew') # create spinbox sbox = Spinbox(master=frm, width=3, bg=bg, format=(f'%0{rndto}d' if rndto > 1 else ''), takefocus=False, from_=1, to=self.lblRow, increment=-1, repeatdelay=(10**5), validate='key', validatecommand=self.checkValid) sbox.grid(column=0, row=0) def btnpress(f=frm, s=sbox): self.updateList(f, s, True) def commit(_, f=frm, s=sbox): self.updateList(f, s) def cancel(_, f=frm, s=sbox): self.cancelChange(f, s) sbox.configure(command=btnpress) sbox.delete(0, 'end') if name: sbox.insert(0, rowLbl) else: name = path.name sbox.bind('<Return>', commit) sbox.bind('<Escape>', cancel) # create name label lbl = Label(master=frm, text=name, bg=bg) lbl.grid(column=1, row=0, sticky='w') # save to data dict self.data[rowLbl] = dict(frm=frm, sbox=sbox, lbl=lbl, path=path, name=name)
def init_canvas(self): self.root = Tk() self.root.title("Painting using Ovals") # Grid mainframe = Frame(self.root) mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(0, weight=3) mainframe.rowconfigure(0, weight=2) mainframe.pack(pady=20, padx=20) # Selected song song_names = list(SONGS.keys()) self.selected_song = StringVar(self.root) self.selected_song.set(song_names[0]) # set the default option Label(mainframe, text="Choose a song").grid(row=1, column=1) song_menu = OptionMenu(mainframe, self.selected_song, *song_names) song_menu.grid(row=2, column=1) # Selected parameter parameter_names = list(PARAMETER_TO_COLOR.keys()) self.parameter = StringVar(self.root) self.parameter.set(parameter_names[0]) Label(mainframe, text="Select Parameter").grid(row=1, column=2) color_menu = OptionMenu(mainframe, self.parameter, *parameter_names) color_menu.grid(row=2, column=2) # Clear button clear_btn = Button(self.root, text="Clear", width=10, command=self.reset_canvas) clear_btn.pack() # Play button clear_btn = Button(self.root, text="Play", width=10, command=self.start_song) clear_btn.pack() # Canvas self.canvas_w = Canvas(self.root, width=CANVAS_WIDTH, height=CANVAS_HEIGHT, highlightbackground="black", bg="white") self.canvas_w.pack(expand=YES, fill=BOTH) # Message message = Label(self.root, text="Press and Drag the mouse to draw") message.pack(side=BOTTOM)
def addActionFrame(self): frame=Frame(self,relief=tk.RAISED,borderwidth=1) frame.pack(fill=tk.X,side=tk.TOP,\ expand=0,padx=8,pady=5) #label=tk.Label(frame,text='Actions:',bg='#bbb') #label.grid(row=0,column=0,sticky=tk.W,padx=8) #---------------Action checkbuttons--------------- frame.columnconfigure(0,weight=1) #---------------------2nd row--------------------- subframe=Frame(frame) subframe.grid(row=1,column=0,columnspan=6,sticky=tk.W+tk.E,\ pady=5) #-------------------Album options------------------- albumlabel=tk.Label(subframe,text=dgbk('专辑:'),\ bg='#bbb') albumlabel.pack(side=tk.LEFT, padx=8) self.album=tk.StringVar() self.albumnames=['All',] self.albummenu=Combobox(subframe,textvariable=\ self.album,values=self.albumnames,state='readonly') self.albummenu.current(0) self.albummenu.bind('<<ComboboxSelected>>',self.setAlbum) self.albummenu.pack(side=tk.LEFT,padx=8) #-------------------Quit button------------------- quit_button=tk.Button(subframe,text=dgbk('退出'),\ command=self.quit) quit_button.pack(side=tk.RIGHT,padx=8) #-------------------Stop button------------------- ''' self.stop_button=tk.Button(subframe,text='Stop',\ command=self.stop) self.stop_button.pack(side=tk.RIGHT,padx=8) ''' #-------------------Start button------------------- self.start_button=tk.Button(subframe,text=dgbk('开始'),\ command=self.start,state=tk.DISABLED) self.start_button.pack(side=tk.RIGHT,pady=8) #-------------------Help button------------------- self.help_button=tk.Button(subframe,text=dgbk('帮助'),\ command=self.showHelp) self.help_button.pack(side=tk.RIGHT,padx=8)
class TimedFrame(Component, ABC): def __init__(self, container, duration, on_expire=lambda timed_frame: None, get_data=None, on_change=lambda: None, update_interval=None, styles=None): super().__init__(container, get_data=get_data, on_change=on_change, update_interval=update_interval, styles=styles) self.started = datetime.now() self.duration = duration # Provide in milliseconds, as with update_interval self._on_expire = on_expire styles = {} if not styles else styles self.styles["progress_bar"] = styles.get("progress_bar", {}) self.styles["inner_frame"] = styles.get("inner_frame", {}) def _refresh_frame(self): def get_data__progress_bar(bar): elapsed = datetime.now() - self.started elapsed_proportion = min(1, (elapsed.total_seconds() * 1000) / self.duration) return elapsed_proportion self._frame__main = Frame(self._outer_frame, **self.styles["frame"]) progress_bar = ProgressBar(self._frame__main, get_data=get_data__progress_bar, on_change=lambda bar: self._on_expire(self), is_reversed=True, styles={ "height": 3, **self.styles["progress_bar"] }) progress_bar_frame = progress_bar.render() self._frame = Frame(self._frame__main, **self.styles["inner_frame"]) self._frame__main.rowconfigure(0, weight=1) self._frame__main.columnconfigure(0, weight=1) self._frame.bind( "<Configure>", lambda event: progress_bar_frame.configure( width=self._frame.winfo_reqwidth())) self._frame__main.grid(row=0, column=0, sticky="nswe") progress_bar_frame.grid(row=1, column=0, sticky="nswe") self._frame.grid(row=0, column=0, sticky="nswe")
def _init_game(self) -> None: # Make some game constants more easily accessible self.rows = self.game.board.rows self.columns = self.game.board.cols # # Main window # self._root = Tk() self._root.title("Othello") self._root.columnconfigure(0, weight=1) self._root.rowconfigure(2, weight=1) self._root.minsize(50 * self.columns + 100, 50 * self.rows + 100) # # Score Label # score_frame = Frame(self._root) self._score_label = ttk.Label(score_frame, background="white", foreground="black", text="TEMPORARY LABEL") #TODO: compute label text score_frame.grid(row=0, column=0, sticky="ew") self._score_label.grid(row=0, column=0, sticky="ew", padx=5, pady=5) score_frame.columnconfigure(0, weight=1) # # Info Label # info_frame = Frame(self._root) self._info_label = ttk.Label(info_frame, text="", background="white", foreground="black") info_frame.grid(row=1, column=0, sticky="ew") self._info_label.grid(row=0, column=0, sticky="ew", padx=5, pady=5) info_frame.columnconfigure(0, weight=1) # # Game content (Othello board) # self._content = Frame(self._root) self._content.grid(row=2, column=0, sticky="nsew") self.cells = [] for row in range(self.rows): for col in range(self.columns): self.cells.append(self._build_cell(row, col)) self._content.columnconfigure(col, weight=1) self._content.rowconfigure(row, weight=1)
def _build_cell(self, row: int, col: int) -> Frame: cell = Frame(self._content, borderwidth=5, relief=const.SUNKEN, height=50, width=50) cell._canvas = Canvas(master=cell, height=50, width=50) cell.row = row cell.col = col cell.bound = False cell.grid(row=row, column=col, sticky="nsew") cell.columnconfigure(0, weight=1) cell.rowconfigure(0, weight=1) cell._canvas.grid(row=0, column=0, sticky="nsew") return cell
def createConsoles(self, parent, nodes, width, title): "Create a grid of consoles in a frame." f = Frame(parent) # Create consoles consoles = [] index = 0 for node in nodes: console = Console(f, self.net, node, title=title) consoles.append(console) row = index / width column = index % width console.grid(row=row, column=column, sticky='nsew') index += 1 f.rowconfigure(row, weight=1) f.columnconfigure(column, weight=1) return f, consoles
def country_select(): # pop up for selecting a country root = tkinter.Tk() root.geometry("800x500+0+0") root.title("Choose a Country") # Add a grid mainframe = Frame(root) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) mainframe.pack(pady=100, padx=100) # Create a Tkinter variable tkvar = StringVar(root) # Dictionary with options choices = set(data['Country']) tkvar.set('Choose One') # set the default option # guven specification popupMenu = OptionMenu(mainframe, tkvar, *choices) Label(mainframe, text="You just need to select one Country from the dropdown", font=("Helvetica", 16)).grid(row=1, column=1) popupMenu.grid(row=2, column=1) # on change dropdown value def change_dropdown(*args): print(tkvar.get()) button = tkinter.Button(master=root, text=tkvar.get(), command=country_wise_graph(tkvar.get())) button.pack(side=tkinter.BOTTOM) _quit() # calling when value changes to anything tkvar.trace('w', change_dropdown) # definig function for quit def _quit(): root.quit() root.destroy() # quit button button = tkinter.Button(master=root, text="Quit", command=_quit, font=("Helvetica", 16)) button.pack(side=tkinter.BOTTOM) # root classifications root.mainloop()
def setup_purchaser(self): purchaser = LabelFrame( master=self.window, text="Purchaser", font=font.Font(size=14, weight=font.BOLD), ) master_frm = Frame(master=purchaser) label_texts = [ ["Name:", "Phone:"], ["Postal Code:", "Province:", "City:"], ["Delivery Address:"], ["Today's Date:"], ["Credit Card No.:", "for dept use, validation id:"], ] master_frm.columnconfigure(0, minsize=60, weight=0) master_frm.columnconfigure(1, weight=1) for i_row, text_list in enumerate(label_texts): text = text_list[0] lbl_head = Label(master=master_frm, text=text, font=self.font_style) lbl_head.grid(row=i_row, column=0, sticky=E, pady=5) frm = Frame(master=master_frm) ent_name = Entry(master=frm, font=self.font_style, width=15) if text == "Delivery Address:": ent_name.pack(fill=X) else: ent_name.pack(side=LEFT) for text in text_list[1:]: lbl = Label(master=frm, text=text, padx=10, font=self.font_style) lbl.pack(side=LEFT, anchor=E) ent_name = Entry(master=frm, font=self.font_style, width=15) ent_name.pack(side=LEFT) frm.grid(row=i_row, column=1, sticky=W + E, pady=5, padx=10) master_frm.pack(fill=BOTH, padx=10, pady=10) purchaser.pack(fill=BOTH, padx=20, pady=5)
def initialize_window(self): self.menubar.entryconfig('Korpus', state='normal') self.menubar.entryconfig('Generator', state='normal') self.settings_menu.entryconfig('Mutator', state='normal') project_frame = Frame(self.window) log_frame = Frame(self.window, relief=tk.SUNKEN) project_frame.grid(row=0, column=0, sticky=tk.N+tk.E+tk.S+tk.W) log_frame.grid(row=1, column=0, columnspan=5, sticky=tk.N+tk.E+tk.S+tk.W, padx=5, pady=5) log_frame.columnconfigure(0, weight=1) log_frame.rowconfigure(1, weight=1) self.initialize_project_frame(project_frame) self.initialize_log_frame(log_frame) devices_frame = Frame(self.window) devices_frame.columnconfigure(0, weight=1) devices_frame.rowconfigure(1, weight=1) self.initialize_devices_frame(devices_frame) devices_frame.grid(row=0, column=1, sticky=tk.N+tk.E+tk.S+tk.W, padx=10)
def __init__(self, runner): self.runner = runner self.messages = {} Screen.destroy() Screen.reinit() super().__init__() Screen.title("NaOH: PocketMine-MP Console") # GUI initialization fstframe = Frame(Screen.root) fstframe.grid(row=0, rowspan=1, columnspan=8) sndframe = Frame(Screen.root) sndframe.grid(row=0, rowspan=1, column=8, columnspan=2) self.scrollbar = Scrollbar(fstframe) self.listbox = Listbox(fstframe, yscrollcommand=self.scrollbar.set, width=120, height=25) self.listbox.grid(row=0, column=0, rowspan=1, columnspan=7, sticky='nswe') self.scrollbar.config(command=self.listbox.yview) self.scrollbar.grid(row=0, column=7, rowspan=1, sticky='nse') self.scrolllock = False Button(fstframe, text='나가기 (주의: 강제 종료됩니다)', command=self.runner.killAll).grid(row=1, column=0, sticky='nwse') self.slbutton = Button(fstframe, text='ScrollLock Off', command=self.togglesl) self.slbutton.grid(row=1, column=1, sticky='new') Label(fstframe, text='명령어: /', justify='right').grid(row=1, column=2) self.cmdentry = Entry(fstframe) self.cmdentry.bind('<Return>', self.put_cmd) self.cmdentry.grid(row=1, column=3, columnspan=5, sticky='nwe') fstframe.rowconfigure(1, weight=1) fstframe.columnconfigure(3, weight=1) fstframe.columnconfigure(4, weight=20) sndframe.rowconfigure(0, weight=1) Button(sndframe, text='서버 상태', command=lambda: statusScreen(self)).grid(row=0, sticky='n') Button(sndframe, text='설정 편집', command=lambda: propertiesScreen(self.runner.workdir + sep + 'server.properties')).grid(row=1, sticky='n') Button(sndframe, text='덤프 삭제', command=self.removeDumps).grid(row=2, sticky='n') self.cmdentry.focus() Screen.root.focus_force() # GUI initialization done self.thread = threading.Thread(target=lambda: asyncStream(self)).start() Screen.root.protocol("WM_DELETE_WINDOW", self.runner.killAll) Screen.root.mainloop() try: Screen.root.destroy() except: self.runner.killAll()
def train(app, parent): frame = Frame(parent) name_tag = Label(frame, text=name) def update_command(v): setattr(app.bot_config, upgrade_attr_name, option_value_to_num(v)) write_bot_config(app.bot_config, app.device.serial.replace(':', "_")) upgrade_label = Label(frame, text='Upgrade Lv.') upgrade_variable = StringVar() upgrade_variable.set(num_to_option_value(getattr(app.bot_config, upgrade_attr_name))) upgrade_option = OptionMenu( frame, upgrade_variable, *lv_upgrade_options, command=update_command ) def train_command(v): setattr(app.bot_config, train_attr_name, option_value_to_num(v)) write_bot_config(app.bot_config, app.device.serial.replace(':', "_")) train_label = Label(frame, text='Training Lv.') train_variable = StringVar() train_variable.set(num_to_option_value(getattr(app.bot_config, train_attr_name))) train_option = OptionMenu( frame, train_variable, *lv_training_options, command=train_command ) name_tag.config(width=8, anchor=N + W, justify=LEFT) upgrade_option.config(width=8) train_option.config(width=8) frame.columnconfigure(0, weight=5) name_tag.grid(row=0, column=0) train_label.grid(row=0, column=2) train_option.grid(row=0, column=3) upgrade_label.grid(row=0, column=4) upgrade_option.grid(row=0, column=5) return frame, None
def generic_func(parent: tk.Frame, values: List[Tuple[str, tk.StringVar]], conf: Property): """Generically make a set of labels.""" for row, (timer, var) in enumerate(values): if timer == 'inf': timer_disp = INF else: timer_disp = timer parent.columnconfigure(1, weight=1) label = ttk.Label(parent, text=timer_disp + ':') label.grid(row=row, column=0) widget = widget_func( parent, var, conf, ) widget.grid(row=row, column=1, sticky='ew')
def create_bottom_buttons(root): """ 创建发送按钮和重置按钮 :param root: 编辑编辑区 :return: 发送按钮和清空按钮 """ bottom_buttons = Frame(root) send_packet_button = Button(bottom_buttons, width=20, text="发送") default_packet_button = Button(bottom_buttons, width=20, text="默认值") reset_button = Button(bottom_buttons, width=20, text="重置") bottom_buttons.pack(side=BOTTOM, fill=X, padx=5, pady=5) send_packet_button.grid(row=0, column=0, padx=5, pady=5) default_packet_button.grid(row=0, column=1, padx=2, pady=5) reset_button.grid(row=0, column=2, padx=5, pady=5) bottom_buttons.columnconfigure(0, weight=1) bottom_buttons.columnconfigure(1, weight=1) bottom_buttons.columnconfigure(2, weight=1) return send_packet_button, reset_button, default_packet_button
def task_display_frame(self): width = self.windows_size[0] - 20 height = 210 frame = Frame(self, width=width, height=height) frame.grid_propagate(False) frame.columnconfigure(0, weight=width) frame.rowconfigure(0, weight=5) frame.rowconfigure(1, weight=5) frame.rowconfigure(2, weight=height - 20) dl = Label(frame, text=self.device.serial, width=width, height=5, bg='white') title = Label(frame, text="Task: None", width=width, height=5) text = Text(frame, width=width, height=height - 30) title.config(bg='white', anchor=W, justify=LEFT) dl.grid(row=0, column=0, pady=(10, 0), sticky=N + W) title.grid(row=1, column=0, pady=10, sticky=N + W) text.grid(row=2, column=0, sticky=N + W) return frame, title, text
def draw_table(self): # clear the canvas of past tables self.tablecanvas.delete("all") # create the frame to hold the table frame = Frame(self.tablecanvas) frame.rowconfigure(0, weight=1) frame.columnconfigure(0, weight=1) # PACE HOLDER FOR REAL TABLE GENERATION for i in range(25): Button(frame, text=i).grid(row=i, column=i) # make the window that holds the frame self.tablecanvas.create_window(0, 0, window=frame, anchor=N + W) frame.update_idletasks() # update the scrollable area to the new width self.tablecanvas.config(scrollregion=self.tablecanvas.bbox("all"))
def __init__(self, game, stats=DEFAULT_STATS, buttons=DEFAULT_BUTTONS_CONTINUE): self.action = None self.root = root = Tk() root.title("Iä! Shub-Niggurath! The Black Goat of the Woods with a Thousand Young!") root.protocol("WM_DELETE_WINDOW", self.close) root.pack_propagate(True) self.grid_canvas = Canvas(root, bd=5, relief=tkinter.SUNKEN) self.grid_canvas.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT) button_frame = Frame(root) button_frame.pack(fill=tkinter.BOTH, side=tkinter.LEFT) stat_frame = Frame(button_frame, bd=1) stat_frame.pack(fill=tkinter.BOTH) stat_frame.columnconfigure(1, weight=1) self.stat_textboxes = stat_textboxes = [] for row, (text, callback) in enumerate(stats): label = Label(stat_frame, text=text + ":", anchor="e") label.grid(row=row, column=0, sticky="wens") textbox = Label(stat_frame, bd=1, relief=tkinter.SUNKEN) textbox.callback = callback # for our own use. textbox.grid(row=row, column=1, sticky="wens") stat_textboxes.append(textbox) for name, bindings, action in buttons: def callback(event, action=action): if self.action is not None: log.error("Action already set: %r when processing %r", self.action, action) self.action = action root.quit() text = name + (" ({})".format(bindings) if bindings else "") button = Button(button_frame, text=text, command=lambda: callback(None)) button.pack() for it in bindings.split(): root.bind(it, callback) if game is not None: self.update(game)
def __init__(self, title, message, detail): Toplevel.__init__(self) self.details_expanded = False self.title(title) self.geometry('380x95') self.minsize(380, 95) self.maxsize(425, 250) self.rowconfigure(0, weight=0) self.rowconfigure(1, weight=1) self.columnconfigure(0, weight=1) button_frame = Frame(self) button_frame.grid(row=0, column=0, sticky='nsew') button_frame.columnconfigure(0, weight=1) button_frame.columnconfigure(1, weight=1) text_frame = Frame(self) text_frame.grid(row=1, column=0, padx=(7, 7), pady=(7, 7), sticky='nsew') text_frame.rowconfigure(0, weight=1) text_frame.columnconfigure(0, weight=1) ttk.Label(button_frame, text=message).grid(row=0, column=0, columnspan=2, pady=(7, 7)) ttk.Button(button_frame, text='OK', command=self.destroy).grid(row=1, column=0, sticky='e') ttk.Button(button_frame, text='Details', command=self.toggle_details).grid(row=1, column=1, sticky='w') self.textbox = Text(text_frame, height=6) self.textbox.insert('1.0', detail) self.textbox.config(state='disabled') self.scrollb = Scrollbar(text_frame, command=self.textbox.yview) self.textbox.config(yscrollcommand=self.scrollb.set)
def __init__(self, master, on_game_end): self.table = {} self.active_player = 'X' self.current_turn = 1 self.turn_string = StringVar(value=f'Ход {self.current_turn}') self.is_game_finished = False self.on_game_end = on_game_end super().__init__(master) # Чтобы фрейм мог расширяться, необходимо настроить сетку на его # контейнере master.rowconfigure(0, weight=1) master.columnconfigure(0, weight=1) top_bar = Frame(self, height=50, width=100) self.timer = Timer(top_bar) for i in range(3): top_bar.columnconfigure(i, weight=1) board = Frame(self) for i in range(3): board.rowconfigure(i, weight=1) board.columnconfigure(0, weight=1) board.columnconfigure(1, weight=2) board.columnconfigure(2, weight=2) board.columnconfigure(3, weight=2) board.columnconfigure(4, weight=1) buttons = [] for i in range(3): buttons_list = [] for j in range(3): self.table[f'cell{i}-{j}'] = StringVar(value='') button = Button(board, textvariable=self.table[f'cell{i}-{j}'], command=lambda arg1=i, arg2=j: self. __handle_turn(arg1, arg2)) buttons_list.append(button) buttons.append(buttons_list) turn_counter = Label( top_bar, textvariable=self.turn_string ) # текст в лейбле можно соеденить со значением переменной(прочитать) # Параметр sticky дает возможность виджету занимать доступное место в # ячейке, расщиряясь за свои границы top_bar.grid(row=0, column=0, columnspan=5, sticky="nsew") board.grid(row=1, column=0, columnspan=5, rowspan=3, sticky="nsew") for i in range(3): for j in range(3): buttons[i][j].grid(row=i, column=j + 1, sticky='nsew') turn_counter.grid(row=0, column=2, sticky="we") self.timer.grid(row=0, column=1, sticky='we')
def addPathFrame(self): frame=Frame(self) frame.pack(fill=tk.X,expand=0,side=tk.TOP,padx=8,pady=5) frame.columnconfigure(1,weight=1) #------------------Database file------------------ label=tk.Label(frame,text='Mendeley Data file:',\ bg='#bbb') label.grid(row=0,column=0,\ sticky=tk.W,padx=8) self.db_entry=tk.Entry(frame) self.db_entry.grid(row=0,column=1,sticky=tk.W+tk.E,padx=8) self.db_button=tk.Button(frame,text='Open',command=self.openFile) self.db_button.grid(row=0,column=2,padx=8,sticky=tk.E) hint=''' Default location on Linux: ~/.local/share/data/Mendeley\ Ltd./Mendeley\ Desktop/[email protected] Default location on Windows: C:\Users\Your_name\AppData\Local\Mendeley Ltd\Mendeley Desktop\[email protected]''' hint_label=tk.Label(frame,text=hint,\ justify=tk.LEFT,anchor=tk.NW) hint_label.grid(row=1,column=0,columnspan=3,\ sticky=tk.W,padx=8) #--------------------Output dir-------------------- label2=tk.Label(frame,text='Output folder:',\ bg='#bbb') label2.grid(row=2,column=0,\ sticky=tk.W,padx=8) self.out_entry=tk.Entry(frame) self.out_entry.grid(row=2,column=1,sticky=tk.W+tk.E,padx=8) self.out_button=tk.Button(frame,text='Choose',command=self.openDir) self.out_button.grid(row=2,column=2,padx=8,sticky=tk.E)
def showPlotTools(self): f2= Frame(self.selectPlotFrame, relief=FLAT,bg='#FADC46') f2.grid(row=1,column=0,sticky=N+S+E+W,padx=10,pady =10) b1 = Button(f2,text='3D K',relief=RAISED,command= lambda:self.plotButtonPressed(1)) b1.grid(row=0, column=0,sticky=N+S+E+W,padx=5,pady =5) b2 = Button(f2,text='3D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(2)) b2.grid(row=0, column=1,sticky=N+S+E+W,padx=5,pady =5) b3 = Button(f2,text='3D DP',relief=RAISED,command=lambda:self.plotButtonPressed(3)) b3.grid(row=0, column=2,sticky=N+S+E+W,padx=5,pady =5) b4 = Button(f2,text='2D K',relief=RAISED,command=lambda:self.plotButtonPressed(4)) b4.grid(row=1, column=0,sticky=N+S+E+W,padx=5,pady =5) b5 = Button(f2,text='2D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(5)) b5.grid(row=1, column=1,sticky=N+S+E+W,padx=5,pady =5) b6 = Button(f2,text='2D DP',relief=RAISED,command=lambda:self.plotButtonPressed(6)) b6.grid(row=1, column=2,sticky=N+S+E+W,padx=5,pady =5) b1.config(state=EguanaModel().machine.plot3DKButtonState) b2.config(state=EguanaModel().machine.plot3DDstButtonState) b3.config(state=EguanaModel().machine.plot3DDpButtonState) b4.config(state=EguanaModel().machine.plot2DKButtonState) b5.config(state=EguanaModel().machine.plot2DDstButtonState) b6.config(state=EguanaModel().machine.plot2DDpButtonState) f2.columnconfigure(0, weight=1) f2.columnconfigure(1, weight=1) f2.columnconfigure(2, weight=1) f2.rowconfigure(0, weight=1) f2.rowconfigure(1, weight=1)
def BuildMainFrame(self): from tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry from tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED menu = Menu(self.master,activeborderwidth=0,bd=0) self.master.config(menu=menu) filemenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0) menu.add_cascade(label="File", underline=0, menu=filemenu) filemenu.add_command(label="New", accelerator='Ctrl+N',command=self.NewCommand) filemenu.add_command(label="Open...",accelerator='Ctrl+O', command=self.OpenCommand) filemenu.add_command(label="Save as...",accelerator='Ctrl+S', command=self.SaveCommand) filemenu.add_separator() filemenu.add_command(label="Quit",accelerator='Ctrl+Q', command=self.QuitCommand) self.log_on = IntVar() self.log_on.set(1) self.output_to_file = StringVar() self.output_to_file.set('n') scriptmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0) modulenames = ['vmtkscripts'] for modulename in modulenames: scriptsubmenu = self.BuildScriptMenu(menu,modulename) if scriptsubmenu: scriptmenu.add_cascade(label=modulename,menu=scriptsubmenu) editmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0) menu.add_cascade(label="Edit",underline=0, menu=editmenu) editmenu.add_cascade(label="Insert script",menu=scriptmenu) editmenu.add_command(label="Insert file name", accelerator='Ctrl+F',command=self.InsertFileName) editmenu.add_separator() editmenu.add_command(label="Clear input", command=self.ClearInputCommand) editmenu.add_command(label="Clear output", command=self.ClearOutputCommand) editmenu.add_command(label="Clear all", command=self.ClearAllCommand) editmenu.add_separator() editmenu.add_checkbutton(label="Log", variable=self.log_on) editmenu.add_separator() editmenu.add_radiobutton(label="No output to file", variable=self.output_to_file,value='n') editmenu.add_radiobutton(label="Write output to file", variable=self.output_to_file,value='w') editmenu.add_radiobutton(label="Append output to file", variable=self.output_to_file,value='a') editmenu.add_command(label="Output file...", command=self.OutputFileCommand) runmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0) menu.add_cascade(label="Run", underline=0, menu=runmenu) runmenu.add_command(label="Run all", command=self.RunAllCommand) runmenu.add_command(label="Run current line", command=self.RunLineCommand) runmenu.add_command(label="Run selection", command=self.RunSelectionCommand) helpmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0) menu.add_cascade(label="Help", underline=0, menu=helpmenu) helpmenu.add_command(label="Help", underline=0, accelerator='F1',command=self.ShowHelpCommand) helpmenu.add_command(label="About", underline=0, command=self.AboutCommand) self.master.bind("<Control-KeyPress-q>", self.QuitHandler) self.master.bind("<Control-KeyPress-n>", self.NewHandler) self.master.bind("<Control-KeyPress-o>", self.OpenHandler) self.master.bind("<Control-KeyPress-s>", self.SaveHandler) self.master.bind("<Control-KeyPress-f>", self.InsertFileNameHandler) self.master.bind("<KeyPress-F1>", self.ShowHelpHandler) self.master.bind("<KeyPress>", self.KeyPressHandler) self.wordIndex = ['1.0','1.0'] self.suggestionswindow = Toplevel(bg='#ffffff',bd=0,height=50,width=600,highlightthickness=0,takefocus=True) self.suggestionswindow.overrideredirect(1) self.suggestionslist = Listbox(self.suggestionswindow,bg='#ffffff',bd=1,fg='#336699',activestyle='none',highlightthickness=0,height=9) self.suggestionslist.insert(END,"foo") self.suggestionslist.pack(side=TOP,fill=X) self.suggestionswindow.bind("<KeyPress>", self.TopKeyPressHandler) self.suggestionswindow.withdraw() self.master.rowconfigure(0,weight=1) self.master.columnconfigure(0,weight=1) content = Frame(self.master,bd=0,padx=2,pady=2) content.grid(row=0,column=0,sticky=N+S+W+E) content.rowconfigure(0,weight=1,minsize=50) content.rowconfigure(1,weight=0) content.columnconfigure(0,weight=1) panes = PanedWindow(content,orient=VERTICAL,bd=1,sashwidth=8,sashpad=0,sashrelief=RAISED,showhandle=True) panes.grid(row=0,column=0,sticky=N+S+W+E) frame1 = Frame(panes,bd=0) frame1.grid(row=0,column=0,sticky=N+S+W+E) frame1.columnconfigure(0,weight=1) frame1.columnconfigure(1,weight=0) frame1.rowconfigure(0,weight=1) panes.add(frame1,height=300,minsize=20) frame2 = Frame(panes,bd=0) frame2.grid(row=1,column=0,sticky=N+S+W+E) frame2.columnconfigure(0,weight=1) frame2.columnconfigure(1,weight=0) frame2.rowconfigure(0,weight=1) panes.add(frame2,minsize=20) self.text_input = Text(frame1, bg='#ffffff',bd=1,highlightthickness=0) self.text_input.bind("<KeyPress>", self.KeyPressHandler) self.text_input.bind("<Button-3>", self.PopupHandler) self.text_input.bind("<Control-Return>", self.RunKeyboardHandler) self.input_scrollbar = Scrollbar(frame1,orient=VERTICAL,command=self.text_input.yview) self.text_input["yscrollcommand"] = self.input_scrollbar.set self.text_output = Text(frame2,state=DISABLED,bd=1,bg='#ffffff',highlightthickness=0) self.output_scrollbar = Scrollbar(frame2,orient=VERTICAL,command=self.text_output.yview) self.text_output["yscrollcommand"] = self.output_scrollbar.set self.text_entry = Entry(content,bd=1,bg='#ffffff',state=DISABLED,highlightthickness=0) self.text_input.focus_set() self.text_input.grid(row=0,column=0,sticky=N+S+W+E) self.input_scrollbar.grid(row=0,column=1,sticky=N+S+W+E) self.text_output.grid(row=0,column=0,sticky=N+S+W+E) self.output_scrollbar.grid(row=0,column=1,sticky=N+S+W+E) self.text_entry.grid(row=1,column=0,sticky=N+S+W+E) self.popupmenu = Menu(self.text_input, tearoff=1, bd=0) self.popupmenu.add_command(label="Context help", command=self.ShowHelpCommand) self.popupmenu.add_cascade(label="Insert script",menu=scriptmenu) self.popupmenu.add_command(label="Insert file name...", command=self.InsertFileName) self.popupmenu.add_separator() self.popupmenu.add_command(label="Run all", command=self.RunAllCommand) self.popupmenu.add_command(label="Run current line", command=self.RunLineCommand) self.popupmenu.add_command(label="Run selection", command=self.RunSelectionCommand) self.output_stream = TkPadOutputStream(self.text_output) self.input_stream = TkPadInputStream(self.text_entry,self.output_stream)
def __init__(self): """ Methode speciale initialisant une nouvelle fenêtre de jeu Ultimate Tic-Tac-Toe. """ super().__init__() # Nom de la fenêtre. self.title("Ultimate Tic-Tac-Toe") # La partie de ultimate Tic-Tac-Toe self.partie = Partie() # Un ditionnaire contenant les 9 canvas des 9 plateaux du jeu self.canvas_uplateau = {} # Création de deux joueurs. self.JoueursDuJeux() Popup() # Création des frames et des canvas du jeu for i in range(0, 3): for j in range(0, 3): cadre = Frame(self, borderwidth=5, relief=GROOVE, background = '#e1e1e1') cadre.grid(row=i, column=j, padx=5, pady=5) cadre.columnconfigure(0, weight=1) cadre.rowconfigure(0, weight=1) cadre.columnconfigure(1, weight=1) cadre.rowconfigure(1, weight=1) cadre.columnconfigure(2, weight=1) cadre.rowconfigure(2, weight=1) #cadre.columnconfigure(j, weight=1) #cadre.rowconfigure(i, weight=1) #Dessiner le cadre en jaune si la sourie entre dans le cadre cadre.bind('<Enter>', self.entrer_frame) cadre.bind('<Leave>', self.sortir_frame) self.canvas_uplateau[i, j] = CanvasPlateau(cadre, self.partie.uplateau[i, j]) self.canvas_uplateau[i, j].grid() # On lie un clic sur le Canvas à une méthode. self.canvas_uplateau[i, j].bind('<Button-1>', self.selectionner) #Pour redimensionner automatiquement la fenêtre principale self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(1, weight=1) self.grid_rowconfigure(1, weight=1) self.grid_columnconfigure(2, weight=1) self.grid_rowconfigure(2, weight=1) # Ajout d'une étiquette d'information. self.messages = Label(self) self.messages.grid(column=0, row=4, columnspan=3) # Ajout d'une étiquette pour le nom des joueurs. self.labNoms = Label(self) self.labNoms.grid(column=0, row=5) # Ajout d'une étiquette pour la date et le chronometre. self.labDate = Label(self) self.labDate.grid(column=0, row=6) # Les bouttons en dessous B1 = Button(self, text='Règles', width=15, command=self.regles).grid(row=7,column=0) B2 = Button(self, text='Nouvelle Partie', width=15, command=self.nouvellePartie).grid(row=7, column=1) B3 = Button(self, text='Statistiques', width=15, command=self.statistiques).grid(row=7, column=2) B4 = Button(self, text='Historique', width=15, command=self.regles).grid(row=8, column=1) B5 = Button(self, text='Quitter', width=5, command=self.quitter).grid(row=8, column=2) B5 = Button(self, text='Tout recommencer', width=15, command=self.regles).grid(row=8, column=0)
class FilePickEdit(Frame): def __init__(self, master, file_mask, default_file, edit_height = None, user_onChange = None, rename_on_edit=0, font = None, coloring=True, allowNone=False, highlighter=None, directory='.'): """ file_mask: file mask (e.g. "*.foo") or list of file masks (e.g. ["*.foo", "*.abl"]) """ self.master = master self.directory = directory self.user_onChange = user_onChange Frame.__init__(self, master) row = 0 self.unmodified = True self.allowNone = allowNone self.file_extension = "" if type(file_mask) != list: file_mask = [file_mask] if "." in file_mask[0]: self.file_extension = file_mask[0][file_mask[0].rfind('.'):] # read filenames self.file_mask = file_mask self.updateList() # filename frame self.list_frame = Frame(self) self.list_frame.grid(row=row, column=0, sticky="WE") self.list_frame.columnconfigure(0, weight=1) # create list self.picked_name = StringVar() self.makelist() # refresh button self.refresh_button = Button(self.list_frame, text='<- refresh', command=self.refresh, height=1) self.refresh_button.grid(row=0, column=1, sticky='E') # save button self.save_button = Button(self.list_frame, text="save", command=self.save, height=1) self.save_button.grid(row=0, column=2, sticky="E") # editor row += 1 if coloring: self.editor = SyntaxHighlightingText(self, self.onEdit, highlighter=highlighter) else: self.editor = ScrolledText2(self, self.onEdit) if font is not None: self.editor.configure(font=font) if edit_height is not None: self.editor.configure(height=edit_height) self.editor.grid(row=row, column=0, sticky="NEWS") self.rowconfigure(row, weight=1) self.columnconfigure(0, weight=1) # option to change filename on edit row += 1 self.options_frame = Frame(self) self.options_frame.grid(row=row, column=0, sticky=W) self.rename_on_edit = IntVar() self.cb = Checkbutton(self.options_frame, text="rename on edit", variable=self.rename_on_edit) self.cb.pack(side=LEFT) self.cb.configure(command=self.onChangeRename) self.rename_on_edit.set(rename_on_edit) # filename frame row += 1 self.filename_frame = Frame(self) self.filename_frame.grid(row=row, column=0, sticky="WE") self.filename_frame.columnconfigure(0, weight=1) # save as filename self.save_name = StringVar() self.save_edit = Entry(self.filename_frame, textvariable = self.save_name) self.save_edit.grid(row=0, column=0, sticky="WE") self.save_name.trace("w", self.onSaveChange) # pick default if applicableButton self.select(default_file) self.row = row def setDirectory(self, directory, keep=False): self.directory = directory self.updateList() self.makelist() # menu = self.list["menu"] scrolledlist # menu = self.list.listbox#["scrolledlist"] # menu.delete(0, 'end') # add the new ones # for filename in self.files: # menu.add_command(label=filename, command=_setit(self.picked_name, filename, None)) # if keep is true, only the files list will be updated but the content of the # text area will not be altered/removed if not keep: self.select("") def refresh(self): sel = self.get() self.updateList() self.select(sel, notify=False) def reloadFile(self): self.editor.delete("1.0", END) filename = self.picked_name.get() if os.path.exists(os.path.join(self.directory, filename)): new_text = open(os.path.join(self.directory, filename)).read() if new_text.strip() == "": new_text = "// %s is empty\n" % filename new_text = new_text.replace("\r", "") else: new_text = "" self.editor.insert(INSERT, new_text) def setText(self, txt): """ Replaces the text in the edit field as by typing into it. """ self.select("") if txt.strip() == "": txt = "// empty database\n" self.editor.insert(INSERT, txt) self.onEdit() def onSelChange(self): self.reloadFile() filename = self.picked_name.get() self.save_name.set(filename) self.save_edit.configure(state=DISABLED) self.unmodified = True if self.user_onChange is not None: self.user_onChange(filename) def onSaveChange(self, name, index, mode): pass def autoRename(self): # modify "save as" name filename = self.picked_name.get() if filename == "": filename = "new" + self.file_extension # if no file selected, create new filename ext = "" extpos = filename.rfind(".") if extpos != -1: ext = filename[extpos:] base = filename[:extpos] hpos = base.rfind("-") num = 0 if hpos != -1: try: num = int(base[hpos+1:]) base = base[:hpos] except: pass while True: num += 1 filename = "%s-%d%s" % (base, num, ext) if not os.path.exists(filename): break self.save_name.set(filename) # user callback if self.user_onChange is not None: self.user_onChange(filename) def onEdit(self): if self.unmodified: self.unmodified = False # do auto rename if it's enabled or there is no file selected (editing new file) if self.rename_on_edit.get() == 1 or self.picked_name.get() == "": self.autoRename() # enable editing of save as name self.save_edit.configure(state=NORMAL) def onChangeRename(self): # called when clicking on "rename on edit" checkbox if self.rename_on_edit.get() == 1: if (not self.unmodified) and self.save_name.get() == self.picked_name.get(): self.autoRename() else: self.save_name.set(self.picked_name.get()) def updateList(self): self.files = [] if self.allowNone: self.files.append("") if os.path.exists(self.directory): for filename in os.listdir(self.directory): for fm in self.file_mask: if fnmatch(filename, fm): self.files.append(filename) self.files.sort() if len(self.files) == 0 and not self.allowNone: self.files.append("(no %s files found)" % str(self.file_mask)) def select(self, filename, notify=True): """ selects the item given by filename """ if filename in self.files: if not havePMW: self.picked_name.set(filename) else: self.list.selectitem(self.files.index(filename)) if notify: self.onSelChange(filename) else: self.editor.delete("1.0", END) def makelist(self): if havePMW: self.list = ComboBox(self.list_frame, selectioncommand = self.onSelChange, scrolledlist_items = self.files, ) self.list.grid(row=0, column=0, padx=0, pady=0, sticky="NEWS") self.list.component('entryfield').component('entry').configure(state = 'readonly', relief = 'raised') self.picked_name = self.list else: self.list = OptionMenu(*(self.list_frame, self.picked_name) + tuple(self.files)) self.list.grid(row=0, column=0, sticky="NEW") self.picked_name.trace("w", self.onSelChange) def save(self): self.get() def set(self, selected_item): self.select(selected_item) def get(self): """ gets the name of the currently selected file, saving it first if necessary """ filename = self.save_name.get() if self.unmodified == False: self.unmodified = True # save the file f = open(os.path.join(self.directory, filename), "w") f.write(self.editor.get("1.0", END).encode('utf-8')) f.close() # add it to the list of files # if not filename in self.files: # self.files.append(filename) # self.files.sort() # self.list.destroy() # self.makelist() # set it as the new pick #if havePMW: # self.picked_name.selectitem(self.files.index(filename), 1) #else: # self.picked_name.set(filename) # self.select(filename) self.refresh() self.select(filename, notify=False) self.save_edit.configure(state=DISABLED) return filename def get_text(self): return self.editor.get("1.0", END) def get_filename(self): return self.save_name.get() def set_enabled(self, state): self.editor.configure(state=state) if havePMW: self.list.component('entryfield_entry').configure(state=state) # self.list.component('arrowbutton').configure(state=state) self.list.component('arrowbutton').bind('<1>', (lambda a: 'break') if state==DISABLED else self.list._postList) else: self.list.configure(state=state) self.save_button.configure(state=state) self.cb.configure(state=state) self.save_edit.configure(state=state)
class OthelloGUI: n = 1 def __init__(self): self._configure_game() self._init_game() self.refresh_board() def _configure_game(self) -> None: config = ConfigureGUI() config.start() self.game = config.getOthello() def _init_game(self) -> None: # Make some game constants more easily accessible self.rows = self.game.board.rows self.columns = self.game.board.cols # # Main window # self._root = Tk() self._root.title("Othello") self._root.columnconfigure(0, weight=1) self._root.rowconfigure(2, weight=1) self._root.minsize(50 * self.columns + 100, 50 * self.rows + 100) # # Score Label # score_frame = Frame(self._root) self._score_label = ttk.Label(score_frame, background="white", foreground="black", text="TEMPORARY LABEL") #TODO: compute label text score_frame.grid(row=0, column=0, sticky="ew") self._score_label.grid(row=0, column=0, sticky="ew", padx=5, pady=5) score_frame.columnconfigure(0, weight=1) # # Info Label # info_frame = Frame(self._root) self._info_label = ttk.Label(info_frame, text="", background="white", foreground="black") info_frame.grid(row=1, column=0, sticky="ew") self._info_label.grid(row=0, column=0, sticky="ew", padx=5, pady=5) info_frame.columnconfigure(0, weight=1) # # Game content (Othello board) # self._content = Frame(self._root) self._content.grid(row=2, column=0, sticky="nsew") self.cells = [] for row in range(self.rows): for col in range(self.columns): self.cells.append(self._build_cell(row, col)) self._content.columnconfigure(col, weight=1) self._content.rowconfigure(row, weight=1) def _build_cell(self, row: int, col: int) -> Frame: cell = Frame(self._content, borderwidth=5, relief=const.SUNKEN, height=50, width=50) cell._canvas = Canvas(master=cell, height=50, width=50) cell.row = row cell.col = col cell.bound = False cell.grid(row=row, column=col, sticky="nsew") cell.columnconfigure(0, weight=1) cell.rowconfigure(0, weight=1) cell._canvas.grid(row=0, column=0, sticky="nsew") return cell def refresh_board(self) -> None: self.draw_board() self._score_label["text"] = "I update when things happen. n = %d" % self.n self.n = self.n + 1 def draw_board(self) -> None: for cell in self.cells: p = Point(cell.col, cell.row) board_piece = self.game.board.piece_at(p) if(Piece.is_playable_piece(board_piece)): self.draw_piece(cell, board_piece) if cell.bound: cell._canvas.unbind("<ButtonPress-1>", None) else: cell._canvas.bind("<ButtonPress-1>", self.click_empty) cell.bound = True def draw_piece(self, cell: Frame, piece: Piece) -> None: cell._canvas.delete(const.ALL) if(piece == Piece.WHITE): cell._canvas.create_oval(10, 10, 50, 50, fill="light grey") elif(piece == Piece.BLACK): cell._canvas.create_oval(10, 10, 50, 50, fill="black") def click_empty(self, event) -> None: row = event.widget.master.row col = event.widget.master.col try: self.game.make_move(row + 1, col + 1) except InvalidMoveException as e: # TODO: # make this print the handled exception's message so we can get rid of # this hard coded string and make it so the error message only has to # be changed in one place self._info_label["foreground"] = ["red", "orange", "yellow", "green", "blue", "purple"][randint(0,5)] self._info_label["text"] = str(e) self.refresh_board() def start(self) -> None: self._root.mainloop()
class OptimizerMainWindow: """ classdocs """ # TODO: change that name def reactToClick(self, event): a = AddRestrictionDialog(self) def __init__(self, optimizer): # always have a reference to model/controller self.optimizer = optimizer # setup main GUI and make stretchable self.guiRoot = Tk() self.guiRoot.title("OPTIMIZR") self.guiRoot.columnconfigure(1, weight=1) self.guiRoot.rowconfigure(0, weight=1) # left (settings) and right (sequences) part self.frameLeft = Frame(self.guiRoot) self.frameLeft.grid(row=0, column=0, sticky=W + E + N + S) self.frameLeft.columnconfigure(0, weight=1) self.frameRight = Frame(self.guiRoot) self.frameRight.grid(row=0, column=1, sticky=W + E + N + S) self.frameRight.columnconfigure(0, weight=1) self.frameRight.rowconfigure(0, weight=1) self.frameRight.rowconfigure(1, weight=1) self.frameSpeciesControll = LabelFrame(self.frameLeft, text="Species", pady=10, padx=10) self.frameSpeciesControll.columnconfigure(1, weight=1) self.frameOptimizationControll = LabelFrame(self.frameLeft, text="Optimization", pady=10, padx=10) self.frameRestrictionControll = LabelFrame(self.frameLeft, text="Restriction Enzymes", pady=10, padx=10) self.frameSpeciesControll.grid(row=0, column=0, sticky=W + E, padx=10, pady=10) self.frameOptimizationControll.grid(row=1, column=0, sticky=W + E, padx=10, pady=10) self.frameRestrictionControll.grid(row=2, column=0, sticky=W + E, padx=10, pady=10) # Species Controll Label(self.frameSpeciesControll, text="Source:").grid(row=0, column=0) Label(self.frameSpeciesControll, text="Target:").grid(row=1, column=0) self.comboSourceSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboSourceSpecies.grid(row=0, column=1, pady=5, sticky="ew") self.comboTargetSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboTargetSpecies.grid(row=1, column=1, pady=5, sticky="we") self.buttonSpeciesList = Button(self.frameSpeciesControll, text="Edit Species List") self.buttonSpeciesList.grid(row=2, column=1, pady=5, sticky="e") self.comboSourceSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) self.comboTargetSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Optimization Controll Label(self.frameOptimizationControll, text="Optimization Strategy:").grid(row=0, column=0) self.comboOptimizationStrategy = Combobox(self.frameOptimizationControll, state="readonly") self.comboOptimizationStrategy.grid(row=0, column=1) self.comboOptimizationStrategy["values"] = self.optimizer.possibleOptimizationStrategies self.comboOptimizationStrategy.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Restriction Enzymes self.listRestriction = Listbox(self.frameRestrictionControll) self.listRestriction.grid(row=0, column=0, columnspan=3, pady=5, sticky=W + E) self.frameRestrictionControll.columnconfigure(0, weight=1) self.buttonRestricionAdd = Button(self.frameRestrictionControll, text=" + ") self.buttonRestricionDel = Button(self.frameRestrictionControll, text=" - ") self.buttonRestricionAdd.grid(row=1, column=1, padx=5) self.buttonRestricionDel.grid(row=1, column=2, padx=5) # Source Sequence Frame self.frameSourceSequence = LabelFrame(self.frameRight, text="Source Sequence", padx=10, pady=10) self.frameResultSequence = LabelFrame(self.frameRight, text="Result Sequence", padx=10, pady=10) self.frameSourceSequence.grid(row=0, column=0, sticky="wens", padx=10, pady=10) self.frameResultSequence.grid(row=1, column=0, sticky="wens", padx=10, pady=10) self.buttonSourceLoad = Button(self.frameSourceSequence, text=" Load ") self.textSourceSeq = ScrolledText(self.frameSourceSequence, height=10) self.buttonSourceLoad.grid(row=0, column=1, sticky="e", pady=5) self.textSourceSeq.grid(row=1, column=0, columnspan=2, sticky="wens") self.frameSourceSequence.columnconfigure(0, weight=1) self.frameSourceSequence.rowconfigure(1, weight=1) self.textSourceSeq.frame.columnconfigure(1, weight=1) self.textSourceSeq.frame.rowconfigure(0, weight=1) self.buttonOptimize = Button(self.frameResultSequence, text=" OPTIMIZE! ") self.buttonOptimize.bind("<ButtonRelease>", self.actionOptimize) self.buttonRemoveRestriction = Button(self.frameResultSequence, text=" RESTRICTION-B-GONE! ") self.buttonRemoveRestriction.bind("<ButtonRelease>", self.actionRemoveRestricion) self.buttonSaveResult = Button(self.frameResultSequence, text=" Save ") self.textResultSequence = ScrolledText(self.frameResultSequence, height=10) self.buttonOptimize.grid(column=0, row=0, pady=5, sticky="w") self.buttonRemoveRestriction.grid(column=1, row=0, pady=5, padx=10, sticky="w") self.textResultSequence.grid(row=1, column=0, columnspan=4, sticky="wens") self.buttonSaveResult.grid(row=2, column=3, pady=5, sticky="e") self.frameResultSequence.columnconfigure(2, weight=1) self.frameResultSequence.rowconfigure(1, weight=1) self.textResultSequence.frame.columnconfigure(1, weight=1) self.textResultSequence.frame.rowconfigure(0, weight=1) self.textSourceSeq.bind("<<Modified>>", self.actionSequenceModified) self.textResultSequence.bind("<<Modified>>", self.actionSequenceModified) # generate color tags for textboxes for i in range(101): # green for normal codons (r, g, b) = colorsys.hsv_to_rgb(210 / 360, i / 100, 1.0) colorHex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255)) self.textSourceSeq.tag_config("normal" + str(i), background=colorHex) self.textResultSequence.tag_config("normal" + str(i), background=colorHex) # red for codons with restriction sites (r, g, b) = colorsys.hsv_to_rgb(5 / 360, i / 100, 1.0) colorHex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255)) self.textSourceSeq.tag_config("restrict" + str(i), background=colorHex) self.textResultSequence.tag_config("restrict" + str(i), background=colorHex) # Set (minimum + max) Window size self.guiRoot.update() self.guiRoot.minsize(self.guiRoot.winfo_width(), self.guiRoot.winfo_height()) self.buttonRestricionAdd.bind("<ButtonRelease>", self.reactToClick) self.buttonRestricionDel.bind("<ButtonRelease>", self.actionRestrictionEnzymeDelete) self.buttonSpeciesList.bind("<ButtonRelease>", self.actionEditSpeciesButton) self.buttonSourceLoad.bind("<ButtonRelease>", self.actionLoadSequence) self.buttonSaveResult.bind("<ButtonRelease>", self.actionSaveSequence) # TEST # self.listRestriction.insert("end", "EcoRI") # self.listRestriction.insert("end", "BamHI") # # dummy event to manually trigger update self.guiRoot.bind("<<Update>>", self.actionUpdate) self.actionUpdate(None) self.guiRoot.mainloop() def actionRestrictionEnzymeDelete(self, event): try: selectedEnzyme = self.listRestriction.selection_get() self.optimizer.restrictionEnzymeList.remove(selectedEnzyme) self.guiRoot.event_generate("<<Update>>") except tkinter.TclError: # no selection pass def actionUpdate(self, event): # print("update called") # clear list of restriction enzymes self.listRestriction.delete(0, "end") for r in self.optimizer.restrictionEnzymeList: self.listRestriction.insert("end", r) self.comboSourceSpecies.delete(0, "end") self.comboTargetSpecies.delete(0, "end") speciesValues = list() for (taxid, name) in self.optimizer.speciesList: speciesValues.append(taxid + ": " + name) self.comboSourceSpecies["values"] = speciesValues self.comboTargetSpecies["values"] = speciesValues if self.comboSourceSpecies.get() not in speciesValues: self.comboSourceSpecies.set("") if self.comboTargetSpecies.get() not in speciesValues: self.comboTargetSpecies.set("") self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) self.optimizer.saveConfig("config.ini") def actionEditSpeciesButton(self, event): speciesListDialog = SpeciesListDialog(self) def actionOptimizerSettingsChanged(self, event=None): # print("Something happened") strategy = self.comboOptimizationStrategy.get() sourceString = self.comboSourceSpecies.get() targetString = self.comboTargetSpecies.get() if not (strategy and sourceString and targetString): return sourceTaxid = sourceString.split(":")[0] targetTaxid = targetString.split(":")[0] self.optimizer.setOptimizer(sourceTaxid, targetTaxid, strategy) self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) # self.optimizer.testPrint() def actionOptimize(self, event=None): self.optimizer.runOptimization() self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) def actionRemoveRestricion(self, event=None): self.optimizer.runRestricionRemoval() self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) def actionSequenceModified(self, event=None): # necessary if, otherwise -> infinite loop if self.textSourceSeq.edit_modified(): seq = self.textSourceSeq.get("1.0", "end").strip() seq = stripCharsNotInList(seq.upper(), ["A", "C", "G", "T"]) self.optimizer.setSourceSeq(seq) oldInsert = self.textSourceSeq.index("insert") self.textSourceSeq.delete("1.0", "end") sourceCodons = self.optimizer.getCodonsForPrint(True) if not sourceCodons: self.textSourceSeq.insert("end", self.optimizer.sourceSequence) else: for (co, sc, r) in sourceCodons: if sc: if not r: self.textSourceSeq.insert("end", co, "normal" + str(int(sc * 100))) # print("normal"+str(int(sc*100))) else: self.textSourceSeq.insert("end", co, "restrict" + str(int(sc * 100))) else: # remainder without color self.textSourceSeq.insert("end", co) self.textSourceSeq.mark_set("insert", oldInsert) # reset the modified status at the very end self.textSourceSeq.edit_modified(False) if self.textResultSequence.edit_modified(): seq = self.textResultSequence.get("1.0", "end").strip() # self.optimizer.setOptimizedSeq(seq) oldInsert = self.textResultSequence.index("insert") self.textResultSequence.delete("1.0", "end") targetCodons = self.optimizer.getCodonsForPrint(False) if not targetCodons: self.textSourceSeq.insert("end", self.optimizer.optimizedSequence) else: for (co, sc, r) in targetCodons: if sc: if not r: self.textResultSequence.insert("end", co, "normal" + str(int(sc * 100))) # print("normal"+str(int(sc*100))) else: self.textResultSequence.insert("end", co, "restrict" + str(int(sc * 100))) else: # remainder without color self.textResultSequence.insert("end", co) self.textSourceSeq.mark_set("insert", oldInsert) self.textResultSequence.edit_modified(False) def actionLoadSequence(self, event=None): filename = tkinter.filedialog.askopenfilename() if filename: seq = sequenceIO.readFile(filename) self.textSourceSeq.delete("1.0", "end") self.textSourceSeq.insert("end", seq) self.textSourceSeq.edit_modified(True) def actionSaveSequence(self, event=None): filename = tkinter.filedialog.asksaveasfilename() if filename: # print("file is " + filename) with open(filename, mode="w") as fd: fd.write(self.optimizer.optimizedSequence)
class MLNQueryGUI(object): def __init__(self, master, gconf, directory=None): self.master = master self.initialized = False self.master.bind('<Return>', self.infer) self.master.bind('<Escape>', lambda a: self.master.quit()) self.master.protocol('WM_DELETE_WINDOW', self.quit) self.dir = os.path.abspath(ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd()))) self.frame = Frame(master) self.frame.pack(fill=BOTH, expand=1) self.frame.columnconfigure(1, weight=1) row = 0 # pracmln project options Label(self.frame, text='PRACMLN Project: ').grid(row=row, column=0, sticky='ES') project_container = Frame(self.frame) project_container.grid(row=row, column=1, sticky="NEWS") # new proj file self.btn_newproj = Button(project_container, text='New Project...', command=self.new_project) self.btn_newproj.grid(row=0, column=1, sticky="WS") # open proj file self.btn_openproj = Button(project_container, text='Open Project...', command=self.ask_load_project) self.btn_openproj.grid(row=0, column=2, sticky="WS") # save proj file self.btn_updateproj = Button(project_container, text='Save Project...', command=self.noask_save_project) self.btn_updateproj.grid(row=0, column=3, sticky="WS") # save proj file as... self.btn_saveproj = Button(project_container, text='Save Project as...', command=self.ask_save_project) self.btn_saveproj.grid(row=0, column=4, sticky="WS") # grammar selection row += 1 Label(self.frame, text='Grammar: ').grid(row=row, column=0, sticky='E') grammars = ['StandardGrammar', 'PRACGrammar'] self.selected_grammar = StringVar() self.selected_grammar.trace('w', self.settings_setdirty) l = OptionMenu(*(self.frame, self.selected_grammar) + tuple(grammars)) l.grid(row=row, column=1, sticky='NWE') # logic selection row += 1 Label(self.frame, text='Logic: ').grid(row=row, column=0, sticky='E') logics = ['FirstOrderLogic', 'FuzzyLogic'] self.selected_logic = StringVar() self.selected_logic.trace('w', self.settings_setdirty) l = OptionMenu(*(self.frame, self.selected_logic) + tuple(logics)) l.grid(row=row, column=1, sticky='NWE') # mln section row += 1 Label(self.frame, text="MLN: ").grid(row=row, column=0, sticky='NE') self.mln_container = FileEditBar(self.frame, directory=self.dir, filesettings={'extension': '.mln', 'ftypes': [('MLN files', '.mln')]}, defaultname='*unknown{}', importhook=self.import_mln, deletehook=self.delete_mln, projecthook=self.save_proj, filecontenthook=self.mlnfilecontent, fileslisthook=self.mlnfiles, updatehook=self.update_mln, onchangehook=self.project_setdirty) self.mln_container.editor.bind("<FocusIn>", self._got_focus) self.mln_container.grid(row=row, column=1, sticky="NEWS") self.mln_container.columnconfigure(1, weight=2) self.frame.rowconfigure(row, weight=1) row += 1 self.use_emln = IntVar() self.use_emln.set(0) self.cb_use_emln = Checkbutton(self.frame, text="use model extension", variable=self.use_emln, command=self.onchange_use_emln) self.cb_use_emln.grid(row=row, column=1, sticky="W") # mln extension section row += 1 self.emlncontainerrow = row self.emln_label = Label(self.frame, text="EMLN: ") self.emln_label.grid(row=self.emlncontainerrow, column=0, sticky='NE') self.emln_container = FileEditBar(self.frame, directory=self.dir, filesettings={'extension': '.emln', 'ftypes': [('MLN extension files','.emln')]}, defaultname='*unknown{}', importhook=self.import_emln, deletehook=self.delete_emln, projecthook=self.save_proj, filecontenthook=self.emlnfilecontent, fileslisthook=self.emlnfiles, updatehook=self.update_emln, onchangehook=self.project_setdirty) self.emln_container.grid(row=self.emlncontainerrow, column=1, sticky="NEWS") self.emln_container.editor.bind("<FocusIn>", self._got_focus) self.emln_container.columnconfigure(1, weight=2) self.onchange_use_emln(dirty=False) self.frame.rowconfigure(row, weight=1) # db section row += 1 Label(self.frame, text="Evidence: ").grid(row=row, column=0, sticky='NE') self.db_container = FileEditBar(self.frame, directory=self.dir, filesettings={'extension': '.db', 'ftypes': [('Database files', '.db')]}, defaultname='*unknown{}', importhook=self.import_db, deletehook=self.delete_db, projecthook=self.save_proj, filecontenthook=self.dbfilecontent, fileslisthook=self.dbfiles, updatehook=self.update_db, onchangehook=self.project_setdirty) self.db_container.grid(row=row, column=1, sticky="NEWS") self.db_container.editor.bind("<FocusIn>", self._got_focus) self.db_container.columnconfigure(1, weight=2) self.frame.rowconfigure(row, weight=1) # inference method selection row += 1 self.list_methods_row = row Label(self.frame, text="Method: ").grid(row=row, column=0, sticky=E) self.selected_method = StringVar() self.selected_method.trace('w', self.select_method) methodnames = sorted(InferenceMethods.names()) self.list_methods = OptionMenu(*(self.frame, self.selected_method) + tuple(methodnames)) self.list_methods.grid(row=self.list_methods_row, column=1, sticky="NWE") # options row += 1 option_container = Frame(self.frame) option_container.grid(row=row, column=1, sticky="NEWS") # Multiprocessing self.multicore = IntVar() self.cb_multicore = Checkbutton(option_container, text="Use all CPUs", variable=self.multicore, command=self.settings_setdirty) self.cb_multicore.grid(row=0, column=2, sticky=W) # profiling self.profile = IntVar() self.cb_profile = Checkbutton(option_container, text='Use Profiler', variable=self.profile, command=self.settings_setdirty) self.cb_profile.grid(row=0, column=3, sticky=W) # verbose self.verbose = IntVar() self.cb_verbose = Checkbutton(option_container, text='verbose', variable=self.verbose, command=self.settings_setdirty) self.cb_verbose.grid(row=0, column=4, sticky=W) # options self.ignore_unknown_preds = IntVar() self.cb_ignore_unknown_preds = Checkbutton(option_container, text='ignore unkown predicates', variable=self.ignore_unknown_preds, command=self.settings_setdirty) self.cb_ignore_unknown_preds.grid(row=0, column=5, sticky="W") # queries row += 1 Label(self.frame, text="Queries: ").grid(row=row, column=0, sticky=E) self.query = StringVar() self.query.trace('w', self.settings_setdirty) Entry(self.frame, textvariable=self.query).grid(row=row, column=1, sticky="NEW") # additional parameters row += 1 Label(self.frame, text="Add. params: ").grid(row=row, column=0, sticky="NE") self.params = StringVar() self.params.trace('w', self.settings_setdirty) self.entry_params = Entry(self.frame, textvariable=self.params) self.entry_params.grid(row=row, column=1, sticky="NEW") # closed-world predicates row += 1 Label(self.frame, text="CW preds: ").grid(row=row, column=0, sticky="E") cw_container = Frame(self.frame) cw_container.grid(row=row, column=1, sticky='NEWS') cw_container.columnconfigure(0, weight=1) self.cwPreds = StringVar() self.cwPreds.trace('w', self.settings_setdirty) self.entry_cw = Entry(cw_container, textvariable=self.cwPreds) self.entry_cw.grid(row=0, column=0, sticky="NEWS") self.closed_world = IntVar() self.cb_closed_world = Checkbutton(cw_container, text="CW Assumption", variable=self.closed_world, command=self.onchange_cw) self.cb_closed_world.grid(row=0, column=1, sticky='W') # output filename row += 1 output_cont = Frame(self.frame) output_cont.grid(row=row, column=1, sticky='NEWS') output_cont.columnconfigure(0, weight=1) # - filename Label(self.frame, text="Output: ").grid(row=row, column=0, sticky="NE") self.output_filename = StringVar() self.entry_output_filename = Entry(output_cont, textvariable=self.output_filename) self.entry_output_filename.grid(row=0, column=0, sticky="NEW") # - save option self.save = IntVar() self.cb_save = Checkbutton(output_cont, text="save", variable=self.save) self.cb_save.grid(row=0, column=1, sticky=W) # start button row += 1 start_button = Button(self.frame, text=">> Start Inference <<", command=self.infer) start_button.grid(row=row, column=1, sticky="NEW") self.settings_dirty = IntVar() self.project_dirty = IntVar() self.gconf = gconf self.project = None self.project_dir = os.path.abspath(ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd()))) if gconf['prev_query_project': self.project_dir] is not None: self.load_project(os.path.join(self.project_dir, gconf['prev_query_project':self.project_dir])) else: self.new_project() self.config = self.project.queryconf self.project.addlistener(self.project_setdirty) self.mln_container.dirty = False self.emln_container.dirty = False self.db_container.dirty = False self.project_setdirty(dirty=False) self.master.geometry(gconf['window_loc_query']) self.initialized = True def _got_focus(self, *_): if self.master.focus_get() == self.mln_container.editor: if not self.project.mlns and not self.mln_container.file_buffer: self.mln_container.new_file() elif self.master.focus_get() == self.db_container.editor: if not self.project.dbs and not self.db_container.file_buffer: self.db_container.new_file() elif self.master.focus_get() == self.emln_container.editor: if not self.project.emlns and not self.emln_container.file_buffer: self.emln_container.new_file() def quit(self): if self.settings_dirty.get() or self.project_dirty.get(): savechanges = messagebox.askyesnocancel("Save changes", "You have unsaved project changes. Do you want to save them before quitting?") if savechanges is None: return elif savechanges: self.noask_save_project() self.master.destroy() else: # write gui settings and destroy self.write_gconfig() self.master.destroy() ####################### PROJECT FUNCTIONS ################################# def new_project(self): self.project = MLNProject() self.project.addlistener(self.project_setdirty) self.project.name = DEFAULTNAME.format('.pracmln') self.reset_gui() self.set_config(self.project.queryconf) self.mln_container.update_file_choices() self.emln_container.update_file_choices() self.db_container.update_file_choices() self.project_setdirty(dirty=True) def project_setdirty(self, dirty=False, *args): self.project_dirty.set(dirty or self.mln_container.dirty or self.db_container.dirty or self.emln_container.dirty) self.changewindowtitle() def settings_setdirty(self, *args): self.settings_dirty.set(1) self.changewindowtitle() def changewindowtitle(self): title = (WINDOWTITLEEDITED if (self.settings_dirty.get() or self.project_dirty.get()) else WINDOWTITLE).format(self.project_dir, self.project.name) self.master.title(title) def ask_load_project(self): filename = askopenfilename(initialdir=self.dir, filetypes=[('PRACMLN project files', '.pracmln')], defaultextension=".pracmln") if filename and os.path.exists(filename): self.load_project(filename) else: logger.info('No file selected.') return def load_project(self, filename): if filename and os.path.exists(filename): projdir, _ = ntpath.split(filename) self.dir = os.path.abspath(projdir) self.project_dir = os.path.abspath(projdir) self.project = MLNProject.open(filename) self.project.addlistener(self.project_setdirty) self.reset_gui() self.set_config(self.project.queryconf.config) self.mln_container.update_file_choices() self.db_container.update_file_choices() if len(self.project.mlns) > 0: self.mln_container.selected_file.set(self.project.queryconf['mln'] or list(self.project.mlns.keys())[0]) self.mln_container.dirty = False if len(self.project.emlns) > 0: self.emln_container.selected_file.set(self.project.queryconf['emln'] or list(self.project.emlns.keys())[0]) self.emln_container.dirty = False if len(self.project.dbs) > 0: self.db_container.selected_file.set(self.project.queryconf['db'] or list(self.project.dbs.keys())[0]) self.db_container.dirty = False self.write_gconfig(savegeometry=False) self.settings_dirty.set(0) self.project_setdirty(dirty=False) self.changewindowtitle() else: logger.error('File {} does not exist. Creating new project...'.format(filename)) self.new_project() def noask_save_project(self): if self.project.name and not self.project.name == DEFAULTNAME.format('.pracmln'): self.save_project(os.path.join(self.project_dir, self.project.name)) else: self.ask_save_project() def ask_save_project(self): fullfilename = asksaveasfilename(initialdir=self.project_dir, confirmoverwrite=True, filetypes=[('PRACMLN project files','.pracmln')], defaultextension=".pracmln") self.save_project(fullfilename) def save_project(self, fullfilename): if fullfilename: fpath, fname = ntpath.split(fullfilename) fname = fname.split('.')[0] self.project.name = fname self.dir = os.path.abspath(fpath) self.project_dir = os.path.abspath(fpath) self.mln_container.save_all_files() self.emln_container.save_all_files() self.db_container.save_all_files() self.update_config() self.project.save(dirpath=self.project_dir) self.write_gconfig() self.load_project(fullfilename) self.settings_dirty.set(0) def save_proj(self): self.project.save(dirpath=self.project_dir) self.write_gconfig() self.project_setdirty(dirty=False) ####################### MLN FUNCTIONS ##################################### def import_mln(self, name, content): self.project.add_mln(name, content) def delete_mln(self, fname): if fname in self.project.mlns: self.project.rm_mln(fname) fnamestr = fname.strip('*') if fnamestr in self.project.mlns: self.project.rm_mln(fnamestr) def update_mln(self, old=None, new=None, content=None, askoverwrite=True): if old is None: old = self.mln_container.selected_file.get() if new is None: new = self.mln_container.selected_file.get().strip('*') if content is None: content = self.mln_container.editor.get("1.0", END).strip() if old == new and askoverwrite: savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new)) if savechanges: self.project.mlns[old] = content else: logger.error('no name specified!') return -1 elif old == new and not askoverwrite: self.project.mlns[old] = content else: if new in self.project.mlns: if askoverwrite: savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new)) if savechanges: self.project.mlns[new] = content else: logger.error('no name specified!') return -1 else: self.project.mlns[new] = content return 1 def mlnfiles(self): return list(self.project.mlns.keys()) def mlnfilecontent(self, filename): return self.project.mlns.get(filename, '').strip() # /MLN FUNCTIONS ##################################### ####################### EMLN FUNCTIONS ##################################### def import_emln(self, name, content): self.project.add_emln(name, content) def delete_emln(self, fname): if fname in self.project.emlns: self.project.rm_emln(fname) fnamestr = fname.strip('*') if fnamestr in self.project.emlns: self.project.rm_emln(fnamestr) def update_emln(self, old=None, new=None, content=None, askoverwrite=True): if old is None: old = self.emln_container.selected_file.get() if new is None: new = self.emln_container.selected_file.get().strip('*') if content is None: content = self.emln_container.editor.get("1.0", END).strip() if old == new and askoverwrite: savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new)) if savechanges: self.project.emlns[old] = content else: logger.error('no name specified!') return -1 elif old == new and not askoverwrite: self.project.emlns[old] = content else: if new in self.project.emlns: if askoverwrite: savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new)) if savechanges: self.project.emlns[new] = content else: logger.error('no name specified!') return -1 else: self.project.emlns[new] = content return 1 def emlnfiles(self): return list(self.project.emlns.keys()) def emlnfilecontent(self, filename): return self.project.emlns.get(filename, '').strip() # /EMLN FUNCTIONS ##################################### # DB FUNCTIONS ##################################### def import_db(self, name, content): self.project.add_db(name, content) def delete_db(self, fname): if fname in self.project.dbs: self.project.rm_db(fname) fnamestr = fname.strip('*') if fnamestr in self.project.dbs: self.project.rm_db(fnamestr) def update_db(self, old=None, new=None, content=None, askoverwrite=True): if old is None: old = self.db_container.selected_file.get() if new is None: new = self.db_container.selected_file.get().strip('*') if content is None: content = self.db_container.editor.get("1.0", END).strip() if old == new and askoverwrite: savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new)) if savechanges: self.project.dbs[old] = content else: logger.error('no name specified!') return -1 elif old == new and not askoverwrite: self.project.dbs[old] = content else: if new in self.project.dbs: if askoverwrite: savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new)) if savechanges: self.project.dbs[new] = content else: logger.error('no name specified!') return -1 else: self.project.dbs[new] = content return 1 def dbfiles(self): return list(self.project.dbs.keys()) def dbfilecontent(self, filename): return self.project.dbs.get(filename, '').strip() # /DB FUNCTIONS ##################################### # GENERAL FUNCTIONS ################################# def select_method(self, *args): self.set_outputfilename() self.settings_setdirty() def onchange_use_emln(self, dirty=True, *args): if not self.use_emln.get(): self.emln_label.grid_forget() self.emln_container.grid_forget() else: self.emln_label.grid(row=self.emlncontainerrow, column=0, sticky="NE") self.emln_container.grid(row=self.emlncontainerrow, column=1, sticky="NWES") if dirty: self.settings_setdirty() def onchange_cw(self, *args): if self.closed_world.get(): self.entry_cw.configure(state=DISABLED) else: self.entry_cw.configure(state=NORMAL) self.settings_setdirty() def reset_gui(self): self.set_config({}) self.db_container.clear() self.emln_container.clear() self.mln_container.clear() def set_config(self, newconf): self.config = newconf self.selected_grammar.set(ifnone(newconf.get('grammar'), 'PRACGrammar')) self.selected_logic.set(ifnone(newconf.get('logic'), 'FirstOrderLogic')) self.mln_container.selected_file.set(ifnone(newconf.get('mln'), '')) if self.use_emln.get(): self.emln_container.selected_file.set(ifnone(newconf.get('mln'), '')) self.db_container.selected_file.set(ifnone(newconf.get('db'), "")) self.selected_method.set(ifnone(newconf.get("method"), InferenceMethods.name('MCSAT'), transform=InferenceMethods.name)) self.multicore.set(ifnone(newconf.get('multicore'), 0)) self.profile.set(ifnone(newconf.get('profile'), 0)) self.params.set(ifnone(newconf.get('params'), '')) self.use_emln.set(ifnone(newconf.get('use_emln'), 0)) self.verbose.set(ifnone(newconf.get('verbose'), 1)) self.ignore_unknown_preds.set(ifnone(newconf.get('ignore_unknown_preds'), 0)) self.output_filename.set(ifnone(newconf.get('output_filename'), '')) self.cwPreds.set(ifnone(newconf.get('cw_preds'), '')) self.closed_world.set(ifnone(newconf.get('cw'), 0)) self.save.set(ifnone(newconf.get('save'), 0)) self.query.set(ifnone(newconf.get('queries'), '')) self.onchange_cw() def set_outputfilename(self): if not hasattr(self, "output_filename") or not hasattr(self, "db_filename") or not hasattr(self, "mln_filename"): return mln = self.mln_container.selected_file.get() db = self.db_container.selected_file.get() if "" in (mln, db): return if self.selected_method.get(): method = InferenceMethods.clazz(self.selected_method.get()) methodid = InferenceMethods.id(method) filename = config.query_output_filename(mln, methodid, db) self.output_filename.set(filename) def update_config(self): self.config = PRACMLNConfig() self.config["use_emln"] = self.use_emln.get() self.config['mln'] = self.mln_container.selected_file.get().strip().lstrip('*') self.config['emln'] = self.emln_container.selected_file.get().strip().lstrip('*') self.config["db"] = self.db_container.selected_file.get().strip().lstrip('*') self.config["method"] = InferenceMethods.id(self.selected_method.get().strip()) self.config["params"] = self.params.get().strip() self.config["queries"] = self.query.get() self.config["output_filename"] = self.output_filename.get().strip() self.config["cw"] = self.closed_world.get() self.config["cw_preds"] = self.cwPreds.get() self.config['profile'] = self.profile.get() self.config['logic'] = self.selected_logic.get() self.config['grammar'] = self.selected_grammar.get() self.config['multicore'] = self.multicore.get() self.config['save'] = self.save.get() self.config['ignore_unknown_preds'] = self.ignore_unknown_preds.get() self.config['verbose'] = self.verbose.get() self.config['window_loc'] = self.master.winfo_geometry() self.config['dir'] = self.dir self.project.queryconf = PRACMLNConfig() self.project.queryconf.update(self.config.config.copy()) def write_gconfig(self, savegeometry=True): self.gconf['prev_query_path'] = self.dir self.gconf['prev_query_project': self.dir] = self.project.name # save geometry if savegeometry: self.gconf['window_loc_query'] = self.master.geometry() self.gconf.dump() def infer(self, savegeometry=True, options={}, *args): mln_content = self.mln_container.editor.get("1.0", END).strip() db_content = self.db_container.editor.get("1.0", END).strip() # create conf from current gui settings self.update_config() # write gui settings self.write_gconfig(savegeometry=savegeometry) # hide gui self.master.withdraw() try: print((headline('PRACMLN QUERY TOOL'))) print() if options.get('mlnarg') is not None: mlnobj = MLN(mlnfile=os.path.abspath(options.get('mlnarg')), logic=self.config.get('logic', 'FirstOrderLogic'), grammar=self.config.get('grammar', 'PRACGrammar')) else: mlnobj = parse_mln(mln_content, searchpaths=[self.dir], projectpath=os.path.join(self.dir, self.project.name), logic=self.config.get('logic', 'FirstOrderLogic'), grammar=self.config.get('grammar', 'PRACGrammar')) if options.get('emlnarg') is not None: emln_content = mlnpath(options.get('emlnarg')).content else: emln_content = self.emln_container.editor.get("1.0", END).strip() if options.get('dbarg') is not None: dbobj = Database.load(mlnobj, dbfiles=[options.get('dbarg')], ignore_unknown_preds=self.config.get('ignore_unknown_preds', True)) else: out(self.config.get('ignore_unknown_preds', True)) dbobj = parse_db(mlnobj, db_content, ignore_unknown_preds=self.config.get('ignore_unknown_preds', True)) if options.get('queryarg') is not None: self.config["queries"] = options.get('queryarg') infer = MLNQuery(config=self.config, mln=mlnobj, db=dbobj, emln=emln_content) result = infer.run() # write to file if run from commandline, otherwise save result to project results if options.get('outputfile') is not None: output = io.StringIO() result.write(output) with open(os.path.abspath(options.get('outputfile')), 'w') as f: f.write(output.getvalue()) logger.info('saved result to {}'.format(os.path.abspath(options.get('outputfile')))) elif self.save.get(): output = io.StringIO() result.write(output) fname = self.output_filename.get() self.project.add_result(fname, output.getvalue()) self.project.save(dirpath=self.dir) logger.info('saved result to file results/{} in project {}'.format(fname, self.project.name)) else: logger.debug('No output file given - results have not been saved.') except: traceback.print_exc() # restore main window sys.stdout.flush() self.master.deiconify()
class SpeciesSearchDialog: def __init__(self, parent, caller): # main window self.parent = parent # dialog that called this second dialog self.caller = caller self.gui = Toplevel(parent.guiRoot) self.gui.grab_set() self.gui.focus() self.gui.columnconfigure(0, weight=1) self.gui.rowconfigure(1, weight=1) self.entrySearch = Entry(self.gui) self.buttonSearch = Button(self.gui, text=" Search ") self.buttonAdd = Button(self.gui, text=" Add Species ") self.buttonClose = Button(self.gui, text=" Close Window ") self.frameResults = Frame(self.gui) self.frameResults.columnconfigure(0, weight=1) self.frameResults.rowconfigure(0, weight=1) self.scrollResults = Scrollbar(self.frameResults, orient="vertical") self.scrollResults.grid(row=0, column=1, sticky="ns") self.listResults = Listbox(self.frameResults, width=70, height=20) self.listResults.grid(row=0, column=0, sticky="nswe") self.listResults.config(yscrollcommand=self.scrollResults.set) self.scrollResults.config(command=self.listResults.yview) self.entrySearch.grid(row=0, column=0, columnspan=2, sticky="we", padx=5, pady=5) self.frameResults.grid(row=1, column=0, columnspan=3, sticky="nswe", padx=5, pady=5) self.buttonSearch.grid(row=0, column=2, padx=5, pady=5, sticky="e") self.buttonAdd.grid(row=2, column=1, padx=5, pady=5, sticky="e") self.buttonClose.grid(row=2, column=2, padx=5, pady=5, sticky="e") self.gui.protocol("WM_DELETE_WINDOW", self.actionClose) self.buttonClose.bind("<ButtonRelease>", self.actionClose) self.buttonAdd.bind("<ButtonRelease>", self.actionAdd) self.buttonSearch.bind("<ButtonRelease>", self.actionSearch) self.entrySearch.bind("<Return>", self.actionSearch) self.gui.update() self.gui.minsize(self.gui.winfo_width(), self.gui.winfo_height()) self.gui.mainloop() def actionAdd(self, event): try: selection = self.listResults.selection_get() selectionSplit = selection.split(":\t", 1) selectionSplit2 = selectionSplit[1].split("\t") if not (selectionSplit[0], selectionSplit2[0]) in self.parent.optimizer.speciesList: self.parent.optimizer.speciesList.append((selectionSplit[0], selectionSplit2[0].strip())) self.caller.gui.event_generate("<<Update>>") except tkinter.TclError: # no selection pass def actionSearch(self, event): query = self.entrySearch.get() if query: self.listResults.delete(0, "end") results = self.parent.optimizer.SPSUMHandler.search(query) # sort results by nr of CDS results = sorted(results.items(), reverse=True, key=lambda x: (int(x[1][1]))) for name, (taxid, ncs) in results: self.listResults.insert("end", taxid + ":\t " + name + " \t(" + ncs + " CDS)") def actionClose(self, event=None): self.caller.gui.event_generate("<<Update>>", when="tail") self.gui.destroy()
def makeMain(root, fields, calcs, exists=False, **opts): """ Populates main window. Args: root(tkinter object): main window titles(array): Titles of rows to populate. Used to determine button functions too. calcs(array): Titles of calculations to perform. Used to determine button functionality. exists(boolean): If a workspace exists already, load from there. Default = False. opts(dictionary): Stores options for filename and directory selection buttons. Returns: Populated main window. TO DO: Make the workspace loadable. And improve documentation/flow. """ entries = [] row = 0 dirOpt = opts['dirOpts'] fileOpt = opts['fileOpts'] # initialize array for stringVariables StrVar = [] #add menu bar to window __makeMenuBar(root) #create a Frame to hold the widgets frame = Frame(root) frame.pack(expand=True, fill=BOTH) frame.columnconfigure(1, weight=1) #create a Frame to hold the calculate buttons frame2 = Frame(root) frame2.pack(expand=True, fill=BOTH) frame2.columnconfigure(0, weight=1) for field in fields: # initialize textVariable for the entry StrVar.insert(row, StringVar('')) lab = Label(frame, text=field) ent = Entry(frame, textvariable=StrVar[row]) lab.grid(row=row, column=0, sticky=W) ent.grid(row = row, column = 1, sticky=W+E) if "Directory" in field: btn = Button(frame, text = 'Select the directory', command = lambda row=row : __dir2Ent(StrVar[row], **dirOpt)) fileOpt['initialdir'] = btn else: btn = Button(frame, text = 'Select the file', command = lambda row=row : __filename_2_ent(StrVar[row], **fileOpt)) btn.grid(row = row, column = 3, sticky = E) entries.append((field, ent, btn)) row += 1 if row == len(fields): for calc in calcs: runBtn = Button(frame2, text = "Calculate " + calc, command = lambda field=calc : calculate(StrVar, field)) runBtn.pack(side = LEFT, padx = 2) ws = WorkSpace(StrVar, opts) ws.save()
def createWidgets(self): panel = Frame(self, name="mainMenu") panel.grid(sticky=W) Button(panel, name="quit", text="Выход", command=self.__quit__).grid(row=0, column=0) Button(panel, name="reconnect", text="Пересоединение", command=self.control.reconnect).grid(row=0, column=1) b = Button(panel, text="Загрузить", command=self.loadSettings) b.grid(row=0, column=2) self.disabledWhileRunning.append(b) b = Button(panel, text="Сохранить", command=self.saveSettings) b.grid(row=0, column=3) self.disabledWhileRunning.append(b) panel = LabelFrame(self, text="Прямое управление стаканом", name="motor") panel.grid(sticky=W) b = Button(panel, text="Вверх", command=self.__up__, name="up") b.grid(row=0, column=0) self.disabledWhileRunning.append(b) b = Button(panel, text="Вниз", command=self.__down__, name="down") b.grid(row=1, column=0) self.disabledWhileRunning.append(b) Label(panel, text="Шаг:").grid(sticky=E, row=0, column=1) self.steps = IntVar(self, "10000") Entry(panel, textvariable=self.steps, width=6).grid(sticky=W, row=0, column=2) Label(panel, text="Скорость:").grid(sticky=E, row=1, column=1) self.speed = IntVar(self, "2000") Entry(panel, textvariable=self.speed, width=6).grid(sticky=W, row=1, column=2) self.position = IntVar(self, "1000") def readPosition(): try: self.position.set(self.control.mover.getPosition()) except (ConnectionResetError, Timeout): pass run_repeating(self, readPosition, 10000) b = Button(panel, text="Прочитать положение", command=readPosition) b.grid(row=0, column=3, columnspan=2) self.disabledWhileRunning.append(b) Label(panel, text="Положение:").grid(sticky=E, row=1, column=3) Entry(panel, textvariable=self.position, width=8, state="disabled").grid(sticky=W, row=1, column=4) panel = LabelFrame(self, text="Программа", name="program") program = panel panel.grid(sticky=W + E) panel.columnconfigure(1, weight=1) row = 0 for f in self.formulae: columns, rows = self.grid_size() Label(panel, text="Насос %d:" % (row + 1)).grid(row=row, column=0, sticky=E) e = Entry(panel, textvariable=f) e.grid(sticky=E + W, row=row, column=1) self.disabledWhileRunning.append(e) f.trace("w", lambda *x: self.after_idle(self.plotFormulae)) row += 1 panel = Frame(program, name="mover") panel.grid(columnspan=2, sticky=W) Label(panel, text="Максимальное смещение:").grid(sticky=E) Entry(panel, textvariable=self.maxTravel).grid(sticky=W, row=0, column=1) Label(panel, text="Скорость:").grid(sticky=E) Entry(panel, textvariable=self.programSpeed).grid(sticky=W, row=1, column=1) Label(panel, text="Время выполнения (в секундах):").grid(sticky=E) e = Entry(panel, textvariable=self.executionTime) e.grid(sticky=W, row=2, column=1) self.current_time = DoubleVar(self, "0") Label(panel, text="Текущее время:").grid(sticky=E) e = Entry(panel, textvariable=self.current_time) e.grid(sticky=W, row=3, column=1) self.disabledWhileRunning.append(e) self.executionTime.trace("w", lambda *x: self.plotFormulae()) panel = Frame(program, name="bottom") panel.grid(columnspan=2, sticky=W) row = 0 startButton = Button(panel, name="start", text="Старт", command=self.__start__) startButton.grid(row=row, column=0) self.disabledWhileRunning.append(startButton) Button(panel, text="Стоп", command=self.__stop__).grid(row=row, column=1) self.canvas = GraphCanvas(self) self.graphs = (Graph(self.canvas), Graph(self.canvas)) self.canvas.x.end = 100 self.canvas.y.end = 24 self.plotFormulae() self.canvas.grid(sticky=E + W + S + N) columns, rows = self.grid_size() self.columnconfigure(columns - 1, weight=1) self.rowconfigure(rows - 1, weight=1)
def addActionFrame(self): frame=Frame(self,relief=tk.RAISED,borderwidth=1) frame.pack(fill=tk.X,side=tk.TOP,\ expand=0,padx=8,pady=5) label=tk.Label(frame,text='Actions:',bg='#bbb') label.grid(row=0,column=0,sticky=tk.W,padx=8) #---------------Action checkbuttons--------------- self.isexport=tk.IntVar() self.ishighlight=tk.IntVar() self.isnote=tk.IntVar() self.isseparate=tk.IntVar() self.check_export=tk.Checkbutton(frame,text='Export PDFs',\ variable=self.isexport,command=self.doExport) self.check_highlight=tk.Checkbutton(frame,\ text='Extract highlights',\ variable=self.ishighlight,command=self.doHighlight) self.check_note=tk.Checkbutton(frame,\ text='Extract notes',\ variable=self.isnote,command=self.doNote) self.check_separate=tk.Checkbutton(frame,\ text='Save separately',\ variable=self.isseparate,command=self.doSeparate,\ state=tk.DISABLED) frame.columnconfigure(0,weight=1) self.check_export.grid(row=0,column=1,padx=8,sticky=tk.W) self.check_highlight.grid(row=0,column=2,padx=8,sticky=tk.W) self.check_note.grid(row=0,column=3,padx=8,sticky=tk.W) self.check_separate.grid(row=0,column=4,padx=8,sticky=tk.W) #---------------------2nd row--------------------- subframe=Frame(frame) subframe.grid(row=1,column=0,columnspan=5,sticky=tk.W+tk.E,\ pady=5) #-------------------Folder options------------------- folderlabel=tk.Label(subframe,text='Mendeley folder:',\ bg='#bbb') folderlabel.pack(side=tk.LEFT, padx=8) self.menfolder=tk.StringVar() self.menfolderlist=['All',] self.foldersmenu=Combobox(subframe,textvariable=\ self.menfolder,values=self.menfolderlist,state='readonly') self.foldersmenu.current(0) self.foldersmenu.bind('<<ComboboxSelected>>',self.setfolder) self.foldersmenu.pack(side=tk.LEFT,padx=8) #-------------------Quit button------------------- quit_button=tk.Button(subframe,text='Quit',\ command=self.quit) quit_button.pack(side=tk.RIGHT,padx=8) #-------------------Stop button------------------- ''' self.stop_button=tk.Button(subframe,text='Stop',\ command=self.stop) self.stop_button.pack(side=tk.RIGHT,padx=8) ''' #-------------------Start button------------------- self.start_button=tk.Button(subframe,text='Start',\ command=self.start,state=tk.DISABLED) self.start_button.pack(side=tk.RIGHT,pady=8) #-------------------Help button------------------- self.help_button=tk.Button(subframe,text='Help',\ command=self.showHelp) self.help_button.pack(side=tk.RIGHT,padx=8)
def __init__(self, master, gconf, directory=None): self.master = master self.initialized = False self.master.bind('<Return>', self.infer) self.master.bind('<Escape>', lambda a: self.master.quit()) self.master.protocol('WM_DELETE_WINDOW', self.quit) self.dir = os.path.abspath(ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd()))) self.frame = Frame(master) self.frame.pack(fill=BOTH, expand=1) self.frame.columnconfigure(1, weight=1) row = 0 # pracmln project options Label(self.frame, text='PRACMLN Project: ').grid(row=row, column=0, sticky='ES') project_container = Frame(self.frame) project_container.grid(row=row, column=1, sticky="NEWS") # new proj file self.btn_newproj = Button(project_container, text='New Project...', command=self.new_project) self.btn_newproj.grid(row=0, column=1, sticky="WS") # open proj file self.btn_openproj = Button(project_container, text='Open Project...', command=self.ask_load_project) self.btn_openproj.grid(row=0, column=2, sticky="WS") # save proj file self.btn_updateproj = Button(project_container, text='Save Project...', command=self.noask_save_project) self.btn_updateproj.grid(row=0, column=3, sticky="WS") # save proj file as... self.btn_saveproj = Button(project_container, text='Save Project as...', command=self.ask_save_project) self.btn_saveproj.grid(row=0, column=4, sticky="WS") # grammar selection row += 1 Label(self.frame, text='Grammar: ').grid(row=row, column=0, sticky='E') grammars = ['StandardGrammar', 'PRACGrammar'] self.selected_grammar = StringVar() self.selected_grammar.trace('w', self.settings_setdirty) l = OptionMenu(*(self.frame, self.selected_grammar) + tuple(grammars)) l.grid(row=row, column=1, sticky='NWE') # logic selection row += 1 Label(self.frame, text='Logic: ').grid(row=row, column=0, sticky='E') logics = ['FirstOrderLogic', 'FuzzyLogic'] self.selected_logic = StringVar() self.selected_logic.trace('w', self.settings_setdirty) l = OptionMenu(*(self.frame, self.selected_logic) + tuple(logics)) l.grid(row=row, column=1, sticky='NWE') # mln section row += 1 Label(self.frame, text="MLN: ").grid(row=row, column=0, sticky='NE') self.mln_container = FileEditBar(self.frame, directory=self.dir, filesettings={'extension': '.mln', 'ftypes': [('MLN files', '.mln')]}, defaultname='*unknown{}', importhook=self.import_mln, deletehook=self.delete_mln, projecthook=self.save_proj, filecontenthook=self.mlnfilecontent, fileslisthook=self.mlnfiles, updatehook=self.update_mln, onchangehook=self.project_setdirty) self.mln_container.editor.bind("<FocusIn>", self._got_focus) self.mln_container.grid(row=row, column=1, sticky="NEWS") self.mln_container.columnconfigure(1, weight=2) self.frame.rowconfigure(row, weight=1) row += 1 self.use_emln = IntVar() self.use_emln.set(0) self.cb_use_emln = Checkbutton(self.frame, text="use model extension", variable=self.use_emln, command=self.onchange_use_emln) self.cb_use_emln.grid(row=row, column=1, sticky="W") # mln extension section row += 1 self.emlncontainerrow = row self.emln_label = Label(self.frame, text="EMLN: ") self.emln_label.grid(row=self.emlncontainerrow, column=0, sticky='NE') self.emln_container = FileEditBar(self.frame, directory=self.dir, filesettings={'extension': '.emln', 'ftypes': [('MLN extension files','.emln')]}, defaultname='*unknown{}', importhook=self.import_emln, deletehook=self.delete_emln, projecthook=self.save_proj, filecontenthook=self.emlnfilecontent, fileslisthook=self.emlnfiles, updatehook=self.update_emln, onchangehook=self.project_setdirty) self.emln_container.grid(row=self.emlncontainerrow, column=1, sticky="NEWS") self.emln_container.editor.bind("<FocusIn>", self._got_focus) self.emln_container.columnconfigure(1, weight=2) self.onchange_use_emln(dirty=False) self.frame.rowconfigure(row, weight=1) # db section row += 1 Label(self.frame, text="Evidence: ").grid(row=row, column=0, sticky='NE') self.db_container = FileEditBar(self.frame, directory=self.dir, filesettings={'extension': '.db', 'ftypes': [('Database files', '.db')]}, defaultname='*unknown{}', importhook=self.import_db, deletehook=self.delete_db, projecthook=self.save_proj, filecontenthook=self.dbfilecontent, fileslisthook=self.dbfiles, updatehook=self.update_db, onchangehook=self.project_setdirty) self.db_container.grid(row=row, column=1, sticky="NEWS") self.db_container.editor.bind("<FocusIn>", self._got_focus) self.db_container.columnconfigure(1, weight=2) self.frame.rowconfigure(row, weight=1) # inference method selection row += 1 self.list_methods_row = row Label(self.frame, text="Method: ").grid(row=row, column=0, sticky=E) self.selected_method = StringVar() self.selected_method.trace('w', self.select_method) methodnames = sorted(InferenceMethods.names()) self.list_methods = OptionMenu(*(self.frame, self.selected_method) + tuple(methodnames)) self.list_methods.grid(row=self.list_methods_row, column=1, sticky="NWE") # options row += 1 option_container = Frame(self.frame) option_container.grid(row=row, column=1, sticky="NEWS") # Multiprocessing self.multicore = IntVar() self.cb_multicore = Checkbutton(option_container, text="Use all CPUs", variable=self.multicore, command=self.settings_setdirty) self.cb_multicore.grid(row=0, column=2, sticky=W) # profiling self.profile = IntVar() self.cb_profile = Checkbutton(option_container, text='Use Profiler', variable=self.profile, command=self.settings_setdirty) self.cb_profile.grid(row=0, column=3, sticky=W) # verbose self.verbose = IntVar() self.cb_verbose = Checkbutton(option_container, text='verbose', variable=self.verbose, command=self.settings_setdirty) self.cb_verbose.grid(row=0, column=4, sticky=W) # options self.ignore_unknown_preds = IntVar() self.cb_ignore_unknown_preds = Checkbutton(option_container, text='ignore unkown predicates', variable=self.ignore_unknown_preds, command=self.settings_setdirty) self.cb_ignore_unknown_preds.grid(row=0, column=5, sticky="W") # queries row += 1 Label(self.frame, text="Queries: ").grid(row=row, column=0, sticky=E) self.query = StringVar() self.query.trace('w', self.settings_setdirty) Entry(self.frame, textvariable=self.query).grid(row=row, column=1, sticky="NEW") # additional parameters row += 1 Label(self.frame, text="Add. params: ").grid(row=row, column=0, sticky="NE") self.params = StringVar() self.params.trace('w', self.settings_setdirty) self.entry_params = Entry(self.frame, textvariable=self.params) self.entry_params.grid(row=row, column=1, sticky="NEW") # closed-world predicates row += 1 Label(self.frame, text="CW preds: ").grid(row=row, column=0, sticky="E") cw_container = Frame(self.frame) cw_container.grid(row=row, column=1, sticky='NEWS') cw_container.columnconfigure(0, weight=1) self.cwPreds = StringVar() self.cwPreds.trace('w', self.settings_setdirty) self.entry_cw = Entry(cw_container, textvariable=self.cwPreds) self.entry_cw.grid(row=0, column=0, sticky="NEWS") self.closed_world = IntVar() self.cb_closed_world = Checkbutton(cw_container, text="CW Assumption", variable=self.closed_world, command=self.onchange_cw) self.cb_closed_world.grid(row=0, column=1, sticky='W') # output filename row += 1 output_cont = Frame(self.frame) output_cont.grid(row=row, column=1, sticky='NEWS') output_cont.columnconfigure(0, weight=1) # - filename Label(self.frame, text="Output: ").grid(row=row, column=0, sticky="NE") self.output_filename = StringVar() self.entry_output_filename = Entry(output_cont, textvariable=self.output_filename) self.entry_output_filename.grid(row=0, column=0, sticky="NEW") # - save option self.save = IntVar() self.cb_save = Checkbutton(output_cont, text="save", variable=self.save) self.cb_save.grid(row=0, column=1, sticky=W) # start button row += 1 start_button = Button(self.frame, text=">> Start Inference <<", command=self.infer) start_button.grid(row=row, column=1, sticky="NEW") self.settings_dirty = IntVar() self.project_dirty = IntVar() self.gconf = gconf self.project = None self.project_dir = os.path.abspath(ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd()))) if gconf['prev_query_project': self.project_dir] is not None: self.load_project(os.path.join(self.project_dir, gconf['prev_query_project':self.project_dir])) else: self.new_project() self.config = self.project.queryconf self.project.addlistener(self.project_setdirty) self.mln_container.dirty = False self.emln_container.dirty = False self.db_container.dirty = False self.project_setdirty(dirty=False) self.master.geometry(gconf['window_loc_query']) self.initialized = True
class EguanaGUI(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() # if not EguanaInit.eguana_root_dir_exists(): # EguanaInit.create_eguana_root_dir() def initUI(self): self.parent.title("EGUANA") self.style = ttk.Style() self.style.theme_use("alt") self.photoName = "eguana.gif" self.frame = Frame(self, relief=FLAT, borderwidth=10,bg='#FADC46') self.frame.pack(fill=BOTH, expand=True) self.pack(fill=BOTH, expand=True) self.setupMenuBar() self.setupTopBar() def setupMenuBar(self): self.menubar = EguanaMenu(self.parent,self) self.parent.config(menu=self.menubar) def setupTopBar(self): self.supportedDevices = [] for fileName in [name for name in os.listdir('./machineConfig') if os.path.isfile('./machineConfig/' + name) and not name == 'eguanaMachineConfig.py' and name.endswith('.py')]: # try:{ components = fileName.split('.') fileName = components[0] className = fileName[0].upper() + fileName[1:] try: module = __import__("machineConfig."+fileName,fromlist=["machineConfig."]) classVar = getattr(module,className) except: continue self.supportedDevices.append(classVar()) # except: # pass self.selectMachineFrame = Frame(self.frame,relief=FLAT,bg='#FADC46') self.selectMachineFrame.pack(fill=BOTH,expand=True) self.setupSelectMachineButtons() def setupSelectMachineButtons(self): numDevices = len(self.supportedDevices) numColumns = 3 numRows = math.ceil((numDevices+1)/3) self.photo = PhotoImage(file="eguana.gif") self.photo = self.photo.subsample(2); self.photo_label = Label(self.selectMachineFrame,image=self.photo,borderwidth=0,highlightthickness=0) self.photo_label.configure(bg='#FADC46') self.photo_label.grid(row=int(numRows/2),column=1, sticky=N+S+E+W,padx=2,pady =2) self.photo_label.image = self.photo index = 0 for i in range(numRows): for j in range(numColumns): if not(j == 1 and i == int(numRows/2)) and (index < numDevices): device = self.supportedDevices[index] b = Button(self.selectMachineFrame,text=device.name,relief=RAISED, command=lambda device=device :self.machineButtonPressed(device)) b.grid(row=i,column=j, sticky=N+S+E+W,padx=2,pady =2) index += 1 for i in range(numRows): self.selectMachineFrame.rowconfigure(i,weight=1) for i in range(numColumns): self.selectMachineFrame.columnconfigure(i,weight=1) def machineButtonPressed(self,inputDevice): dirStr = filedialog.askdirectory() if len(dirStr) and inputDevice.isDirectoryValid(dirStr): inputDevice.setDirPath(dirStr) EguanaModel().machine = inputDevice self.selectMachineFrame.destroy() self.menubar.inputSelected() self.photo_label.destroy() dirStr = 'Input Path : '+dirStr self.selectPlotFrame = Frame(self.frame, relief=FLAT,bg='#FADC46') self.selectPlotFrame.pack(fill=BOTH,expand=True) self.selectPlotFrame.rowconfigure(0,weight=1) self.selectPlotFrame.rowconfigure(1,weight=2) self.selectPlotFrame.columnconfigure(0,weight=1) self.infoFrame = Frame(self.selectPlotFrame, relief=FLAT, bg='#FADC46') self.infoFrame.grid(row=0,column=0, sticky=N+S+E+W,padx=2,pady =2) self.machineNameLabel = Label(self.infoFrame, text=inputDevice.name,relief=FLAT) self.machineNameLabel.grid(row=0,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.directoryLabel = Label(self.infoFrame, text="No project currently selected",relief=FLAT) self.directoryLabel.grid(row=1,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.directoryLabel.config(text=dirStr) self.outputDirButton = Button(self.infoFrame,text="No output directory selected. Click to select an output directory ",relief=RAISED,fg='red',command=self.askOutputDirectory) self.outputDirButton.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton = Button(self.infoFrame,text="No filter selected. Click to select a filter",relief=RAISED,fg='red',command=self.selectFilter) self.filterButton.grid(row=3,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.trialLabel = Label(self.infoFrame,text="Trial Number",relief=FLAT,justify=RIGHT,anchor=E) self.trialLabel.grid(row=4,column=0, sticky=N+S+E+W,padx=2,pady =2) vcmd = (self.master.register(self.validate),'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') self.trialEntry = Entry(self.infoFrame,validate = 'key', validatecommand = vcmd) self.trialEntry.grid(row=4,column=1, sticky=N+S+E+W,padx=2,pady =2) self.infoFrame.columnconfigure(0, weight=1) self.infoFrame.columnconfigure(1, weight=1) self.infoFrame.rowconfigure(0, weight=1) self.infoFrame.rowconfigure(1, weight=10) self.infoFrame.rowconfigure(2, weight=10) self.infoFrame.rowconfigure(3, weight=10) self.infoFrame.rowconfigure(4, weight=10) self.showPlotTools() def validate(self, action, index, value_if_allowed, prior_value, text, validation_type, trigger_type, widget_name): if len(value_if_allowed)==0 : return True if text in '0123456789.-+ ': try: float(value_if_allowed) return True except ValueError: return False else: return False def askOutputDirectory(self): dirStr = filedialog.askdirectory() if len(dirStr): dirStr = 'Output Path : '+dirStr self.outputDirButton.config(text=dirStr) def showPlotTools(self): f2= Frame(self.selectPlotFrame, relief=FLAT,bg='#FADC46') f2.grid(row=1,column=0,sticky=N+S+E+W,padx=10,pady =10) b1 = Button(f2,text='3D K',relief=RAISED,command= lambda:self.plotButtonPressed(1)) b1.grid(row=0, column=0,sticky=N+S+E+W,padx=5,pady =5) b2 = Button(f2,text='3D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(2)) b2.grid(row=0, column=1,sticky=N+S+E+W,padx=5,pady =5) b3 = Button(f2,text='3D DP',relief=RAISED,command=lambda:self.plotButtonPressed(3)) b3.grid(row=0, column=2,sticky=N+S+E+W,padx=5,pady =5) b4 = Button(f2,text='2D K',relief=RAISED,command=lambda:self.plotButtonPressed(4)) b4.grid(row=1, column=0,sticky=N+S+E+W,padx=5,pady =5) b5 = Button(f2,text='2D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(5)) b5.grid(row=1, column=1,sticky=N+S+E+W,padx=5,pady =5) b6 = Button(f2,text='2D DP',relief=RAISED,command=lambda:self.plotButtonPressed(6)) b6.grid(row=1, column=2,sticky=N+S+E+W,padx=5,pady =5) b1.config(state=EguanaModel().machine.plot3DKButtonState) b2.config(state=EguanaModel().machine.plot3DDstButtonState) b3.config(state=EguanaModel().machine.plot3DDpButtonState) b4.config(state=EguanaModel().machine.plot2DKButtonState) b5.config(state=EguanaModel().machine.plot2DDstButtonState) b6.config(state=EguanaModel().machine.plot2DDpButtonState) f2.columnconfigure(0, weight=1) f2.columnconfigure(1, weight=1) f2.columnconfigure(2, weight=1) f2.rowconfigure(0, weight=1) f2.rowconfigure(1, weight=1) def plotButtonPressed(self,number): trialNum = self.trialEntry.get() try: trialNum = int(trialNum) print(EguanaModel().machine.ifTrialExists(trialNum)) if EguanaModel().machine.ifTrialExists(trialNum): self.plotFigure(number) return True else: messagebox.showerror( "Trial Number Error", "The trial doesn't exist" ) return False except ValueError: messagebox.showerror( "Trial Number Error", "Error with the trial number" ) return False def plotFigure(self,number): m = CoilNumDialog(self.frame) if m.isSet(): print(m.getValues()) EguanaModel().machine.getDataForTrialNumber(number) def selectFilter(self): ffPopup = FilterFunctionPopup(self) if ffPopup.selectedFilter is not None: EguanaModel().filterFunction = ffPopup.selectedFilter ftPopup = FilterTypePopup(self,ffPopup.selectedFilter) if (ftPopup.selectedHeadFilterType is not None) and (ftPopup.selectedHeadFilterType is not None): self.menubar.setSelectedFilters(ffPopup.selectedFilter,ftPopup.selectedHeadFilterType,ftPopup.selectedJawFilterType) EguanaModel().filterTypeHead = ftPopup.selectedHeadFilterType EguanaModel().filterTypeJaw = ftPopup.selectedJawFilterType EguanaModel().filterFunction = ffPopup.selectedFilter buttonText = '{} - Jaw Filter : {} - Head Filter {}'.format(ffPopup.selectedFilter.name,ftPopup.selectedJawFilterType.name, ftPopup.selectedHeadFilterType.name) self.filterButton.config(text=buttonText) def updateSelectedFilters(self,ffName,ftHeadName,ftJawName): buttonText = '{} - Jaw Filter : {} - Head Filter {}'.format(ffName,ftHeadName,ftJawName) self.filterButton.config(text=buttonText) def changeImage(self): self.photo = PhotoImage(file=self.photoName) self.photo = self.photo.subsample(2); self.photo_label.image = self.photo self.photo_label.config(image=self.photo) def cursorPosition(self,event): if event.widget == self.openButton3D: if self.photoName == "eguana2.gif": self.photoName = "eguana.gif" self.changeImage() elif event.widget == self.openButton2D: if self.photoName == "eguana.gif": self.photoName = "eguana2.gif" self.changeImage()
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("EGUANA") self.style = ttk.Style() self.style.theme_use("alt") self.photoName = "eguana.gif" self.frame = Frame(self, relief=FLAT, borderwidth=10,bg='#FADC46') self.frame.pack(fill=BOTH, expand=True) self.pack(fill=BOTH, expand=True) self.setupMenuBar() self.setupTopBar() def setupMenuBar(self): self.menubar = EguanaMenu(self.parent,self) self.parent.config(menu=self.menubar) def setupTopBar(self): self.openButton3D = Button(self.frame,text="Select Directory for 3D EMA",relief=RAISED,command=self.askDirectory) self.openButton3D.grid(row=0,column=0, sticky=N+S+E+W,padx=2,pady =2) self.openButton2D = Button(self.frame,text="Select Directory for 2D EMA",relief=RAISED,command=self.askDirectory); self.openButton2D.grid(row=2,column=2, sticky=N+S+E+W,padx=2,pady =2) self.p1Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p1Button.grid(row=0,column=1, sticky=N+S+E+W,padx=2,pady =2) self.p2Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p2Button.grid(row=0,column=2, sticky=N+S+E+W,padx=2,pady =2) self.p3Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p3Button.grid(row=1,column=0, sticky=N+S+E+W,padx=2,pady =2) self.p4Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p4Button.grid(row=1,column=2, sticky=N+S+E+W,padx=2,pady =2) self.p5Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p5Button.grid(row=2,column=0, sticky=N+S+E+W,padx=2,pady =2) self.p6Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p6Button.grid(row=2,column=1, sticky=N+S+E+W,padx=2,pady =2) self.openButton3D.bind('<Motion>',self.cursorPosition) self.openButton2D.bind('<Motion>',self.cursorPosition) self.photo = PhotoImage(file="eguana.gif") self.photo = self.photo.subsample(2); self.photo_label = Label(self.frame,image=self.photo,borderwidth=0,highlightthickness=0) self.photo_label.configure(bg='#FADC46') self.photo_label.grid(row=1,column=1, sticky=N+S+E+W,padx=2,pady =2) self.photo_label.image = self.photo self.frame.columnconfigure(0, weight=1) self.frame.columnconfigure(1, weight=1) self.frame.columnconfigure(2, weight=1) self.frame.rowconfigure(0, weight=1) self.frame.rowconfigure(1, weight=1) self.frame.rowconfigure(2, weight=1) def askDirectory(self): dirStr = filedialog.askdirectory() if len(dirStr): self.openButton3D.destroy() self.openButton2D.destroy() self.p1Button.destroy() self.p2Button.destroy() self.p3Button.destroy() self.p4Button.destroy() self.p5Button.destroy() self.p6Button.destroy() self.menubar.entryconfigure('Filter', state = 'active') self.photo_label.destroy() dirStr = 'Input Path : '+dirStr self.frame.grid_forget() self.infoFrame = Frame(self.frame, relief=FLAT, bg='#FADC46') self.infoFrame.grid(row=0,column=0,columnspan=3, sticky=N+S+E+W,padx=2,pady =2) self.directoryLabel = Label(self.infoFrame, text="No project currently selected",relief=FLAT) self.directoryLabel.grid(row=0,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.directoryLabel.config(text=dirStr) self.outputDirButton = Button(self.infoFrame,text="No output directory selected. Click to select an output directory ",relief=RAISED,fg='red',command=self.askOutputDirectory) self.outputDirButton.grid(row=1,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton = Button(self.infoFrame,text="No filter selected. Click to select a filter",relief=RAISED,fg='red',command=self.selectFilter) self.filterButton.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.trialLabel = Label(self.infoFrame,text="Trial Number",relief=FLAT,justify=RIGHT,anchor=E) self.trialLabel.grid(row=3,column=0, sticky=N+S+E+W,padx=2,pady =2) vcmd = (self.master.register(self.validate),'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') self.trialEntry = Entry(self.infoFrame,validate = 'key', validatecommand = vcmd) self.trialEntry.grid(row=3,column=1, sticky=N+S+E+W,padx=2,pady =2) self.infoFrame.columnconfigure(0, weight=1) self.infoFrame.columnconfigure(1, weight=1) self.infoFrame.rowconfigure(0, weight=1) self.infoFrame.rowconfigure(1, weight=1) self.infoFrame.rowconfigure(2, weight=1) self.infoFrame.rowconfigure(3, weight=1) self.showPlotTools() def validate(self, action, index, value_if_allowed, prior_value, text, validation_type, trigger_type, widget_name): if len(value_if_allowed)==0 : return True if text in '0123456789.-+ ': try: float(value_if_allowed) return True except ValueError: return False else: return False def askOutputDirectory(self): dirStr = filedialog.askdirectory() if len(dirStr): dirStr = 'Output Path : '+dirStr self.outputDirButton.destroy() self.outputDirLabel = Label(self.infoFrame, relief=FLAT) self.outputDirLabel.grid(row=1,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.outputDirLabel.config(text=dirStr) def showPlotTools(self): f2= Frame(self.frame, relief=FLAT,bg='#FADC46') f2.grid(row=1,column=0,rowspan=2,columnspan=3,sticky=N+S+E+W,padx=10,pady =10) b1 = Button(f2,text='3D K',relief=RAISED,command= lambda:self.plotButtonPressed(1)) b1.grid(row=0, column=0,sticky=N+S+E+W,padx=5,pady =5) b2 = Button(f2,text='3D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(2)) b2.grid(row=0, column=1,sticky=N+S+E+W,padx=5,pady =5) b3 = Button(f2,text='3D DP',relief=RAISED,command=lambda:self.plotButtonPressed(3)) b3.grid(row=0, column=2,sticky=N+S+E+W,padx=5,pady =5) b4 = Button(f2,text='2D K',relief=RAISED,command=lambda:self.plotButtonPressed(4)) b4.grid(row=1, column=0,sticky=N+S+E+W,padx=5,pady =5) b5 = Button(f2,text='2D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(5)) b5.grid(row=1, column=1,sticky=N+S+E+W,padx=5,pady =5) b6 = Button(f2,text='2D DP',relief=RAISED,command=lambda:self.plotButtonPressed(6)) b6.grid(row=1, column=2,sticky=N+S+E+W,padx=5,pady =5) f2.columnconfigure(0, weight=1) f2.columnconfigure(1, weight=1) f2.columnconfigure(2, weight=1) f2.rowconfigure(0, weight=1) f2.rowconfigure(1, weight=1) def plotButtonPressed(self,number): trialNum = self.trialEntry.get() try: trialNum = float(trialNum) if trialNum < 16 and trialNum > 0: self.plotFigure(number) return True else: messagebox.showerror( "Trial Number Error", "The trial number is out of range" ) return False except ValueError: messagebox.showerror( "Trial Number Error", "Error with the trial number" ) return False def plotFigure(self,number): m = CoilNumDialog(self.frame) if m.isSet(): print(m.getValues()) def selectFilter(self): self.top = FilterPopup(self); def speech3DButtonPressed(self): self.menubar.filterSelected(0) self.top.destroy() if hasattr(self, 'filterLabel'): self.filterLabel.config(text="Filter : speech3D") else: self.filterLabel = Label(self.infoFrame, text="Filter : speech3D",relief=FLAT) self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton.destroy() def speech2DButtonPressed(self): self.menubar.filterSelected(1) self.top.destroy() if hasattr(self, 'filterLabel'): self.filterLabel.config(text="Filter : speech2D") else: self.filterLabel = Label(self.infoFrame, text="Filter : speech2D ",relief=FLAT) self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton.destroy() def swallow3DButtonPressed(self): self.menubar.filterSelected(2) self.top.destroy() if hasattr(self, 'filterLabel'): self.filterLabel.config(text="Filter : swallow3D") else: self.filterLabel = Label(self.infoFrame, text="Filter : swallow3D ",relief=FLAT) self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton.destroy() def swallow2DButtonPressed(self): self.menubar.filterSelected(3) self.top.destroy() if hasattr(self, 'filterLabel'): self.filterLabel.config(text="Filter : swallow2D") else: self.filterLabel = Label(self.infoFrame, text="Filter : swallow2D ",relief=FLAT) self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton.destroy() def changeImage(self): self.photo = PhotoImage(file=self.photoName) self.photo = self.photo.subsample(2); self.photo_label.image = self.photo self.photo_label.config(image=self.photo) def cursorPosition(self,event): if event.widget == self.openButton3D: if self.photoName == "eguana2.gif": self.photoName = "eguana.gif" self.changeImage() elif event.widget == self.openButton2D: if self.photoName == "eguana.gif": self.photoName = "eguana2.gif" self.changeImage()
def show_items(self, items, upper=[]): """ Creates a new page on the stack, automatically adds a back button when there are pages on the stack already :param items: list the items to display :param upper: list previous levels' ids :return: None """ num = 0 # create a new frame wrap = Frame(self, bg="black") # when there were previous frames, hide the top one and add a back button for the new one if len(self.framestack): self.hide_top() back = FlatButton( wrap, text='back…', image=self.get_icon("arrow.left"), command=self.go_back, ) back.set_color("#00a300") # green back.grid(row=0, column=0, padx=1, pady=1, sticky=TkC.W + TkC.E + TkC.N + TkC.S) num += 1 # add the new frame to the stack and display it self.framestack.append(wrap) self.show_top() # calculate tile distribution all = len(items) + num rows = floor(sqrt(all)) cols = ceil(all / rows) # make cells autoscale for x in range(int(cols)): wrap.columnconfigure(x, weight=1) for y in range(int(rows)): wrap.rowconfigure(y, weight=1) # display all given buttons for item in items: act = upper + [item['name']] if 'icon' in item: image = self.get_icon(item['icon']) else: image = self.get_icon('scrabble.'+item['label'][0:1].lower()) btn = FlatButton( wrap, text=item['label'], image=image ) if 'items' in item: # this is a deeper level btn.configure(command=lambda act=act, item=item: self.show_items(item['items'], act), text=item['label']+'…') btn.set_color("#2b5797") # dark-blue else: # this is an action btn.configure(command=lambda act=act: self.go_action(act), ) if 'color' in item: btn.set_color(item['color']) # add buton to the grid btn.grid( row=int(floor(num / cols)), column=int(num % cols), padx=1, pady=1, sticky=TkC.W + TkC.E + TkC.N + TkC.S ) num += 1