class SplashScreen: root = None win = None img = 'images/splash-screen' flag = 0 def __init__(self, root): self.root = root self.width = 500 self.height = 300 self.flag = config.preferences.show_splash def show(self): self.root.withdraw() if self.flag: img_file = os.path.join(app.config.sk_share_dir, self.img + '.png') from sk1sdk.tkpng import load_icon load_icon(self.root, img_file, self.img) scrnWt = self.root.winfo_screenwidth() scrnHt = self.root.winfo_screenheight() winXPos = (scrnWt / 2) - (self.width / 2) winYPos = (scrnHt / 2) - (self.height / 2) self.win = Toplevel() self.win.overrideredirect(1) self.win.configure(background='black') self.banner = Label(self.win, image=self.img, cursor='watch', borderwidth=0) self.banner.pack() self.verlb = Label(self.win, text='version %s' % (config.version, ), bg='white') self.verlb.place(x=10, y=240) self.verlb['font'] += ' bold' self.txtlb = Label(self.win, text='Start...', bg='white') self.txtlb.place(x=10, y=265) self.progress_bar = SS_ProgressBar(self.win) self.progress_bar.pack(fill=X, side=TOP) geom = (self.width, self.height, winXPos, winYPos) self.win.geometry('%dx%d+%d+%d' % geom) self.win.update() def hide(self): if self.flag and self.win: self.win.withdraw() self.win.destroy() def set_val(self, val, txt=''): self.progress_bar.set_val(val) if txt: self.txtlb['text'] = txt self.win.update()
def main(): pygame.init() root = Tk() win_option = Toplevel(root) menu = Menu(root, win_option) app = QuizLetter(win_option) win_option.withdraw() root.mainloop() pygame.quit()
class SplashScreen: root = None win = None img = 'images/splash-screen' flag = 0 def __init__(self, root): self.root = root self.width = 500 self.height = 300 self.flag = config.preferences.show_splash def show(self): self.root.withdraw() if self.flag: img_file = os.path.join(app.config.sk_share_dir, self.img + '.png') from sk1sdk.tkpng import load_icon load_icon(self.root, img_file, self.img) scrnWt = self.root.winfo_screenwidth() scrnHt = self.root.winfo_screenheight() winXPos = (scrnWt / 2) - (self.width / 2) winYPos = (scrnHt / 2) - (self.height / 2) self.win = Toplevel() self.win.overrideredirect(1) self.win.configure(background='black') self.banner = Label(self.win, image=self.img, cursor='watch', borderwidth=0) self.banner.pack() self.verlb = Label(self.win, text='version %s' % (config.version,), bg='white') self.verlb.place(x=10, y=240) self.verlb['font'] += ' bold' self.txtlb = Label(self.win, text='Start...', bg='white') self.txtlb.place(x=10, y=265) self.progress_bar = SS_ProgressBar(self.win) self.progress_bar.pack(fill=X, side=TOP) geom = (self.width, self.height, winXPos, winYPos) self.win.geometry('%dx%d+%d+%d' % geom) self.win.update() def hide(self): if self.flag and self.win: self.win.withdraw() self.win.destroy() def set_val(self, val, txt=''): self.progress_bar.set_val(val) if txt: self.txtlb['text'] = txt self.win.update()
class SshUserPw(object): ''' A separate GUI window to enter the SSH username and password ''' def __init__(self, callback): self._callback = callback self._root = Toplevel() self._root.title('FlowEntry Trace') self._root.minsize(width=300, height=150) self._top_frame = Frame(self._root) self._top_frame.pack(side=TOP, fill=X, padx=10, pady=10) # The text labels label_entry_frame = Frame(self._top_frame) label_entry_frame.pack(side=TOP, anchor=W, pady=5) self._username_label = LabelEntry(label_entry_frame, 'username') self._password_label = LabelEntry(label_entry_frame, 'password') # the buttons button_frame = Frame(self._top_frame, pady=5) button_frame.pack(side=BOTTOM, anchor=S) buttons_dict = OrderedDict([('ok', self._ok_callback), ('cancel', self._cancel_callback)]) Buttons(button_frame, buttons_dict, button_orientation=LEFT) # Hide this window until its needed self._root.withdraw() @property def username(self): return self._username_label.entry_text @property def password(self): return self._password_label.entry_text def display(self, show=True): if show: self._root.update() self._root.deiconify() else: self._root.withdraw() def _cancel_callback(self): self.display(False) def _ok_callback(self): if not self.username or not self.password: Popup('Both the username and password must be filled in') return self.display(False) self._callback()
def Modules (close = False): if not Modules.singleton: win = Toplevel (takefocus = True) win.protocol ('WM_DELETE_WINDOW', win.withdraw) win.resizable (width = False, height = False) win.withdraw() oApp = GUI (master = win) Modules.singleton = _Modules (oApp = oApp) return Modules.singleton
def PPSel(): if PPSel.singleton == None: win = Toplevel(takefocus=True) win.protocol('WM_DELETE_WINDOW', win.withdraw) win.resizable(width=False, height=False) win.withdraw() oApp = GUI(master=win) PPSel.singleton = _PPSel(oApp=oApp) return PPSel.singleton
def XMC (master, sample): if XMC.singleton == None: win = Toplevel (takefocus = True) win.protocol ('WM_DELETE_WINDOW', win.withdraw) win.withdraw() oApp = GUI (win, sample) XMC.singleton = _XMC (oApp, sample) if master not in XMC.master: XMC.master.append (master) return XMC.singleton
def HIRES(master, oTCON, oXHIRES, sample, cryostat): if HIRES.singleton == None: win = Toplevel(takefocus=True) win.protocol('WM_DELETE_WINDOW', win.withdraw) win.withdraw() oApp = GUI(win, sample) HIRES.singleton = _HIRES(oApp, oTCON, oXHIRES, sample, cryostat) if master not in HIRES.master: HIRES.master.append(master) return HIRES.singleton
def configure_param_lmme_dialog(self): w = Toplevel() w.protocol('WM_DELETE_WINDOW', self.hide_param_dialog) self.param_dlg = w w.withdraw() # cache la fenetre w.rowconfigure(0, weight=1) w.columnconfigure(0, weight=1) prm = ParamModeLMME( w, "Paramètres du calcul modal pour la méthode LMME", relief='sunken', borderwidth=2) prm.grid(row=0, column=0) self.param_mode_iter_simult_lmme = prm Button(w, text="Appliquer", command=self.anything_changed).grid( row=1, column=0) Button(w, text="OK", command=self.hide_param_dialog).grid( row=2, column=0)
def Sample(master): if not Sample.singleton: win = Toplevel(takefocus=True) win.protocol('WM_DELETE_WINDOW', win.withdraw) win.resizable(width=False, height=False) win.withdraw() oApp = GUI(master=win) Sample.singleton = _Sample(oApp) if master not in Sample.master: Sample.master.append(master) return Sample.singleton
def about( self ): "Display about box." about = self.aboutBox if about is None: bg = 'white' about = Toplevel( bg='white' ) about.title( 'About' ) info = self.appName + ': a simple network editor for Mini-CCNx - based on Miniedit ' warning = 'Development version - not entirely functional!' author = 'Carlos Cabral, Jan 2013' author2 = 'Miniedit by Bob Lantz <rlantz@cs>, April 2010' line1 = Label( about, text=info, font='Helvetica 10 bold', bg=bg ) line2 = Label( about, text=warning, font='Helvetica 9', bg=bg ) line3 = Label( about, text=author, font='Helvetica 9', bg=bg ) line4 = Label( about, text=author2, font='Helvetica 9', bg=bg ) line1.pack( padx=20, pady=10 ) line2.pack(pady=10 ) line3.pack(pady=10 ) line4.pack(pady=10 ) hide = ( lambda about=about: about.withdraw() ) self.aboutBox = about # Hide on close rather than destroying window Wm.wm_protocol( about, name='WM_DELETE_WINDOW', func=hide ) # Show (existing) window about.deiconify()
def SUS (master, oTCON, oXLIA, oXMC, sample, cryostat): if SUS.singleton == None: win = Toplevel (takefocus = True) win.protocol ('WM_DELETE_WINDOW', win.withdraw) win.withdraw() oApp = GUI (win, sample) SUS.singleton = _SUS ( oApp, oTCON, oXLIA, oXMC, sample, cryostat) if master not in SUS.master: SUS.master.append (master) return SUS.singleton
def construct(self): """ Construct the window and the frame used to display the XML :return: """ top = Toplevel() top.withdraw() top.protocol("WM_DELETE_WINDOW", self.view_xml_pane) top.columnconfigure(0, weight=1) top.rowconfigure(0, weight=1) top.title("XML Preview") self._pane = top xml_area = Text(top, borderwidth=2, relief="sunken") xml_area.config(font=("consolas", 12), undo=True, wrap='word', state=DISABLED) xml_area.grid(row=0, column=0, sticky="nsew", padx=2, pady=2) scrollbar = Scrollbar(top, command=xml_area.yview) scrollbar.grid(row=0, column=1, sticky='nsew') xml_area['yscrollcommand'] = scrollbar.set self._text_area = xml_area
class Restraints(object): def __init__(self, parent, bondForceParams, atoms_def): self.parent = parent self.main = Toplevel(self.parent) self.bondForceParams = bondForceParams self.atoms_def = atoms_def self.main.title('PyFepRestr') self.validated_values = [] if platform == "darwin": self.button_font = self.label_font = self.radiobutton_font = Font( family='Arial', size=15) else: self.radiobutton_font = Font(font=Radiobutton()["font"]) self.label_font = Font(font=Label()["font"]) self.button_font = Font(font=Button()["font"]) self.r_var = BooleanVar() self.r_var.set(1) rj1 = Radiobutton(self.main, text='kJ', variable=self.r_var, value=0, command=self.refresh, font=self.radiobutton_font) rcal1 = Radiobutton(self.main, text="kCal", variable=self.r_var, value=1, command=self.refresh, font=self.radiobutton_font) rj1.grid(row=0, column=0, padx=5, pady=5) rcal1.grid(row=0, column=1, padx=5, pady=5) labels = [ 'Temp', 'K raA', u'K \u03b8a', u'K \u03b8A', u'K \u03c6ba', u'K \u03c6aA', u'K \u03c6AB' ] label_all = [] self.entry_all = [] self.entry_all_get = [] self.dimen_all = [] for lab in labels: label_answer = Label(self.main, text=lab, anchor=W, font=self.label_font) label_all.append(label_answer) entry = Entry(self.main) self.entry_all.append(entry) self.entry_all_get.append(entry.get) dimen = Label(self.main, anchor=W, font=self.label_font) self.dimen_all.append(dimen) for i, (label, entry, dimen) in enumerate( zip(label_all, self.entry_all, self.dimen_all)): label.grid(row=i + 1, column=1, padx=5, pady=5, sticky=W) entry.grid(row=i + 1, column=2, padx=5, pady=5, sticky=W) dimen.grid(row=i + 1, column=3, padx=10, pady=5, sticky=W) self.dimen_all[0]['text'] = 'Kelvin' self.refresh() self.button_res = Button(self.main, text="Next -> ", command=self.validate, font=self.button_font) self.button_res.grid(row=11, column=2, padx=5, pady=5) self.destroyProgr = Button(self.main, text='Exit', bg='red', command=self.main.destroy, font=self.button_font) self.destroyProgr.grid(row=0, column=3, padx=5, pady=5) self.helpProgr = Button(self.main, text=' ? ', bg='#ffb3fe', command=self.getHelp, font=self.button_font) self.helpProgr.grid(row=12, column=0, padx=5, pady=5) self.select_atoms = StringVar() self.select_atoms.set("Select 6 atoms") atoms_list = ["Select 6 atoms", "Select 2 atoms"] menu = OptionMenu(self.main, self.select_atoms, *atoms_list) menu.grid(row=11, column=3, padx=5, pady=5) def refresh(self): if self.r_var.get(): self.dimen_all[1].configure(text=u'kCal/mol/\u212b\u00b2') for dimen in self.dimen_all[2:]: dimen.configure(text=u'kCal/mol/rad\u00b2') else: self.dimen_all[1].configure(text=u'kJ/mol/\u212b\u00b2') for dimen in self.dimen_all[2:]: dimen.configure(text=u'kJ/mol/rad\u00b2') for dimen in self.dimen_all: dimen.update() def validate(self): for i, k in enumerate(self.entry_all_get): try: f = float(k()) if f <= 0: raise ValueError self.entry_all[i]['bg'] = 'white' except ValueError: self.entry_all[i]['bg'] = "red" return self.validated_values.append(f) self.finish() def finish(self): if self.r_var.get(): self.validated_values = list((self.validated_values[0],)) + \ list(map(kCal_to_kJ, self.validated_values[1:])) self.bondForceParams['T'] = self.validated_values[0] # Temperature (K) self.bondForceParams['K_r_aA'] = self.validated_values[ 1] * 100 # force constant for distance (kJ/mol/nm^2) self.bondForceParams['K_th_a'] = self.validated_values[ 2] # force constant for angle (kJ/mol/rad^2) self.bondForceParams['K_th_A'] = self.validated_values[ 3] # force constant for angle (kJ/mol/rad^2) self.bondForceParams['K_phi_ba'] = self.validated_values[ 4] # force constant for dihedral (kJ/mol/rad^2) self.bondForceParams['K_phi_aA'] = self.validated_values[ 5] # force constant for dihedral (kJ/mol/rad^2) self.bondForceParams['K_phi_AB'] = self.validated_values[ 6] # force constant for dihedral (kJ/mol/rad^2) showinfo('Info', 'Now choose the atoms you need') if self.select_atoms.get() == 'Select 6 atoms': wiz = RestraintWizard(self.parent, self.bondForceParams, self.atoms_def) else: wiz = RestraintWizardTwo(self.parent, self.bondForceParams, self.atoms_def) cmd.set_wizard(wiz) cmd.refresh_wizard() self.main.withdraw() self.main.destroy() @staticmethod def getHelp(): with tempfile.NamedTemporaryFile('w', delete=False, suffix='.html') as f: url = "file://" + f.name f.write(help_1) webbrowser.open(url)
class Tooltips: tooltip_delay = 100 def __init__(self): self.descriptions = {} self.balloon = None self.balloon_label = None self.last_widget = '' self.after_id = None self.root = None def AddDescription(self, widget, description): self.descriptions[widget._w] = description if widget._w == self.last_widget: self.balloon_label['text'] = description def RemoveDescription(self, widget): if type(widget) == InstanceType: widget = widget._w if self.descriptions.has_key(widget): del self.descriptions[widget] def GetDescription(self, widget): if type(widget) == InstanceType: widget = widget._w if self.descriptions.has_key(widget): return self.descriptions[widget] return '' def create_balloon(self, root): self.root = root self.balloon = Toplevel(self.root) self.balloon.withdraw() self.balloon.overrideredirect(1) self.balloon["relief"] = 'flat' label = TLabel(self.balloon, text='Tooltip', style='Tooltips') label.pack(ipadx=2, ipady=2) self.balloon_label = label def popup_balloon(self, widget_name, x, y, text): self.last_widget = widget_name self.balloon.withdraw() self.balloon_label['text'] = text width = self.balloon_label.winfo_reqwidth() height = self.balloon_label.winfo_reqheight() screenwidth = self.root.winfo_screenwidth() screenheight = self.root.winfo_screenheight() x = self.root.winfo_pointerx() y = self.root.winfo_pointery() + 20 if screenwidth < (x + width): x = x - width if screenheight < (y + height): y = y - height - 25 self.balloon.geometry('%+d%+d' % (x, y)) self.balloon.update() self.balloon.deiconify() self.balloon.tkraise() def popup_delayed(self, widget_name, x, y, text, *args): self.after_id = None self.popup_balloon(widget_name, x, y, text) def enter_widget(self, event): widget_name = event.widget text = self.GetDescription(widget_name) if text: x = event.x y = event.y if self.after_id: print 'after_id in enter' self.root.after_cancel(self.after_id) self.after_id = self.root.after(self.tooltip_delay, self.popup_delayed, widget_name, x, y, text) def leave_widget(self, event): global last_widget, after_id if self.after_id is not None: self.root.after_cancel(self.after_id) self.after_id = None self.last_widget = '' last_widget = '' self.balloon.withdraw() button_press = leave_widget def destroy_widget(self, event): self.RemoveDescription(event.widget)
class PypeTkPad(object): def __init__(self, master, queue, pypeOutput): self.queue = queue self.pypeOutput = pypeOutput self.master = master self.master.title('PypePad') self.master.geometry("%dx%d%+d%+d" % (700, 500, 0, 0)) self.master.minsize(300, 100) self.output_file_name = None self.BuildMainFrame() self.UpdateOutput() def NewCommand(self): self.ClearAllCommand() def OpenCommand(self): import tkFileDialog from Tkinter import END openfile = tkFileDialog.askopenfile() if not openfile: return for line in openfile.readlines(): self.text_input.insert(END,line) def SaveCommand(self): import tkFileDialog from Tkinter import END saveasfile = tkFileDialog.asksaveasfile() if not saveasfile: return alltext = self.text_input.get("1.0",END) saveasfile.write(alltext) def QuitCommand(self): self.master.quit() def ClearInputCommand(self): from Tkinter import END self.text_input.delete("1.0",END) def ClearOutputCommand(self): from Tkinter import NORMAL, END, DISABLED self.text_output["state"] = NORMAL self.text_output.delete("1.0",END) self.text_output["state"] = DISABLED self.text_output.see(END) self.text_output.update() def ClearAllCommand(self): self.ClearInputCommand() self.ClearOutputCommand() def OutputFileCommand(self): import tkFileDialog outputfilename = tkFileDialog.asksaveasfilename() if sys.platform == 'win32' and len(outputfilename.split()) > 1: outputfilename = '"%s"' % outputfilename self.output_file_name = outputfilename def AboutCommand(self): self.OutputText('\n') self.OutputText('* PypePad, Copyright (c) Luca Antiga, David Steinman. *\n') self.OutputText('\n') def UpdateOutput(self): if self.pypeOutput: text = self.pypeOutput.pop(0) self.output_stream.write(text) self.master.after(10,self.UpdateOutput) def RunPype(self,arguments): if not arguments: return if self.output_to_file.get() is not 'n' and self.output_file_name: self.output_stream.output_to_file = True self.output_stream.output_file = open(self.output_file_name,self.output_to_file.get()) else: self.output_stream.output_to_file = False self.queue.append(arguments) def GetWordUnderCursor(self): from Tkinter import CURRENT splitindex = self.text_input.index(CURRENT).split('.') line = self.text_input.get(splitindex[0]+".0",splitindex[0]+".end") wordstart = line.rfind(' ',0,int(splitindex[1])-1)+1 wordend = line.find(' ',int(splitindex[1])) if wordend == -1: wordend = len(line) word = line[wordstart:wordend] return word def GetWordIndex(self): startindex = self.text_input.index("insert-1c wordstart") endindex = self.text_input.index("insert-1c wordend") if self.text_input.get(startindex+'-1c') == '-' and self.text_input.get(startindex+'-2c') == '-': startindex = self.text_input.index("insert-1c wordstart -2c") elif self.text_input.get(startindex+'-1c') == '-' and self.text_input.get(startindex+'-2c') == ' ': startindex = self.text_input.index("insert-1c wordstart -1c") self.wordIndex[0] = startindex self.wordIndex[1] = endindex word = self.text_input.get(self.wordIndex[0],self.wordIndex[1]) return word def GetLogicalLine(self,physicallineid): indexes, lines = self.GetLogicalLines() return lines[indexes[physicallineid]] def GetLogicalLineRange(self,physicallinefirstid,physicallinelastid): indexes, lines = self.GetLogicalLines() return lines[indexes[physicallinefirstid]:indexes[physicallinelastid]+1] def GetAllLogicalLines(self): return self.GetLogicalLines()[1] def GetLogicalLines(self): from Tkinter import END physicallines = self.text_input.get("1.0",END).split('\n') lines = [] indexes = [0] * len(physicallines) lineid = 0 previousline = "" join = 0 for line in physicallines: if line.startswith('#'): if join: indexes[lineid] = indexes[lineid-1] elif join: if line.endswith('\\'): lines[-1] = lines[-1] + " " + line[:-1] join = 1 else: lines[-1] = lines[-1] + " " + line join = 0 indexes[lineid] = indexes[lineid-1] else: if line.endswith('\\'): join = 1 lines.append(line[:-1]) else: lines.append(line) join = 0 if lineid > 0: indexes[lineid] = indexes[lineid-1]+1 lineid += 1 return indexes, lines def GetLineUnderCursor(self): from Tkinter import INSERT currentlineid = int(self.text_input.index(INSERT).split('.')[0]) - 1 return self.GetLogicalLine(currentlineid) def RunAllCommand(self): lines = self.GetAllLogicalLines() for line in lines: if line and line.strip(): self.RunPype(line) def RunLineCommand(self): line = self.GetLineUnderCursor() if line and line.strip(): self.RunPype(line) def RunSelectionCommand(self): from Tkinter import TclError, SEL_FIRST, SEL_LAST try: firstlineid = int(self.text_input.index(SEL_FIRST).split('.')[0]) - 1 lastlineid = int(self.text_input.index(SEL_LAST).split('.')[0]) - 1 lines = self.GetLogicalLineRange(firstlineid,lastlineid) for line in lines: self.RunPype(line) except TclError: pass def GetSuggestionsList(self,word): list = [] try: exec('import vmtkscripts') except ImportError: return None if word.startswith('--'): list = ['--pipe','--help'] elif word.startswith('-'): optionlist = [] scriptindex = self.text_input.search('vmtk',self.wordIndex[0],backwards=1) moduleName = self.text_input.get( scriptindex,scriptindex+' wordend' ) try: exec('import '+moduleName) exec('scriptObjectClassName = '+moduleName+'.'+moduleName) exec ('scriptObject = '+moduleName+'.'+scriptObjectClassName +'()') members = scriptObject.InputMembers + scriptObject.OutputMembers for member in members: optionlist.append('-'+member.OptionName) exec('list = [option for option in optionlist if option.count(word)]') except: return list else: exec('list = [scriptname for scriptname in vmtkscripts.__all__ if scriptname.count(word) ]') return list def FillSuggestionsList(self,word): from Tkinter import END self.suggestionslist.delete(0,END) suggestions = self.GetSuggestionsList(word) for suggestion in suggestions: self.suggestionslist.insert(END,suggestion) def ReplaceTextCommand(self,word): self.text_input.delete(self.wordIndex[0],self.wordIndex[1]) self.text_input.insert(self.wordIndex[0],word) self.text_input.focus_set() def ShowHelpCommand(self): word = self.GetWordUnderCursor() self.OutputText(word) if word: self.RunPype(word+' --help') else: self.OutputText('Enter your vmtk Pype above and Run.\n') def AutoCompleteCommand(self): word = self.GetWordIndex() self.suggestionswindow.withdraw() if word: self.FillSuggestionsList(word) self.suggestionswindow.geometry("%dx%d%+d%+d" % (400, 150, self.text_output.winfo_rootx(),self.text_output.winfo_rooty())) self.suggestionswindow.deiconify() self.suggestionswindow.lift() def InsertScriptName(self,scriptname): from Tkinter import INSERT self.text_input.insert(INSERT,scriptname+' ') def InsertFileName(self): from Tkinter import INSERT import tkFileDialog openfilename = tkFileDialog.askopenfilename() if not openfilename: return if len(openfilename.split()) > 1: openfilename = '"%s"' % openfilename self.text_input.insert(INSERT,openfilename+' ') def KeyPressHandler(self,event): if event.keysym == "Tab" : self.AutoCompleteCommand() self.suggestionslist.focus_set() self.suggestionslist.selection_set(0) return "break" else: self.text_input.focus_set() def TopKeyPressHandler(self,event): from Tkinter import ACTIVE, INSERT if event.keysym in ['Down','Up'] : self.suggestionslist.focus_set() elif event.keysym == "Return": word = self.suggestionslist.get(ACTIVE) self.ReplaceTextCommand(word) self.suggestionswindow.withdraw() self.text_input.focus_set() elif len(event.keysym) == 1 : self.suggestionswindow.withdraw() self.text_input.insert(INSERT,event.keysym) self.text_input.focus_set() else : self.suggestionswindow.withdraw() self.text_input.focus_set() def NewHandler(self,event): self.NewCommand() def OpenHandler(self,event): self.OpenCommand() def SaveHandler(self,event): self.SaveCommand() def InsertFileNameHandler(self,event): self.InsertFileName() return "break" def QuitHandler(self,event): self.QuitCommand() def ShowHelpHandler(self,event): self.ShowHelpCommand() def RunKeyboardHandler(self,event): from Tkinter import SEL_FIRST, TclError try: self.text_input.index(SEL_FIRST) self.RunSelectionCommand() except TclError: self.RunLineCommand() return "break" def RunAllHandler(self,event): self.RunAllCommand() def PopupHandler(self,event): try: self.popupmenu.tk_popup(event.x_root, event.y_root, 0) finally: self.popupmenu.grab_release() def OutputText(self,text): from Tkinter import NORMAL, END, DISABLED self.text_output["state"] = NORMAL self.text_output.insert(END,text) self.text_output["state"] = DISABLED def BuildScriptMenu(self,parentmenu,modulename): from Tkinter import Menu menu = Menu(parentmenu,bd=1,activeborderwidth=0) try: exec('import '+ modulename) except ImportError: return None scriptnames = [] exec ('scriptnames = [scriptname for scriptname in '+modulename+'.__all__]') menulength = 20 for i in range(len(scriptnames)/menulength+1): subscriptnames = scriptnames[i*menulength:(i+1)*menulength] if not subscriptnames: break submenu = Menu(menu,bd=1,activeborderwidth=0) menu.add_cascade(label=subscriptnames[0]+"...",menu=submenu) for scriptname in subscriptnames: callback = CallbackShim(self.InsertScriptName,scriptname) submenu.add_command(label=scriptname,command=callback) return menu 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)
class AddCatalogSourcesDialog(): """Class to gather input values for loading catalog sources This class presents a dialog box to the user allowing them to input values for the various filenames, model names, and other values needed to extract the Fermi Source Catalog sources from the relevant files and add them to their model. Usage: dialog = AddCatalogSourceDialog() data = dialog.getData() The getData() method returns a dictionary of the data values entered by the user. The dictionary keys are listed below in the description of the values the user is prompted for. If the dialog is canceled, it returns a None object. The user is prompted to input the following values - Source Catalog file (key => 'catalogFile') - This is the FITS file of the Fermi Source catalog. This can be the 1FGL, 2FGL, or 3FGL (once published) catalog file. This contains the sources to be added to the model. - LAT Event File (key => 'eventFile') - This is a valid FT1 LAT event FITS file. This file is used to extract the region of interest (ROI) information to determine which sources should be selected from the catalog. - Source Significance Limit (key => 'sigLimit') - This is the significance limit threshold for selecting sources from the catalog. Sources with significance values less than this limit will not be added to the model. - Galactic Diffuse Model file (key => 'galDiffFile') - This is the file containing the galactic diffuse model to use. By default it points to the standard file provided with the Science Tools. - Galactic Diffuse Model Name (key => 'gdModelName') - This is the name of the model to use from the galactic diffuse model file. By default it is set to ????????????. - Isotropic Template file (key => 'iosTempFile') - The name of the file containing the isotropic diffuse templates. By default this is set to the standard file provided with the Science Tools. - Isotropic Template Name (key => 'isoTempName') - The name of the isotropic template to use. By default this is set to ????????????. - Variable Source Radius - radius within which all sources should be set to allow their parameters to vary. Outside of this radius parameters will be fixed to catalog values. Values less than 0 are treated as meaning that the radius is the same as the extraction radius in the FT1 event file. Default is -1 - Force Point Source flag - If set all extended sources in the catalog will be treated as point sources. Default is false. - Extended Source Template Directory - Directory containing the extended source model files. This is only needed if the Force Point Source flag is no. """ def __init__(self): """Initialize the class Parameters: - self - This AddCatalogSourcesDialog object Return value: - none Description: This method simply creates the top level Tk window for holding the dialog box and initializes an empty dictionary to hold the return values. """ self.win = Toplevel() self.win.title("Add Catalog Sources") # self.win.minsize(500, 100) self.values = {} # need access to these outside their creation function self.l9 = Label() self.b7 = Button() def _draw(self): """Create the dialog box Parameters: - self - This AddCatalogSourcesDialog object Return value: - none Description: This method creates the dialog box to be presented to the user. It also creates the internal EntryField variables to hold the data values entered by the user. """ labelWidth = 32 msg = Label( self.win, width=60, pady=5, text= "To load catalog sources please provide the following information:" ) msg.pack(side=TOP) scFrame = Frame(self.win) l1 = Label(scFrame, text="Source Catalog File:", width=labelWidth, anchor=E) l1.pack(side=LEFT) self._catalogFileField = Pmw.EntryField(scFrame, value="") self._catalogFileField.pack(side=LEFT, expand=YES, fill=X) b1 = Button(scFrame, text="Browse...", command=(lambda: self._getFile(self._catalogFileField))) b1.pack(side=LEFT) scFrame.pack(side=TOP, expand=YES, fill=X) ft1Frame = Frame(self.win) l2 = Label(ft1Frame, text="Event File (for ROI):", width=labelWidth, anchor=E) l2.pack(side=LEFT) self._eventFileField = Pmw.EntryField(ft1Frame, value="") self._eventFileField.pack(side=LEFT, expand=YES, fill=X) b2 = Button(ft1Frame, text="Browse...", command=(lambda: self._getFile(self._eventFileField))) b2.pack(side=LEFT) ft1Frame.pack(side=TOP, expand=YES, fill=X) sigFrame = Frame(self.win) l3 = Label(sigFrame, text="Source Significance Limit:", width=labelWidth, anchor=E) l3.pack(side=LEFT) self._sigLimitField = Pmw.EntryField(sigFrame, value=4) self._sigLimitField.pack(side=LEFT) sigFrame.pack(side=TOP, expand=YES, fill=X) galDiffFrame = Frame(self.win) l4 = Label(galDiffFrame, text="Galactic Diffuse Model File:", width=labelWidth, anchor=E) l4.pack(side=LEFT) self._galDiffFileField = Pmw.EntryField( galDiffFrame, value=FERMI_DIR + "/refdata/fermi/galdiffuse/gll_iem_v06.fits") self._galDiffFileField.pack(side=LEFT, expand=YES, fill=X) b4 = Button(galDiffFrame, text="Browse...", command=(lambda: self._getFile(self._galDiffFileField))) b4.pack(side=LEFT) galDiffFrame.pack(side=TOP, expand=YES, fill=X) gdModelFrame = Frame(self.win) l5 = Label(gdModelFrame, text="Galactic Diffuse Model Name:", width=labelWidth, anchor=E) l5.pack(side=LEFT) self._gdModelNameField = Pmw.EntryField(gdModelFrame, value="GAL_v06") self._gdModelNameField.pack(side=LEFT) gdModelFrame.pack(side=TOP, expand=YES, fill=X) isoTempFrame = Frame(self.win) l6 = Label(isoTempFrame, text="Isotropic Template File:", width=labelWidth, anchor=E) l6.pack(side=LEFT) self._isoTempFileField = Pmw.EntryField( isoTempFrame, value=FERMI_DIR + "/refdata/fermi/galdiffuse/isotrop_4years_P7_v9_repro_source_v1.txt" ) self._isoTempFileField.pack(side=LEFT, expand=YES, fill=X) b6 = Button(isoTempFrame, text="Browse...", command=(lambda: self._getFile(self._isoTempFileField))) b6.pack(side=LEFT) isoTempFrame.pack(side=TOP, expand=YES, fill=X) itNameFrame = Frame(self.win) l7 = Label(itNameFrame, text="Isotropic Template Name:", width=labelWidth, anchor=E) l7.pack(side=LEFT) self._isoTempNameField = Pmw.EntryField(itNameFrame, value="Extragalactic Diffuse") self._isoTempNameField.pack(side=LEFT) itNameFrame.pack(side=TOP, expand=YES, fill=X) radFrame = Frame(self.win) l8 = Label(radFrame, text="Variable Source Radius:", width=labelWidth, anchor=E) l8.pack(side=LEFT) self._radLimitField = Pmw.EntryField(radFrame, value=-1) self._radLimitField.pack(side=LEFT) radFrame.pack(side=TOP, expand=YES, fill=X) extTempFrame = Frame(self.win) self.l9 = Label(extTempFrame, text="Extended Source Template Directory:", width=labelWidth, anchor=E, state=DISABLED) self.l9.pack(side=LEFT) self._extTempFileField = Pmw.EntryField(extTempFrame, value="", entry_state=DISABLED) self._extTempFileField.pack(side=LEFT, expand=YES, fill=X) self.b7 = Button( extTempFrame, text="Browse...", command=(lambda: self._getDir(self._extTempFileField)), state=DISABLED) self.b7.pack(side=LEFT) psFrame = Frame(self.win) l10 = Label(psFrame, text="Force Point Sources ", width=labelWidth, anchor=E) l10.pack(side=LEFT) self._psFlagField = Pmw.RadioSelect( psFrame, buttontype='radiobutton', command=self._checkForcePointSource) self._psFlagField.pack(side=LEFT) self._psFlagField.add('Yes') self._psFlagField.add('No') self._psFlagField.invoke('No') psFrame.pack(side=TOP, expand=YES, fill=X) extTempFrame.pack(side=TOP, expand=YES, fill=X) buttonFrame = Frame(self.win, pady=5) b10 = Button(buttonFrame, text="Cancel", command=(lambda: self._cancel())) b10.pack(side=LEFT) b8 = Button(buttonFrame, text="Reset Fields", command=(lambda: self._resetFields())) b8.pack(side=LEFT) b9 = Button(buttonFrame, text="Import Sources", command=(lambda: self._importSources())) b9.pack(side=RIGHT) buttonFrame.pack(side=TOP, expand=YES, fill=X) def _checkForcePointSource(self, tag): if ("Yes" == tag): self.l9.config(state=ACTIVE) self.b7.config(state=ACTIVE) self._extTempFileField.configure(entry_state=NORMAL) else: self.l9.config(state=DISABLED) self.b7.config(state=DISABLED) self._extTempFileField.configure(entry_state=DISABLED) def _cancel(self): """Cancels the dialog Paramters: - self - This AddCatalogSources Dialog object Return value: - none Description: This method simply sets the self.values variable to a None object to signify that no action was taken and then destroys the dialog window causing the getData() method to return the None object to the caller. """ self.values = None self.win.withdraw() self.win.quit() def _getFile(self, e): """Fill filename field using Open File dialog Parameters: - self - This AddCatalogSourcesDialog object - e - The EntryField object to store the filename in Return value: - none Description: This method uses the standard Tkinter Open File dialog to allow the user to select a file name to associate with the passed in entry field. If the user selects a file, it is store in the field. If not file is selected, the entry field is not updated. """ f = e.getvalue() if ("" == f): d = "." else: d = dirname(f) filename = askopenfilename(initialfile=f, initialdir=d) if (() != filename): e.setvalue(filename) def _getDir(self, e): """Fill directory name using Open Directory dialog Parameters: - self - This AddCatalogSourcesDialog object - e - The EntryField object to store the directory in Return value: - none Description: This method uses the standard Tkinter Open File dialog to allow the user to select a file name to associate with the passed in entry field. If the user selects a file, it is store in the field. If not file is selected, the entry field is not updated. """ d = e.getvalue() if ("" == d): d = "." dirName = askdirectory(initialdir=d) if (() != dirName): e.setvalue(dirName) def _resetFields(self): """Resets all the user field values Parameters: - self - This AddCatalogSourcesDialog object Return value: - none Description: This method clears all user input and resets them to their default values. This method is the click handler for the "Reset Fields" button on the dialog box and is invoked when the button is pressed. """ self._catalogFileField.setvalue("") self._eventFileField.setvalue("") self._sigLimitField.setvalue(4) self._galDiffFileField.setvalue( FERMI_DIR + "/refdata/fermi/galdiffuse/gll_iem_v06.fits") self._gdModelNameField.setvalue("GAL_v06") self._isoTempFileField.setvalue( FERMI_DIR + "/refdata/fermi/galdiffuse/isotrop_4years_P7_v9_repro_source_v1.txt" ) self._isoTempNameField.setvalue("Extragalactic Diffuse") self._radLimitField.setvalue(-1) self._psFlagField.invoke('No') self._extTempFileField.setvalue("") def _importSources(self): """Prepares data for return to calling program Parameters: - self - This AddCatalogSourcesDialog object Return value: - none Description: This method reads the values of all the entry fields in the dialog and stores their values in the internal data dictionary. It also validates the entries to see that 1) files exist and 2) other entries make sense. Validation is limited, however, and relies on upstream checking of data before final use. Once the data is stored, this method closes the dialog box allowing the data to be returned. This method is the click handler for the "Import Sources" button. """ # Validate entries to make sure the files at least exist. This should # only be a problem if the user typed in the entry instead of using the # file browser. validCF = isfile(self._catalogFileField.getvalue()) validEF = isfile(self._eventFileField.getvalue()) validGF = isfile(self._galDiffFileField.getvalue()) or ( "" == self._galDiffFileField.getvalue()) #these are optional validIF = isfile(self._isoTempFileField.getvalue()) or ( "" == self._isoTempFileField.getvalue()) validETD = not (not isdir(self._extTempFileField.getvalue()) and ("Yes" == self._psFlagField.getvalue())) if (validCF and validEF and validGF and validIF): # They are all good so load up the values and return self.values["catalogFile"] = self._catalogFileField.getvalue() self.values["eventFile"] = self._eventFileField.getvalue() self.values["sigLimit"] = self._sigLimitField.getvalue() self.values["galDiffFile"] = self._galDiffFileField.getvalue() self.values["gdModelName"] = self._gdModelNameField.getvalue() self.values["isoTempFile"] = self._isoTempFileField.getvalue() self.values["isTempName"] = self._isoTempNameField.getvalue() self.values["radiusLimit"] = self._radLimitField.getvalue() flag = self._psFlagField.getvalue() if ('Yes' == flag): self.values["forcePointSource"] = True else: self.values["forcePointSource"] = False self.values["extTempDir"] = self._extTempFileField.getvalue() self.win.withdraw() self.win.quit() else: msg = "The files listed in the following fields do not exist. Please correct them.\n\n" if (not validCF): msg += "Source Catalog File\n" if (not validEF): msg += "Event File\n" if (not validGF): msg += "Galactic Diffuse Model File\n" if (not validIF): msg += "Isotropic Template File\n" if (not validETD): msg += "Extended Source Template Directory\n" Pmw.MessageDialog(self.win, message_text=msg) def getData(self): """Public method to invoke the dialog Parameters: - self - This AddCatalogSourcesDialog object Return value: - self.values - a dictionary containing all the user entered (or default) values for the parameters needed to import sources from the Fermi LAT catalogs into the current model. Description: This method invokes the _draw() method to create the dialog box, starts it running, and returns the data values once the dialog is closed. """ self._draw() self.win.mainloop() return self.values
class TraceGui(object): def __init__(self, trace_complete_callback=None): self._trace_results_callback = trace_complete_callback self._flow_entries_container = None self._root = Toplevel() self._root.title('FlowEntry Trace') self._root.minsize(width=300, height=350) #self._root.geometry('%dx%d+%d+%d'%(900, 700, 120, 120)) # widthxheight+x+y self._top_frame = Frame(self._root) self._top_frame.pack(side=TOP, fill=X, padx=10, pady=10) # TODO for now these label names have to be exactly the same as the FlowEntryMatch object properties # consider either using the property values, or setting the FlowEntryMatch objects in _trace_callback() # differently. This way is kind-of a hack # The text labels label_entry_frame = Frame(self._top_frame) label_entry_frame.pack(side=TOP, anchor=W, pady=5) self._in_port_label = LabelEntry(label_entry_frame, 'in_port') self._dl_src_label = LabelEntry(label_entry_frame, 'dl_src') self._dl_dst_label = LabelEntry(label_entry_frame, 'dl_dst') self._dl_type_label = LabelOption(label_entry_frame, 'dl_type', 'empty', 'empty', 'ARP', 'IP', 'RARP') self._vlan_vid_label = LabelEntry(label_entry_frame, 'dl_vlan') self._vlan_pcp_label = LabelEntry(label_entry_frame, 'dl_vlan_pcp') self._nw_src_label = LabelEntry(label_entry_frame, 'nw_src') self._nw_dst_label = LabelEntry(label_entry_frame, 'nw_dst') self._nw_tos_label = LabelEntry(label_entry_frame, 'nw_tos') self._nw_proto_label = LabelOption(label_entry_frame, 'nw_proto', 'empty', 'empty', 'ICMP', 'SCTP', 'TCP', 'UDP') self._tp_src_label = LabelEntry(label_entry_frame, 'tp_src') self._tp_dst_label = LabelEntry(label_entry_frame, 'tp_dst') # This list is used when clearing the label entries self._label_entries = [self._in_port_label, self._dl_src_label, self._dl_dst_label, self._dl_type_label, self._vlan_vid_label, self._vlan_pcp_label, self._nw_src_label, self._nw_dst_label, self._nw_tos_label, self._nw_proto_label, self._tp_src_label, self._tp_dst_label] ''' check_frame = Frame(self._top_frame) check_frame.pack(side=TOP, anchor=W, pady=5) self._trace_display_label = LabelBase(check_frame, 'Trace display', width=18) radio_vals = ['FlowEntry list highlighting', 'seperate window'] self._radio_trace_display = Radios(check_frame, radio_vals) ''' # the buttons button_frame = Frame(self._top_frame, pady=5) button_frame.pack(side=BOTTOM, anchor=S) buttons_dict = OrderedDict([('trace', self._trace_callback), ('reset', self._reset_callback), ('cancel', self._cancel_callback)]) Buttons(button_frame, buttons_dict, button_orientation=LEFT) # Hide this window until its needed self._root.withdraw() # # The trace results window # self._trace_result = Toplevel() self._trace_result.title('FlowEntry Trace Results') self._trace_result.minsize(width=1200, height=700) self._trace_result.withdraw() # The trace results scrollable list list_frame = Frame(self._trace_result) list_frame.pack(side=TOP, expand=YES, fill=BOTH) self._trace_results_list = ScrolledList(list_frame) # The trace results close button result_button_frame = Frame(self._trace_result, padx=5) result_button_frame.pack(side=BOTTOM, anchor=S) Buttons(result_button_frame, {'close' : self._trace_result.withdraw}) def _trace_callback(self): # # Get the input specified in the Trace input window input_match_obj_list = [] for label_entry in self._label_entries: if len(label_entry.entry_text) > 0 and label_entry.entry_text != 'empty': match_object = FlowEntryFactory.get_match_object(label_entry.label_text, label_entry.entry_text) #print '\t%s' % match_object input_match_obj_list.append(match_object) # # Do the tracing flow_tracer = FlowTracer(self._flow_entries_container, input_match_obj_list) # returns a dictionary of MatchedFlowEntry to (next_table, drop, output, next_input_matches) matched_flow_entries = flow_tracer.trace() # # Open the self._trace_result window to display the results self._trace_results_list.clear() if len(matched_flow_entries) < 1: Popup("No tracing matches found") return for (matched_flow_entry, results) in matched_flow_entries.iteritems(): if matched_flow_entry.table_ < 0: # No match was found self._trace_results_list.append_list_entry('') self._trace_results_list.append_list_entry('No Match was found in table %s' % results[0]) next_action = 'Drop' else: self._trace_results_list.append_list_entry('') self._trace_results_list.append_list_entry('Match found in table %s' % matched_flow_entry.table_) self._trace_results_list.append_list_entry(' Flow Entry [%s]' % matched_flow_entry) self._trace_results_list.append_list_entry(' Resulting Flow Entry Matches [%d]' % len(results[3])) for r in results[3]: self._trace_results_list.append_list_entry(' [%s]' % r) if results[1]: next_action = 'Drop' elif results[2]: next_action = 'Output: %s' % results[2] else: next_action = 'Goto Table %s' % results[0] self._trace_results_list.append_list_entry(' Resulting Action: [%s]' % next_action); # Now display the window self._trace_result.update() self._trace_result.deiconify() # # This will call the root gui to display matched flow entries if self._trace_results_callback: self._trace_results_callback(matched_flow_entries) def _reset_callback(self): # Reset all of the fields for label_entry in self._label_entries: label_entry.clear_entry() def _cancel_callback(self): self.display(False) def display(self, show=True): if show: self._root.update() self._root.deiconify() else: self._root.withdraw() def set_flow_entries_container(self, fe_container): self._flow_entries_container = fe_container flow_entries_conatiner = property(fset=set_flow_entries_container)
class EmbeddedMolViewer: def __init__(self, target=None, # Tk container name = 'Embedded camera', debug = 0, ): self.debug = debug if self.debug: print "EmbeddedMolViewer __init__> ", target self.target = target self.PMV_win = Toplevel() self.PMV_win.withdraw() VFGUI.hasDnD2 = False print "\n==========================================" print " Initializing PMV..." self.mv = MoleculeViewer(logMode = 'overwrite', master=self.PMV_win, # customizer='custom_pmvrc', title='[embedded viewer]', withShell=False, verbose=False, gui = True, guiVisible=1) self.VIEWER = self.mv.GUI.VIEWER self.GUI = self.mv.GUI self.VIEWER.cameras[0].suspendRedraw = 1 # stop updating the main Pmv camera self._pmv_visible = False self.cameras = {} # 'name' {'obj' : pmv_obj, 'structures': [mol1_obj, mol2_obj, ....], } self.cameras['pmv'] = { 'obj' :self.VIEWER.cameras[0], 'structures' : [], } self.cameraslist = ['pmv'] # name0, name1, name2 # keep the order in which cameras are added self.target = target print " [ DONE ]" print "==========================================\n" self.initStyles() if self.target: self.addCamera(target = self.targer, name=name) def initStyles(self): """ initialize styles dictionary """ #color_cb = CallbackFunction(self.mv.colorByAtomType, (['lines', 'balls', 'sticks'], log=0) ) #self.styles ={ 'default' : [ color_cb ] } # XXX WHAT TO DO? pass def togglepmv(self, event=None): """ toggle between visible and hidden pmv""" if self._pmv_visible: self._hidePmv() else: self._showPmv() def _showPmv(self, event=None): """ stop all cams and restore the underlying pmv session """ if self.debug: print "_showPmv> called" print "ACTIVE CAMS", self.activeCams() self._pmv_suspended_cams = self.activeCams() self.activateCam(['pmv'], only=1, mols=True) self._pmv_visible = True self.mv.GUI.ROOT.deiconify() def _hidePmv(self, event=None): """ stop Pmv camera, minimize Pmv and restore previously disabled cams """ self.VIEWER.cameras[0].suspendRedraw = 1 # stop updating the main Pmv camera self._pmv_visible = False self.mv.GUI.ROOT.withdraw() self.activateCam(self._pmv_suspended_cams, only=1, mols=True) def addCamera(self,target,name = '', depth=True, bgcolor=(0., 0., 0.)): """ add a new camera 'name' bound to 'target'""" if self.debug: print "adding another camera" if name in self.cameraslist: print "Camera [%s] already exist!", name return cam_obj = self.VIEWER.AddCamera(master=target) # the next ones will be added) if depth: cam_obj.fog.Set(enabled=1) cam_obj.backgroundColor = ( bgcolor + (1.0,) ) cam_obj.Redraw() self.cameraslist.append(name) self.cameras[name] = { 'obj':cam_obj, 'structures' : [] } return cam_obj def delCamera(self, idx=None, name=None, mols=True): """ delete camera by index or by name; by default all molecules loaded in a given camera are loaded """ if self.debug: print "delcamera", idx, name if idx == None and name == None: print "delete camera by name or by idx!" return if idx == 0 or len(self.VIEWER.cameras) == 1: print "cowardly refusing to delete the main Pmv camera...(returning)" return self.VIEWER.DeleteCamera(idx) name = self.cameraslist.pop(idx) if mols: for s in self.cameras[name]['structures']: self.mv.deleteMol(s) # delete all objects from this camera self.nukeCamMols(name) # delete camera del self.cameras[name] def activeCams(self): """ return list of active cameras""" active = [] #active = [ name for name in self.cameras.keys() if self.cameras[name]['obj'].suspendRedraw == 0 ] for c in self.cameras.keys(): if not self.cameras[c]['obj'].suspendRedraw: active.append(c) return active def cams(self): """ return the list of all camera names""" return self.cameras.keys() def cameraByName(self, name): #, attribute='obj'): """ retrieve camera object by name None, if camera doesn't exist """ cam = self.cameras.get(name, None) if not cam == None: return cam['obj'] else: return None def cameraStructures(self, name): """ return all mols loaded in this camera""" return self.cameras[name]['structures'] def activateCam(self, namelist=[], only=1, mols=True): """ activate redraw on selected camera and disabling (by default) other cameras """ # - reactivate this camera if self.debug: print "activatecam> namelist", namelist for c in self.cameras.keys(): if c in namelist: for s in self.cameras[c]['structures']: # XXX ASK MICHEL if isinstance(s, Molecule): s = s.geomContainer.geoms['master'] s.Set(visible=True) #,redraw=False) self.cameras[c]['obj'].Redraw() self.cameras[c]['obj'].suspendRedraw = 0 elif only: self.cameras[c]['obj'].suspendRedraw = 1 # hide molecules loaded in this camera for s in self.cameras[c]['structures']: if isinstance(s, Molecule): s = s.geomContainer.geoms['master'] s.Set(visible=False) #,redraw=False) def deactivateCam(self, namelist=[]): """ disable redraw update in cameras""" self.VIEWER.redrawLock.acquire() if len(namelist) == 0: namelist = self.cameras.keys() for c in namelist: self.cameras[c]['obj'].suspendRedraw = 1 self.VIEWER.redrawLock.release() def loadMolWithStyle(self, molfile, style='default'): """ load molecules with representation style """ mol = self.mv.readMolecule(molfile, modelsAs='conformations') return mol def loadInCamera(self, molfile, camera, style='default'): """ load molecule in selected camera and apply optional repr.style """ mol = self.loadMolWithStyle(molfile, style=style)[0] self.cameras[camera]['structures'].append(mol) return mol def deleteInCamera(self, molobj, camera): """ delete an object from a camera""" m = """ ####################################### ### ### ### PROBLEMATIC DELETION! ASK MICHEL ### ISSUE WITH DELETING FILES ### ### #######################################""" #print m #print "LIST OF STRUCTURES", self.cameras[camera]['structures'] self.mv.deleteMol(molobj) self.cameras[camera]['structures'] = [ x for x in self.cameras[camera]['structures'] if not x == molobj ] return idx = self.cameras[camera]['structures'].index(molobj) d = self.cameras[camera]['structures'].pop(idx) try: self.mv.deleteMol(d) except: print "TRYING TO DELETE MOLECULE %s RAISED ERROR!" % d def nukeCamMols(self, camera): """ delete all molecules from a cam""" for m in self.cameras[camera]['structures']: self.mv.deleteMol(m) self.cameras[camera]['structures'] = [] def centerView(self, item=None): """ center the view on specified target if target is None, reset the view on all mols """ root = self.VIEWER.rootObject if item == None: item = root self.VIEWER.toggleTransformRootOnly(False) self.VIEWER.SetCurrentObject(item) #self.VIEWER.Reset_cb() self.VIEWER.Normalize_cb() self.VIEWER.toggleTransformRootOnly(True) self.VIEWER.Center_cb() self.VIEWER.SetCurrentObject(root)
class SkyglowEstimationToolbox: """Main class that establishes GUI.""" def __init__(self, root): self.root = root # Radio action buttons self.action = None self.sgmap_single_btn, self.krn_lib_btn, self.multi_map_btn = None, None, None self.file_log_var = StringVar() self.csv_file_var = StringVar() self.krn_folder_var = StringVar() self.output_folder_var = StringVar() self.sgmap_folder_var = StringVar() self.krn_ent_var = StringVar() self.krn_var, self.hem_var = IntVar(), IntVar() self.img, self.cdiag = None, None self.lat_lbl, self.lat_entry = None, None self.k_lbl, self.k_entry = None, None self.zen_lbl, self.zen_entry = None, None self.azi_lbl, self.azi_entry = None, None self.krn_lvl, self.krn_entry, self.krn_btn = None, None, None self.txt_redir, self.prg_log = None, None self.map_btn, self.gen_krn_btn = None, None # Sets window title, size, and icon on screen. self.root.title("Skyglow Estimation Toolbox (SET)") self.root.geometry('%dx%d+%d+%d' % (constants.SW * 0.75, constants.SH * 0.75, 25, 25)) self.root.iconbitmap(os.path.join(os.getcwd(), constants.ICO)) self.root.resizable(False, False) self.root.update_idletasks() # Creates three paned windows for the main screen. base = PanedWindow() base.pack(fill=BOTH, expand=1) sub1 = PanedWindow(base, orient=VERTICAL, height=self.root.winfo_height() * 3 / 4) base.add(sub1) sub2 = PanedWindow(sub1, orient=HORIZONTAL, height=self.root.winfo_height() / 5) sub1.add(sub2) # Creates frame for holding inputs. self.input_frame = Frame(sub2) sub2.add(self.input_frame) # Creates frame for bottom half of main screen. self.img_frame = Frame(sub1, bd=2, bg='white', relief="sunken") sub1.add(self.img_frame) # Creates canvas for displaying images. self.img_canvas = Canvas(self.img_frame, bd=2, relief="groove", width=constants.SW * 0.6, height=self.root.winfo_height() * 3 / 4 * 0.9) self.img_canvas.place(relx=.5, rely=.5, anchor=CENTER) # Creates help button for link to documentation, instructions, and about. self.help_btn = Menubutton(self.input_frame, text="Help", relief="raised", bd=2, width=8, pady=1) #self.help_btn.place(relx=1, rely=0, anchor=NE) self.help_btn.grid(column=4, columnspan=1, row=0) self.help_btn_menu = Menu(self.help_btn, tearoff=0) doc = 'https://github.com/NASA-DEVELOP' self.help_btn_menu.add_command(label="Documentation", command=lambda: self.open_url(doc)) self.help_btn_menu.add_command(label="Instructions", command=self.instructions) self.help_btn_menu.add_separator() self.help_btn_menu.add_command(label="About", command=self.about) self.help_btn["menu"] = self.help_btn_menu def main_screen(self): """Set up input GUI and image display screen.""" self.action = IntVar() btn_width = int(constants.SW / 60) file_width = int(constants.SW / 18) lbl_width = int(constants.SW / 60) gen_width = int(constants.SW / 42) radio_font = Font(family='TkDefaultFont', size=12) self.sgmap_single_btn = Radiobutton( self.input_frame, text="Generate Artificial Skyglow Map", font=radio_font, width=btn_width, variable=self.action, value='sng', command=self.sng_popup) self.krn_lib_btn = Radiobutton(self.input_frame, text="Generate Kernel Library", font=radio_font, width=btn_width, variable=self.action, value='krn', command=self.krn_popup) self.multi_map_btn = Radiobutton( self.input_frame, text="Generate Maps from Multiple Kernels", font=radio_font, width=btn_width, variable=self.action, value='mul', command=self.mul_popup) self.hem_map_btn = Radiobutton( self.input_frame, text="Generate Hemispherical Visualization", font=radio_font, width=btn_width, variable=self.action, value='hem', command=self.hem_popup) #Place widget self.sgmap_single_btn.grid(column=0, columnspan=1, row=0) self.krn_lib_btn.grid(column=1, columnspan=1, row=0) self.multi_map_btn.grid(column=2, columnspan=1, row=0) self.hem_map_btn.grid(column=3, columnspan=1, row=0) # VIIRS Image Reference File self.file_lbl = Label(self.input_frame, text="Image File:", width=lbl_width, anchor=E) self.file_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.file_log_var) self.browse_btn = Button(self.input_frame, text="Browse", command=self.import_viirs) # Angles CSV File self.csv_file_lbl = Label(self.input_frame, text="Angles CSV File:", width=lbl_width, anchor=E) self.csv_file_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.csv_file_var) self.csv_browse_btn = Button(self.input_frame, text="Browse", command=self.import_csv) # Multiple Maps form Kernel library self.mul_file_lbl = Label(self.input_frame, text="Kernel Folder:", width=lbl_width, anchor=E) self.mul_file_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.krn_folder_var) self.mul_browse_btn = Button(self.input_frame, text="Browse", command=self.import_krn_folder) # MultiKrn Map Output Location self.output_lbl = Label(self.input_frame, text="Output Location:", width=lbl_width, anchor=E) self.output_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.output_folder_var) self.output_btn = Button(self.input_frame, text="Browse", command=self.import_out_folder) # Hemisphere Output Location self.sgmap_folder_lbl = Label(self.input_frame, text="Skyglow Map Location:", width=lbl_width, anchor=E) self.sgmap_folder_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.sgmap_folder_var) self.sgmap_folder_btn = Button(self.input_frame, text="Browse", command=self.import_sgmap_folder) # Import Kernel Checkbutton self.check_lbl = Label(self.input_frame, text="Import Kernel:", width=lbl_width, anchor=E) self.krn_chk = Checkbutton(self.input_frame, anchor=W, variable=self.krn_var, command=self.checkbtn_val) self.hem_chk_lbl = Label(self.input_frame, text="Generate kernels for hemisphere:", width=lbl_width, anchor=E) self.hem_chk = Checkbutton(self.input_frame, anchor=W, variable=self.hem_var) # Region Latitude (deg), Grand Teton National park = 43.7904 degrees N self.lat_lbl = Label(self.input_frame, text="Latitude (deg):", width=lbl_width, anchor=E) self.lat_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") self.lon_lbl = Label(self.input_frame, text="Longitude (deg):", width=lbl_width, anchor=E) self.lon_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") # Atmospheric Clarity Parameter, REF 2, Eq. 12, p. 645 self.k_lbl = Label(self.input_frame, text="Atmospheric Clarity Parameter:", width=btn_width, anchor=E) self.k_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") # Zenith angle (deg), z, REF 2, Fig. 6, p.648 self.zen_lbl = Label(self.input_frame, text="Zenith Angle (deg):", width=lbl_width, anchor=E) self.zen_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") # Azimuth angle (deg) self.azi_lbl = Label(self.input_frame, text="Azimuth Angle (deg):", width=lbl_width, anchor=E) self.azi_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") self.krn_lbl = Label(self.input_frame, text="Kernel File:", width=lbl_width, anchor=E) self.krn_ent = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.krn_ent_var) self.krn_btn = Button(self.input_frame, text="Browse", command=self.import_krn) # Generate Artificial Skyglow Map Button self.map_btn = Button(self.input_frame, text="Generate Artificial Skyglow Map", width=gen_width, command=self.generate_map) # Generate Kernal library button for SET self.gen_krn_btn = Button(self.input_frame, text="Generate Kernel Library", width=gen_width, command=self.generate_krn) # Generate Map of Multiple Kernals(word better later on) self.mul_map_btn = Button(self.input_frame, text="Generate Maps from Multiple Kernels", width=gen_width, command=self.generate_mmap) # Generate Hemispherical Visualization Display of Skyglow self.hem_gen_btn = Button(self.input_frame, text="Generate Hemisphere", width=gen_width, command=self.generate_hem) def import_viirs(self): """Import a VIIRS DNB file.""" # Allows user to search through his directory for VIIRS Image file. file_types = [('TIFF Files', '*.tif'), ('All files', '*')] file_name = filedialog.askopenfilename(initialdir='/', title="Select file", filetypes=file_types) self.file_log_var.set(file_name) # Checks to see if file is empty. If not, displays image on canvas. if file_name != '': pilimg = Image.open(file_name) pilimg_width, pilimg_height = pilimg.size pilimg.tile = [ t for t in pilimg.tile if t[1][2] < pilimg_width and t[1][3] < pilimg_height ] canvas_size = (self.img_canvas.winfo_width(), self.img_canvas.winfo_height()) pilimg_r = pilimg.resize(canvas_size, Image.ANTIALIAS) pilimg_col = ImageOps.colorize(ImageOps.grayscale(pilimg_r), (0, 0, 0), (255, 255, 255)) pilimg_cont = ImageOps.autocontrast(pilimg_col, cutoff=.4, ignore=None) self.img = ImageTk.PhotoImage(pilimg_cont) self.img_canvas.create_image(canvas_size[0] / 2, canvas_size[1] / 2, image=self.img) else: print('File is empty.') def import_csv(self): """Import CSV file.""" file_types = [('CSV Files', '*.csv'), ('All files', '*')] file_name = filedialog.askopenfilename(initialdir='/', title="Select file", filetypes=file_types) self.csv_file_var.set(file_name) if file_name is '': print('File is empty.') def import_krn_folder(self): """Import kernel folder.""" krn_dir = filedialog.askdirectory(initialdir='/', title="Select kernel folder") self.krn_folder_var.set(krn_dir) if krn_dir is '': print('Directory is empty.') def import_out_folder(self): """Import skyglow output folder.""" output_dir = filedialog.askdirectory(initialdir='/', title="Select output folder") self.output_folder_var.set(output_dir) if output_dir is '': print('Directory is empty.') def import_krn(self): """Import existing kernel tif.""" file_types = [('TIFF Files', '*.tif'), ('All files', '*')] file_name = filedialog.askopenfilename(initialdir='/', title="Select file", filetypes=file_types) self.krn_ent_var.set(file_name) def import_sgmap_folder(self): """Import skyglow map folder for hemisphere building.""" sgmap_dir = filedialog.askdirectory(initialdir='/', title="Select skyglow map folder") self.sgmap_folder_var.set(sgmap_dir) if sgmap_dir is '': print('Directory is empty.') def sng_popup(self): """Single map tab.""" self.remove_all() self.check_lbl.grid(column=0, row=2) self.krn_chk.place(relx=.22, rely=.41, anchor=CENTER) self.file_lbl.grid(column=0, row=1) self.file_log.grid(column=1, columnspan=3, row=1) self.browse_btn.grid(column=4, row=1, sticky=W, padx=3) self.lat_lbl.grid(column=0, row=3) self.lat_entry.grid(column=1, row=3) self.k_lbl.grid(column=2, row=3) self.k_entry.grid(column=3, row=3) self.zen_lbl.grid(column=0, row=4) self.zen_entry.grid(column=1, row=4) self.azi_lbl.grid(column=2, row=4) self.azi_entry.grid(column=3, row=4) self.map_btn.grid(column=1, columnspan=3, row=5, sticky=N + S + E + W) def krn_popup(self): """Kernel lib tab.""" self.remove_all() # latitude self.lat_lbl.grid(column=0, row=3) self.lat_entry.grid(column=1, row=3) # atmospheric clarity self.k_lbl.grid(column=2, row=3) self.k_entry.grid(column=3, row=3) # angles file self.csv_file_lbl.grid(column=0, row=1) self.csv_file_log.grid(column=1, columnspan=3, row=1) self.csv_browse_btn.grid(column=4, row=1, sticky=W, padx=3) # input VIIRS image self.file_lbl.grid(column=0, row=2) self.file_log.grid(column=1, columnspan=3, row=2) self.browse_btn.grid(column=4, row=2, sticky=W, padx=3) self.hem_chk_lbl.grid(column=0, row=4) self.hem_chk.place(relx=.21, rely=.69) self.gen_krn_btn.grid(column=1, columnspan=3, row=5, sticky=N + S + E + W) def mul_popup(self): """Multiple maps tab.""" self.remove_all() # Kernel folder location self.mul_file_lbl.grid(column=0, row=1) self.mul_file_log.grid(column=1, columnspan=3, row=1) self.mul_browse_btn.grid(column=4, row=1, sticky=W, padx=3) # input VIIRS image self.file_lbl.grid(column=0, row=2) self.file_log.grid(column=1, columnspan=3, row=2) self.browse_btn.grid(column=4, row=2, sticky=W, padx=3) # Choose output location self.output_lbl.grid(column=0, row=3) self.output_log.grid(column=1, columnspan=3, row=3) self.output_btn.grid(column=4, row=3, sticky=W, padx=3) # Generate map from kernel folder self.mul_map_btn.grid(column=1, columnspan=3, row=4, sticky=N + S + E + W) def hem_popup(self): """Hemisphere tab.""" self.remove_all() # Skyglow Map Folder self.sgmap_folder_lbl.grid(column=0, row=1) self.sgmap_folder_log.grid(column=1, columnspan=3, row=1) self.sgmap_folder_btn.grid(column=4, row=1, sticky=W, padx=3) # Latitude entry self.lat_lbl.grid(column=0, row=3) self.lat_entry.grid(column=1, row=3) # Longitude entry self.lon_lbl.grid(column=2, row=3) self.lon_entry.grid(column=3, row=3) # Generate Hemispherical Visualization button self.hem_gen_btn.grid(column=1, columnspan=3, row=4, sticky=N + S + E + W) def remove_all(self): """Remove all existing GUI elements before opening new tab.""" self.check_lbl.grid_remove() self.krn_chk.place_forget() self.hem_chk.place_forget() self.hem_chk_lbl.grid_remove() self.file_lbl.grid_remove() self.file_log.grid_remove() self.browse_btn.grid_remove() self.krn_lbl.grid_remove() self.krn_ent.grid_remove() self.krn_btn.grid_remove() self.lat_lbl.grid_remove() self.lat_entry.grid_remove() self.k_lbl.grid_remove() self.k_entry.grid_remove() self.zen_lbl.grid_remove() self.zen_entry.grid_remove() self.azi_lbl.grid_remove() self.azi_entry.grid_remove() self.map_btn.grid_remove() self.gen_krn_btn.grid_remove() self.mul_map_btn.grid_remove() self.csv_file_lbl.grid_remove() self.csv_file_log.grid_remove() self.csv_browse_btn.grid_remove() self.mul_file_lbl.grid_remove() self.mul_file_log.grid_remove() self.mul_browse_btn.grid_remove() self.output_lbl.grid_remove() self.output_log.grid_remove() self.output_btn.grid_remove() self.hem_gen_btn.grid_remove() self.lat_lbl.grid_remove() self.lat_entry.grid_remove() self.lon_lbl.grid_remove() self.lon_entry.grid_remove() self.sgmap_folder_lbl.grid_remove() self.sgmap_folder_log.grid_remove() self.sgmap_folder_btn.grid_remove() def checkbtn_val(self): """Change interface based on if Import Kernel button is checked.""" # Import Kernel File widgets when Kernel Checkbutton is marked. if self.krn_var.get(): self.lat_lbl.grid_remove() self.lat_entry.grid_remove() self.k_lbl.grid_remove() self.k_entry.grid_remove() self.zen_lbl.grid_remove() self.zen_entry.grid_remove() self.azi_lbl.grid_remove() self.azi_entry.grid_remove() self.krn_lbl.grid(column=0, row=2) self.krn_ent.grid(column=1, columnspan=3, row=2) self.krn_btn.grid(column=4, row=2, sticky=W, padx=3) self.krn_chk.place_forget() self.krn_chk.place(relx=0.19, rely=.5) # Input parameter widgets when Kernel Checkbuttton is unmarked else: self.krn_lbl.grid_remove() self.krn_ent.grid_remove() self.krn_btn.grid_remove() self.lat_lbl.grid(column=0, row=3) self.lat_entry.grid(column=1, row=3) self.k_lbl.grid(column=2, row=3) self.k_entry.grid(column=3, row=3) self.zen_lbl.grid(column=0, row=4) self.zen_entry.grid(column=1, row=4) self.azi_lbl.grid(column=2, row=4) self.azi_entry.grid(column=3, row=4) self.krn_chk.place_forget() self.krn_chk.place(relx=0.22, rely=.41, anchor=CENTER) @staticmethod def open_url(url): """"Open a url""" webbrowser.open_new(url) def instructions(self): """Open instructions window.""" # Instantiates separate Toplevel instruction window. instr_window = Toplevel(self.root) instr_window.geometry('550x575+25+25') instr_window.title('Instructions') instr_window.wm_iconbitmap(constants.ICO) instr_window.resizable(False, False) # Creatse Scrollbar and Frame for containing other widgets. instr_scroll = Scrollbar(instr_window) instr_scroll.pack(fill=Y, side="right") instr_frame = Frame(instr_window, bg='white') instr_frame.pack(fill=BOTH, side="left") # Adds instruction text from constants and adds image of Cinzano's diagram. instr = Text(instr_frame, width=65, height=40, padx=10, pady=5, bd=0, wrap="word") instr.insert("end", constants.INSTR) cdiagram_file = Image.open("./static/cinzano_diagram.PNG") cdiagram_file = cdiagram_file.resize((500, 450), Image.ANTIALIAS) self.cdiag = ImageTk.PhotoImage(cdiagram_file) instr.image_create("end", image=self.cdiag) instr.tag_add("top", "1.0", "4.10") instr.tag_config("top", font='Times 12 bold') instr.tag_add("body", "5.0", "19.20") instr.tag_config("body", font='Times 12') instr.insert("end", constants.CDIAG) instr.pack() instr_scroll.config(command=instr.yview) def about(self): """Open an about window. Window gives authors, SET version number, and icon credit. """ # Instantiates a new Toplevel about window. about_window = Toplevel(self.root) about_window.geometry('350x335+25+25') about_window.title('About') about_window.wm_iconbitmap(constants.ICO) about_window.resizable(False, False) # Adds text to about window. about = Text(about_window, width=50, height=30, padx=10, pady=3) about.insert("end", constants.ABOUT) about.tag_add("abt", "1.0", "21.30") about.tag_config("abt", font='Times 10 bold', justify=CENTER) about.pack() def progress(self): """Construct a progress window to monitor darksky.""" # Instantiates a new Toplevel window and frame for progress bar and loading log. self.prg_window = Toplevel(self.root) self.prg_window.geometry('650x325+250+250') self.prg_window.title('Generating Artificial Skyglow Map...') self.prg_window.iconbitmap(constants.ICO) self.prg_window.resizable(False, False) prg_frame = Frame(self.prg_window) prg_frame.pack(fill=BOTH) # Creates Scrollbar, Progressbar, and Label for checking progress.. prg_scroll = Scrollbar(prg_frame) prg_scroll.pack(fill=Y, side="right") self.prg_bar = ttk.Progressbar(prg_frame, orient=HORIZONTAL, length=750, mode='indeterminate') self.prg_bar.pack() self.prg_bar.start() prg_lbl_txt = StringVar() prg_lbl = Label(prg_frame, textvariable=prg_lbl_txt) prg_lbl.pack() # Displays message log that prints from log file and starts darkskypy. self.prg_log = Text(prg_frame, width=90, padx=5, pady=5, relief="sunken") self.prg_log.pack() self.prg_log.insert( "end", "*****Progress Log*****\n=======================\n") self.prg_log.tag_add("abt", "1.0", "3.0") self.prg_log.tag_config("abt", font='Courier 12 bold', justify=CENTER) self.txt_redir = LogRedirector(self.prg_log) logger.addHandler(self.txt_redir) sys.stderr = StderrRedirector(self.prg_log) prg_lbl_txt.set("Start time: " + str(time.asctime())) self.no_progress = 0 def update_progress(self): """Update progress window to prevent it from freezing.""" self.prg_log.update() # if only one thread exists, stop progress bar and close window if len(threading.enumerate()) == 1: self.prg_bar.stop() self.no_progress += 1 if self.no_progress == 3: self.prg_window.withdraw() else: self.prg_bar.start() self.root.after(1000, self.update_progress) def generate_map(self): """Call darksky.sgmapper in background thread.""" # Acquires input arguments. lat_in, k_in, zen_in, azi_in, file_in, krn_file_in = 0, 0, 0, 0, '', '' if self.krn_var.get(): krn_file_in = self.krn_ent_var.get() else: lat_in = float(self.lat_entry.get()) k_in = float(self.k_entry.get()) zen_in = float(self.zen_entry.get()) azi_in = float(self.azi_entry.get()) file_in = self.file_log_var.get() self.progress() # Create new threads to run light propagation model simultaneously. p_thread = threading.Thread(target=self.update_progress()) t_thread = threading.Thread(target=darksky.sgmapper, args=(lat_in, k_in, zen_in, azi_in, file_in, krn_file_in)) t_thread.setDaemon(True) p_thread.start() t_thread.start() def generate_krn(self): """Start kernel generation in background threads.""" # Acquires input arguments csv_in, file_in, lat_in, k_in, hem = '', '', 0, 0, False csv_in = self.csv_file_var.get() file_in = self.file_log_var.get() lat_in = float(self.lat_entry.get()) k_in = float(self.k_entry.get()) hem = self.hem_var.get() self.progress() # Create new threads to run light propagation model simultaneously. p_thread = threading.Thread(target=self.update_progress()) with open(csv_in, "rb") as f: angle_list = loadtxt(f, delimiter=",", skiprows=1) p_thread.start() for angle_set in angle_list: t_thread = threading.Thread(target=darksky.generate_krn, args=(lat_in, k_in, angle_set[0], angle_set[1], file_in, hem)) t_thread.setDaemon(True) t_thread.start() def generate_mmap(self): """Start brightness map creation from kernels.""" # Acquires input arguments krn_folder_in, file_in, output_in, = '', '', '' krn_folder_in = self.krn_folder_var.get() file_in = self.file_log_var.get() output_in = self.output_folder_var.get() self.progress() # Create new threads to run light propagation model simultaneously. p_thread = threading.Thread(target=self.update_progress()) t_thread = threading.Thread(target=darksky.multisgmapper, args=(file_in, krn_folder_in, output_in)) t_thread.setDaemon(True) p_thread.start() t_thread.start() def generate_hem(self): """Generate hemisphere.""" sgmap_folder_in, lat_in, lon_in, = '', 0, 0 sgmap_folder_in = self.sgmap_folder_var.get() lat_in = float(self.lat_entry.get()) lon_in = float(self.lon_entry.get()) darksky.generate_hem(lat_in, lon_in, sgmap_folder_in)
epics['amp'] = 'FKC00V' epics['write_tau'] = cs_checkbox(lf_results, 3, 1, '', False) epics['tau'] = 'FKC01V' epics['write_tswa'] = cs_checkbox(lf_results, 5, 1, '', False) epics['tswa'] = 'FKC02V' class pv: fill = PV('CUMZR:MBcurrent') curt = PV('TOPUPCC:rdCurCS') ampl = PV(epics['amp']) tau = PV(epics['tau']) tswa = PV(epics['tswa']) popup = Toplevel(bg='') popup.overrideredirect(True) popup.withdraw() popupstr, popuplab = cp_label(popup, '', label_conf={'bg':'black', 'fg':'green', 'font':'Mono 15'}, pack_conf={'side':'right'}) def b2click(event, text): # get epics var name text = epics[text] # create popup displaying epics name popupstr.set(text) popup.update() w, h = popuplab.winfo_width() + 15, popuplab.winfo_height() x, y = root.winfo_pointerx(), root.winfo_pointery() popup.wm_geometry('{:d}x{:d}+{:d}+{:d}'.format(w, h, x, y))
class Tooltips: def __init__(self): self.descriptions = {} self.balloon = None self.balloon_label = None self.last_widget = '' self.after_id = None def AddDescription(self, widget, description): self.descriptions[widget._w] = description if widget._w == self.last_widget: self.balloon_label['text'] = description def RemoveDescription(self, widget): if type(widget) == InstanceType: widget = widget._w if self.descriptions.has_key(widget): del self.descriptions[widget] def GetDescription(self, widget): if type(widget) == InstanceType: widget = widget._w if self.descriptions.has_key(widget): return self.descriptions[widget] return '' def create_balloon(self, root): self.root = root self.balloon = Toplevel(self.root, name = 'tooltips') self.balloon.withdraw() self.balloon.overrideredirect(1) label = Label(self.balloon, name = 'label', text = 'Tooltip') label.pack() self.balloon_label = label def popup_balloon(self, widget_name, x, y, text): self.last_widget = widget_name self.balloon.withdraw() self.balloon_label['text'] = text x = x - self.balloon_label.winfo_reqwidth() / 2 self.balloon.geometry('%+d%+d' % (x, y)) self.balloon.update() self.balloon.deiconify() self.balloon.tkraise() def popup_delayed(self, widget_name, x, y, text, *args): self.after_id = None self.popup_balloon(widget_name, x, y, text) def enter_widget(self, widget_name): text = self.GetDescription(widget_name) if text: widget = self.root.nametowidget(widget_name) x = widget.winfo_rootx() + widget.winfo_width() / 2 y = widget.winfo_rooty() + widget.winfo_height() #y = y + height #x = x + width / 2 if self.after_id: print 'after_id in enter' self.root.after_cancel(self.after_id) self.after_id = self.root.after(config.preferences.tooltip_delay, self.popup_delayed, widget_name, x, y, text) def leave_widget(self, widget_name): global last_widget, after_id if self.after_id is not None: self.root.after_cancel(self.after_id) self.after_id = None self.last_widget = '' last_widget = '' self.balloon.withdraw() button_press = leave_widget def destroy_widget(self, event): self.RemoveDescription(event.widget)
class PypeTkPad(object): def __init__(self, master, queue, pypeOutput): self.queue = queue self.pypeOutput = pypeOutput self.master = master self.master.title('PypePad') self.master.geometry("%dx%d%+d%+d" % (700, 500, 0, 0)) self.master.minsize(300, 100) self.output_file_name = None self.BuildMainFrame() self.UpdateOutput() def NewCommand(self): self.ClearAllCommand() def OpenCommand(self): import tkFileDialog from Tkinter import END openfile = tkFileDialog.askopenfile() if not openfile: return for line in openfile.readlines(): self.text_input.insert(END, line) def SaveCommand(self): import tkFileDialog from Tkinter import END saveasfile = tkFileDialog.asksaveasfile() if not saveasfile: return alltext = self.text_input.get("1.0", END) saveasfile.write(alltext) def QuitCommand(self): self.master.quit() def ClearInputCommand(self): from Tkinter import END self.text_input.delete("1.0", END) def ClearOutputCommand(self): from Tkinter import NORMAL, END, DISABLED self.text_output["state"] = NORMAL self.text_output.delete("1.0", END) self.text_output["state"] = DISABLED self.text_output.see(END) self.text_output.update() def ClearAllCommand(self): self.ClearInputCommand() self.ClearOutputCommand() def OutputFileCommand(self): import tkFileDialog outputfilename = tkFileDialog.asksaveasfilename() if sys.platform == 'win32' and len(outputfilename.split()) > 1: outputfilename = '"%s"' % outputfilename self.output_file_name = outputfilename def AboutCommand(self): self.OutputText('\n') self.OutputText( '* PypePad, Copyright (c) Luca Antiga, David Steinman. *\n') self.OutputText('\n') def UpdateOutput(self): if self.pypeOutput: text = self.pypeOutput.pop(0) self.output_stream.write(text) self.master.after(10, self.UpdateOutput) def RunPype(self, arguments): if not arguments: return if self.output_to_file.get() is not 'n' and self.output_file_name: self.output_stream.output_to_file = True self.output_stream.output_file = open(self.output_file_name, self.output_to_file.get()) else: self.output_stream.output_to_file = False self.queue.append(arguments) def GetWordUnderCursor(self): from Tkinter import CURRENT splitindex = self.text_input.index(CURRENT).split('.') line = self.text_input.get(splitindex[0] + ".0", splitindex[0] + ".end") wordstart = line.rfind(' ', 0, int(splitindex[1]) - 1) + 1 wordend = line.find(' ', int(splitindex[1])) if wordend == -1: wordend = len(line) word = line[wordstart:wordend] return word def GetWordIndex(self): startindex = self.text_input.index("insert-1c wordstart") endindex = self.text_input.index("insert-1c wordend") if self.text_input.get(startindex + '-1c') == '-' and self.text_input.get( startindex + '-2c') == '-': startindex = self.text_input.index("insert-1c wordstart -2c") elif self.text_input.get(startindex + '-1c') == '-' and self.text_input.get( startindex + '-2c') == ' ': startindex = self.text_input.index("insert-1c wordstart -1c") self.wordIndex[0] = startindex self.wordIndex[1] = endindex word = self.text_input.get(self.wordIndex[0], self.wordIndex[1]) return word def GetLogicalLine(self, physicallineid): indexes, lines = self.GetLogicalLines() return lines[indexes[physicallineid]] def GetLogicalLineRange(self, physicallinefirstid, physicallinelastid): indexes, lines = self.GetLogicalLines() return lines[indexes[physicallinefirstid]:indexes[physicallinelastid] + 1] def GetAllLogicalLines(self): return self.GetLogicalLines()[1] def GetLogicalLines(self): from Tkinter import END physicallines = self.text_input.get("1.0", END).split('\n') lines = [] indexes = [0] * len(physicallines) lineid = 0 previousline = "" join = 0 for line in physicallines: if line.startswith('#'): if join: indexes[lineid] = indexes[lineid - 1] elif join: if line.endswith('\\'): lines[-1] = lines[-1] + " " + line[:-1] join = 1 else: lines[-1] = lines[-1] + " " + line join = 0 indexes[lineid] = indexes[lineid - 1] else: if line.endswith('\\'): join = 1 lines.append(line[:-1]) else: lines.append(line) join = 0 if lineid > 0: indexes[lineid] = indexes[lineid - 1] + 1 lineid += 1 return indexes, lines def GetLineUnderCursor(self): from Tkinter import INSERT currentlineid = int(self.text_input.index(INSERT).split('.')[0]) - 1 return self.GetLogicalLine(currentlineid) def RunAllCommand(self): lines = self.GetAllLogicalLines() for line in lines: if line and line.strip(): self.RunPype(line) def RunLineCommand(self): line = self.GetLineUnderCursor() if line and line.strip(): self.RunPype(line) def RunSelectionCommand(self): from Tkinter import TclError, SEL_FIRST, SEL_LAST try: firstlineid = int( self.text_input.index(SEL_FIRST).split('.')[0]) - 1 lastlineid = int(self.text_input.index(SEL_LAST).split('.')[0]) - 1 lines = self.GetLogicalLineRange(firstlineid, lastlineid) for line in lines: self.RunPype(line) except TclError: pass def GetSuggestionsList(self, word): list = [] try: exec('import vmtkscripts') except ImportError: return None if word.startswith('--'): list = ['--pipe', '--help'] elif word.startswith('-'): optionlist = [] scriptindex = self.text_input.search('vmtk', self.wordIndex[0], backwards=1) moduleName = self.text_input.get(scriptindex, scriptindex + ' wordend') try: exec('import ' + moduleName) exec('scriptObjectClassName = ' + moduleName + '.' + moduleName) exec('scriptObject = ' + moduleName + '.' + scriptObjectClassName + '()') members = scriptObject.InputMembers + scriptObject.OutputMembers for member in members: optionlist.append('-' + member.OptionName) exec( 'list = [option for option in optionlist if option.count(word)]' ) except: return list else: exec( 'list = [scriptname for scriptname in vmtkscripts.__all__ if scriptname.count(word) ]' ) return list def FillSuggestionsList(self, word): from Tkinter import END self.suggestionslist.delete(0, END) suggestions = self.GetSuggestionsList(word) for suggestion in suggestions: self.suggestionslist.insert(END, suggestion) def ReplaceTextCommand(self, word): self.text_input.delete(self.wordIndex[0], self.wordIndex[1]) self.text_input.insert(self.wordIndex[0], word) self.text_input.focus_set() def ShowHelpCommand(self): word = self.GetWordUnderCursor() self.OutputText(word) if word: self.RunPype(word + ' --help') else: self.OutputText('Enter your vmtk Pype above and Run.\n') def AutoCompleteCommand(self): word = self.GetWordIndex() self.suggestionswindow.withdraw() if word: self.FillSuggestionsList(word) self.suggestionswindow.geometry( "%dx%d%+d%+d" % (400, 150, self.text_output.winfo_rootx(), self.text_output.winfo_rooty())) self.suggestionswindow.deiconify() self.suggestionswindow.lift() def InsertScriptName(self, scriptname): from Tkinter import INSERT self.text_input.insert(INSERT, scriptname + ' ') def InsertFileName(self): from Tkinter import INSERT import tkFileDialog openfilename = tkFileDialog.askopenfilename() if not openfilename: return if len(openfilename.split()) > 1: openfilename = '"%s"' % openfilename self.text_input.insert(INSERT, openfilename + ' ') def KeyPressHandler(self, event): if event.keysym == "Tab": self.AutoCompleteCommand() self.suggestionslist.focus_set() self.suggestionslist.selection_set(0) return "break" else: self.text_input.focus_set() def TopKeyPressHandler(self, event): from Tkinter import ACTIVE, INSERT if event.keysym in ['Down', 'Up']: self.suggestionslist.focus_set() elif event.keysym == "Return": word = self.suggestionslist.get(ACTIVE) self.ReplaceTextCommand(word) self.suggestionswindow.withdraw() self.text_input.focus_set() elif len(event.keysym) == 1: self.suggestionswindow.withdraw() self.text_input.insert(INSERT, event.keysym) self.text_input.focus_set() else: self.suggestionswindow.withdraw() self.text_input.focus_set() def NewHandler(self, event): self.NewCommand() def OpenHandler(self, event): self.OpenCommand() def SaveHandler(self, event): self.SaveCommand() def InsertFileNameHandler(self, event): self.InsertFileName() return "break" def QuitHandler(self, event): self.QuitCommand() def ShowHelpHandler(self, event): self.ShowHelpCommand() def RunKeyboardHandler(self, event): from Tkinter import SEL_FIRST, TclError try: self.text_input.index(SEL_FIRST) self.RunSelectionCommand() except TclError: self.RunLineCommand() return "break" def RunAllHandler(self, event): self.RunAllCommand() def PopupHandler(self, event): try: self.popupmenu.tk_popup(event.x_root, event.y_root, 0) finally: self.popupmenu.grab_release() def OutputText(self, text): from Tkinter import NORMAL, END, DISABLED self.text_output["state"] = NORMAL self.text_output.insert(END, text) self.text_output["state"] = DISABLED def BuildScriptMenu(self, parentmenu, modulename): from Tkinter import Menu menu = Menu(parentmenu, bd=1, activeborderwidth=0) try: exec('import ' + modulename) except ImportError: return None scriptnames = [] exec('scriptnames = [scriptname for scriptname in ' + modulename + '.__all__]') menulength = 20 for i in range(len(scriptnames) / menulength + 1): subscriptnames = scriptnames[i * menulength:(i + 1) * menulength] if not subscriptnames: break submenu = Menu(menu, bd=1, activeborderwidth=0) menu.add_cascade(label=subscriptnames[0] + "...", menu=submenu) for scriptname in subscriptnames: callback = CallbackShim(self.InsertScriptName, scriptname) submenu.add_command(label=scriptname, command=callback) return menu 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)
class Tooltips: tooltip_delay = 100 def __init__(self): self.descriptions = {} self.balloon = None self.balloon_label = None self.last_widget = '' self.after_id = None self.root = None def AddDescription(self, widget, description): self.descriptions[widget._w] = description if widget._w == self.last_widget: self.balloon_label['text'] = description def RemoveDescription(self, widget): if type(widget) == InstanceType: widget = widget._w if self.descriptions.has_key(widget): del self.descriptions[widget] def GetDescription(self, widget): if type(widget) == InstanceType: widget = widget._w if self.descriptions.has_key(widget): return self.descriptions[widget] return '' def create_balloon(self, root): self.root = root self.balloon = Toplevel(self.root) self.balloon.withdraw() self.balloon.overrideredirect(1) self.balloon["relief"] = 'flat' label = TLabel(self.balloon, text='Tooltip', style='Tooltips') label.pack(ipadx=2, ipady=2) self.balloon_label = label def popup_balloon(self, widget_name, x, y, text): self.last_widget = widget_name self.balloon.withdraw() self.balloon_label['text'] = text width = self.balloon_label.winfo_reqwidth() height = self.balloon_label.winfo_reqheight() screenwidth = self.root.winfo_screenwidth() screenheight = self.root.winfo_screenheight() x = self.root.winfo_pointerx() y = self.root.winfo_pointery() + 20 if screenwidth < (x + width): x = x - width if screenheight < (y + height): y = y - height - 25 self.balloon.geometry('%+d%+d' % (x, y)) self.balloon.update() self.balloon.deiconify() self.balloon.tkraise() def popup_delayed(self, widget_name, x, y, text, *args): self.after_id = None self.popup_balloon(widget_name, x, y, text) def enter_widget(self, event): widget_name = event.widget text = self.GetDescription(widget_name) if text: x = event.x;y = event.y if self.after_id: print 'after_id in enter' self.root.after_cancel(self.after_id) self.after_id = self.root.after(self.tooltip_delay, self.popup_delayed, widget_name, x, y, text) def leave_widget(self, event): global last_widget, after_id if self.after_id is not None: self.root.after_cancel(self.after_id) self.after_id = None self.last_widget = '' last_widget = '' self.balloon.withdraw() button_press = leave_widget def destroy_widget(self, event): self.RemoveDescription(event.widget)