class waitWidget(Frame): # pylint: disable=R0924,R0904 """ A wait widget that shows something is happening. """ def __init__(self, queue, master): self.queue = queue Frame.__init__(self, master) self.pack(fill="both") self.focus_set() # get the focus self.grab_set() # make this window modal master.resizable(False, False) # not resizable master.title("") # no title # don't let user close window using X - instead call timer master.protocol("WM_DELETE_WINDOW", self.timer) self.wait = IntVar(master, 0, "wait") Label(master, bitmap="hourglass").pack(fill="both") Label(master, text="Please wait ...").pack(fill="both") Label(master, textvariable=self.wait).pack(fill="both") self.timer() def timer(self): """ A callback that counts milliseconds until SELF.QUEUE has somthing in it """ wait = self.wait.get() + 1 if not self.queue.empty(): # when queue is filled, quit loop and print elapsed time logging.debug('elapsed time = %2.1f [s]', wait * 0.10) self.quit() self.wait.set(wait) # loop over this callback every 100[ms] until queue is filled self.after(100, self.timer)
class Transmitter(object): def __init__(self, sstv, root, progress): def encode_line_hooked(line): progress.update_image(line) return self.original_encode_line(line) self.progress = progress self.sstv = sstv self.original_encode_line = sstv.encode_line sstv.encode_line = encode_line_hooked self.root = root self.tx_enabled = IntVar() self.audio_thread = None self.stopping = False def start_stop_tx(self): if self.tx_enabled.get(): self.stopping = False self.audio_thread = AudioThread(self.sstv, self) self.audio_thread.start() else: self.stop() if self.progress is not None: self.progress.update_image() def stop(self): if self.audio_thread is not None: self.stopping = True self.audio_thread.stop() def audio_thread_ended(self): if not self.stopping: self.tx_enabled.set(0) def close(self): self.root.destroy()
def input_input_checkbox(self, e): var = IntVar(master=self.frame) self.master.serialized[e.name] = lambda: var.get() and True or False if e.default is not None: var.set(e.default) w = Checkbutton(self.frame, text=self.compile_text(e.label), variable=var) self.pack_element(w)
class PVmodule_tk(Frame): """ classdocs """ def __init__(self, pvapp, top): """ Constructor """ self.pvapp = pvapp Frame.__init__(self, top) self.pack(expand=True) # if user resizes, expand Frame self.pack(fill='both') self.focus_set() # get the focus self.grab_set() # make this window modal self['bg'] = 'black' # set black background self['padx'] = '15' # pad sides with 15 points self['pady'] = '5' # pad top/bottom 5 points self.master.title('PVmodule') # set title bar self.SPlogoLabel = Label(self, image=self.pvapp.SPlogo, cnf={'borderwidth': '0'}) self.SPlogoLabel.pack({'side': 'top'}) self.numberCells = IntVar(self) # bind numberCells self.numberCells.set(MODULE_SIZES[0]) # default value # pylint: disable = W0142 self.numberCellsOption = OptionMenu(self, self.numberCells, *MODULE_SIZES) # pylint: enable = W0142 self.numberCellsOption.pack({'side': 'top', 'fill': 'both'}) self.QUIT = Button(self, cnf={'text': 'Quit', 'command': self.quit}) self.QUIT.pack({'side': 'top', 'fill': 'both'})
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Scale") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) scale = Scale(self, from_=0, to=100, command=self.onScale) scale.place(x=20, y=20) self.var = IntVar() self.label = Label(self, text=0, textvariable=self.var) self.label.place(x=130, y=70) def onScale(self, val): v = int(float(val)) self.var.set(v)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Scale") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) scale = Scale(self, from_=0, to=100, command=self.onScale) scale.pack(side=LEFT, padx=15) self.var = IntVar() self.label = Label(self, text=0, textvariable=self.var) self.label.pack(side=LEFT) def onScale(self, val): v = int(float(val)) self.var.set(v)
class NumberOfClasses(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent number_of_classes_label = Label(self, text = 'Number of classes: ') number_of_classes_label.grid(row = 0, column = 0) number_options = range(DEFAULT_NUMBER_OF_CLASS, MAX_NUMBER_OF_CLASSES+1) self.selected_number = IntVar(self, value = DEFAULT_NUMBER_OF_CLASS) option_menu = OptionMenu(self, self.selected_number, *number_options, command = self._on_number_selection) option_menu.grid(row = 0, column = 1) self.observers = [] def register_observer(self, observer): self.observers.append(observer) def notify_observers(self, class_number): for observer in self.observers: observer.set_class_number(class_number) def _on_number_selection(self, selected_number): self.notify_observers(selected_number) def get(self): return self.selected_number.get() def reset(self): self.selected_number.set(DEFAULT_NUMBER_OF_CLASS)
class SizableTreeView(TreeView): def __init__(self, tree, settings): self._trees = (tree, ) self._top = Tk() cf = self._cframe = CanvasFrame(self._top) # Size is variable. self._size = IntVar(self._top) self._size.set(12) bold = (settings['font'], -int(12 * settings['scale']), 'bold') norm = (settings['font'], -int(12 * settings['scale'])) self._width = 1 self._widgets = [] widget = TreeWidget( cf.canvas(), tree, node_font=bold, leaf_color=settings['terminal_color'], node_color=settings['nonterminal_color'], roof_color='#004040', roof_fill='white', line_color='#004040', leaf_font=norm, ) widget['xspace'] = int(settings['scale'] * widget['xspace']) widget['yspace'] = int(settings['scale'] * widget['yspace']) self._widgets.append(widget) cf.add_widget(widget, 0, 0) self._layout() self._cframe.pack(expand=1, fill='both', side='left')
class SizableTreeView(TreeView): def __init__(self, tree, settings): self._trees = (tree,) self._top = Tk() cf = self._cframe = CanvasFrame(self._top) # Size is variable. self._size = IntVar(self._top) self._size.set(12) bold = (settings["font"], -int(12 * settings["scale"]), "bold") norm = (settings["font"], -int(12 * settings["scale"])) self._width = 1 self._widgets = [] widget = TreeWidget( cf.canvas(), tree, node_font=bold, leaf_color=settings["terminal_color"], node_color=settings["nonterminal_color"], roof_color="#004040", roof_fill="white", line_color="#004040", leaf_font=norm, ) widget["xspace"] = int(settings["scale"] * widget["xspace"]) widget["yspace"] = int(settings["scale"] * widget["yspace"]) self._widgets.append(widget) cf.add_widget(widget, 0, 0) self._layout() self._cframe.pack(expand=1, fill="both", side="left")
class NumberOfClasses(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent number_of_classes_label = Label(self, text='Number of classes: ') number_of_classes_label.grid(row=0, column=0) number_options = range(DEFAULT_NUMBER_OF_CLASS, MAX_NUMBER_OF_CLASSES + 1) self.selected_number = IntVar(self, value=DEFAULT_NUMBER_OF_CLASS) option_menu = OptionMenu(self, self.selected_number, *number_options, command=self._on_number_selection) option_menu.grid(row=0, column=1) self.observers = [] def register_observer(self, observer): self.observers.append(observer) def notify_observers(self, class_number): for observer in self.observers: observer.set_class_number(class_number) def _on_number_selection(self, selected_number): self.notify_observers(selected_number) def get(self): return self.selected_number.get() def reset(self): self.selected_number.set(DEFAULT_NUMBER_OF_CLASS)
def __init__(self, master, track, sequencer): TrackFrame.__init__(self, master, track) self.id_label = Label(self, text=str(track.id)) self.id_label.pack(side='left') self.instrument_label = Label(self, text=str(track.instrument_tone), width=3) self.instrument_label.pack(side='left') mute_var = IntVar() self.mute_toggle = Checkbutton(self, command=lambda: check_cmd(track, mute_var), variable=mute_var) self.mute_toggle.pack(side='left') mute_var.set(not track.mute) rhythm_frame = Frame(self) rhythm_frame.pack(side='right') subdivision = sequencer.measure_resolution / sequencer.beats_per_measure self.buttons = [] for b in range(0, len(self.track.rhythms)): button = RhythmButton(rhythm_frame, track, b, not b % subdivision) self.buttons.append(button) button.grid(row=0, column=b, padx=1) self.beat = 0
def init(): """初始化页面""" global face_file_list, face_image, face_label, detect_label all_files = os.listdir(image_dir) face_file_list = filter(lambda x: x.endswith('jpg'), all_files) get_face_record(offset) place_image(offset) face_image = Label(master, image=tk_image) face_image.place(anchor=u'nw', x=10, y=40) face_label = IntVar() face_label.set(face_record.label) score_ugly = Radiobutton(master, text=u'丑', variable=face_label, value=0, command=set_face_label) score_ugly.place(anchor=u'nw', x=120, y=10) score_normal = Radiobutton(master, text=u'一般', variable=face_label, value=1, command=set_face_label) score_normal.place(anchor=u'nw', x=160, y=10) score_pretty = Radiobutton(master, text=u'漂亮', variable=face_label, value=2, command=set_face_label) score_pretty.place(anchor=u'nw', x=220, y=10) detect_label = Label(master, text=u'') detect_label.place(anchor=u'nw', x=580, y=10) handle_detect()
class GUI(object): def __init__(self, master): self.master = master master.title("Calculator") self.calculator = Calculator() self.entered_number = 0 self.total_label_text = IntVar() self.total_label = Label(master, textvariable=self.total_label_text) self.label = Label(master, text="Total:") vcmd = master.register(self.validate) # we have to wrap the command self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P')) self.add_button = Button(master, text="+", command=lambda: self.update("add")) self.subtract_button = Button(master, text="-", command=lambda: self.update("subtract")) self.reset_button = Button(master, text="Reset", command=lambda: self.update("reset")) # LAYOUT self.label.grid(row=0, column=0, sticky=W) self.total_label.grid(row=0, column=1, columnspan=2, sticky=E) self.entry.grid(row=1, column=0, columnspan=3, sticky=W+E) self.add_button.grid(row=2, column=0) self.subtract_button.grid(row=2, column=1) self.reset_button.grid(row=2, column=2, sticky=W+E) self.update_total() def update_total(self): self.total_label_text.set(self.calculator.total) def validate(self, new_text): if not new_text: # the field is being cleared self.entered_number = 0 return True try: self.entered_number = int(new_text) return True except ValueError: return False def update(self, method): if method == "add": self.calculator.add(self.entered_number) elif method == "subtract": self.calculator.sub(self.entered_number) else: # reset self.calculator.reset() self.update_total() self.entry.delete(0, END)
class Checkbox(Checkbutton): def __init__(self, master, text, default=None, **args): self.var = IntVar() Checkbutton.__init__(self, master, text=text, variable=self.var, **args) if default is not None: self.var.set(default) def get(self): return self.var.get()
class Calculator: def __init__(self, master): self.master = master master.title("Simple Calculator") self.total = 0 self.entered_number = 0 self.total_label_text = IntVar() self.total_label_text.set(self.total) self.total_label = Label(master, textvariable=self.total_label_text) self.label = Label(master, text="Result:") vcmd = master.register(self.validate) self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P')) self.add_button = Button(master, text="+", command=lambda: self.update("add")) self.subtract_button = Button(master, text="-", command=lambda: self.update("subtract")) self.divide_button = Button(master, text="/", command=lambda: self.update("divide")) self.multipy_button = Button(master, text="*", command=lambda: self.update("multiply")) self.label.grid(row=0, column=0, sticky=W) self.total_label.grid(row=0, column=1, columnspan=4, sticky=E) self.entry.grid(row=1, column=0, columnspan=3, sticky=W+E) self.add_button.grid(row=2, column=0) self.subtract_button.grid(row=2, column=1) self.multiply_button.grid(row=2, column=2) self.divide_button.grid(row=2, column=3) def validate(self, new_text): if not new_text: self.entered_number = 0 return True try: self.entered_number = int(new_text) return True except ValueError: return False def update(self, method): if method == "add": self.total += self.entered_number elif method == "subtract": self.total -= self.entered_number else: # reset self.total = 0 self.total_label_text.set(self.total) self.entry.delete(0, END)
def __init__(self, parent=None, picks=[], side=LEFT, anchor=W, default=[]): Frame.__init__(self, parent) self.vars = [] for i,pick in enumerate(picks): var = IntVar() chk = Checkbutton(self, text=pick, variable=var) chk.pack(side=side, anchor=anchor, expand=YES) if i< len(default): var.set(default[i]) self.vars.append(var)
class PropertyPanel(SketchPanel): receivers = SketchPanel.receivers[:] def __init__(self, master, main_window, doc, *args, **kw): self.var_auto_update = IntVar(master) self.var_auto_update.set(1) apply(SketchPanel.__init__, (self, master, main_window, doc) + args, kw) receivers.append((SELECTION, 'selection_changed')) receivers.append((EDITED, 'selection_changed')) def selection_changed(self, *args): if self.var_auto_update.get(): self.Update() def create_std_buttons(self, master, update_from=1): button_frame = Frame(master) button = Checkbutton(button_frame, text=_("Auto Update"), variable=self.var_auto_update) button.pack(side=TOP, expand=1, fill=X) if update_from: button = UpdatedButton(button_frame, text=_("Update From..."), command=self.update_from_object) button.pack(side=TOP, expand=1, fill=X) button = UpdatedButton(button_frame, text=_("Apply"), command=self.do_apply, sensitivecb=self.can_apply) button.pack(side=LEFT, expand=1, fill=X) self.Subscribe(SELECTION, button.Update) button = UpdatedButton(button_frame, text=_("Close"), command=self.close_dlg) button.pack(side=RIGHT, expand=1, fill=X) return button_frame def update_from_object(self): self.main_window.canvas.PickObject(self.update_from_object_cb) def update_from_object_cb(self, obj): pass can_apply = SketchPanel.doc_has_selection def SetDocument(self, doc): SketchPanel.SetDocument(self, doc) self.selection_changed()
class Calculator: def __init__(self, master): self.master = master master.title("Calculator") self.total = 0 self.entered_number = 0 self.total_label_text = IntVar() self.total_label_text.set(self.total) self.total_label = Label(master, textvariable=self.total_label_text) self.label = Label(master, text="Total:") vcmd = master.register(self.validate) # we have to wrap the command self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P')) self.add_button = Button(master, text="+", command=lambda: self.update("add")) self.subtract_button = Button(master, text="-", command=lambda: self.update("subtract")) self.reset_button = Button(master, text="Reset", command=lambda: self.update("reset")) # LAYOUT self.label.grid(row=0, column=0, sticky=W) self.total_label.grid(row=0, column=1, columnspan=2, sticky=E) self.entry.grid(row=1, column=0, columnspan=3, sticky=W+E) self.add_button.grid(row=2, column=0) self.subtract_button.grid(row=2, column=1) self.reset_button.grid(row=2, column=2, sticky=W+E) def validate(self, new_text): if not new_text: # the field is being cleared self.entered_number = 0 return True try: self.entered_number = int(new_text) return True except ValueError: return False def update(self, method): if method == "add": self.total += self.entered_number elif method == "subtract": self.total -= self.entered_number else: # reset self.total = 0 self.total_label_text.set(self.total) self.entry.delete(0, END)
def chooseLepcharge(): """Displays options if user checks the box to select leptons' charges""" TwoLepcharge_val = IntVar() TwoLepcharge_val.set(1) if st_lepchargecb.get() == 1: b1_LepCharge.grid(row=1, sticky=W) b2_LepCharge.grid(row=2, sticky=W) else: b1_LepCharge.grid_forget() b2_LepCharge.grid_forget() del TwoLepcharge_val
def chooseLepflavour(): """Displays options if user checks the box to select leptons' flavours""" TwoLepflavour_val = IntVar() TwoLepflavour_val.set(1) if st_lepflavourcb.get() == 1: b1_LepFlavour.grid(row=4, sticky=W) b2_LepFlavour.grid(row=5, sticky=W) else: b1_LepFlavour.grid_forget() b2_LepFlavour.grid_forget() del TwoLepflavour_val
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Listbox + Scale + ChkBtn") self.pack(fill=BOTH, expand=1) acts = ['Scarlett Johansson', 'Rachel Weiss', 'Natalie Portman', 'Jessica Alba'] lb = Listbox(self) for i in acts: lb.insert(END, i) lb.bind("<<ListboxSelect>>", self.onSelect) lb.place(x=20, y=20) self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) self.label.place(x=20, y=190) scale = Scale(self, from_=0, to=100, command=self.onScale) scale.place(x=20, y=220) self.var_scale = IntVar() self.label_scale = Label(self, text=0, textvariable=self.var_scale) self.label_scale.place(x=180, y=220) self.var_chk = IntVar() cb = Checkbutton(self, text="Test", variable=self.var_chk, command=self.onClick) cb.select() cb.place(x=220, y=60) def onSelect(self, val): sender = val.widget idx = sender.curselection() value = sender.get(idx) self.var.set(value) def onScale(self, val): v = int(float(val)) self.var_scale.set(v) def onClick(self): if self.var_chk.get() == 1: self.var.set("checked") else: self.var.set("unchecked")
class RadioButtonlist(ttk.Frame): def __init__(self,master=None,buttonnamelist=[],**kw): ttk.Frame.__init__(self, master=None, **kw) self.__buttonlist=[] self.__vat= IntVar() self.__vat.set(0) for i in range(len(buttonnamelist)): self.__buttonlist.append(ttk.Radiobutton(self,text=buttonnamelist[i],variable=self.__vat,value=i)) self.__buttonlist[i].pack(anchor = 'nw',side = 'left',padx=5,pady=5) def getvalue(self): return self.__vat.get()
class Transmitter(object): def __init__(self, sstv, root, progress, set_ptt_pin, ptt_state): def encode_line_hooked(line): progress.update_image(line) return self.original_encode_line(line) self.progress = progress self.sstv = sstv self.original_encode_line = sstv.encode_line sstv.encode_line = encode_line_hooked self.root = root self.tx_enabled = IntVar() self.audio_thread = None self.stopping = False self.set_ptt_pin = set_ptt_pin self.ptt_state = ptt_state def set_ptt(self, state): if self.set_ptt_pin is None: return if not state: sleep(0.2) self.set_ptt_pin(state != self.ptt_state) if state: sleep(0.2) def start_stop_tx(self): if self.tx_enabled.get(): self.stopping = False self.audio_thread = AudioThread(self.sstv, self) self.set_ptt(True) self.audio_thread.start() else: self.stop() if self.progress is not None: self.progress.update_image() def stop(self): if self.audio_thread is not None: self.stopping = True self.audio_thread.stop() self.set_ptt(False) def audio_thread_ended(self): if not self.stopping: self.set_ptt(False) self.tx_enabled.set(0) def close(self): self.root.destroy()
class Application(object): def __init__(self, root): self.counter = IntVar() self.counter.set(0) self.label = Label(root, textvariable=self.counter) self.label.pack() self.button = Button(root, text="add one", command=self.increment) self.button.pack() def increment(self): self.counter.set(self.counter.get() + 1)
class PropertyPanel(SketchPanel): receivers = SketchPanel.receivers[:] def __init__(self, master, main_window, doc, *args, **kw): self.var_auto_update = IntVar(master) self.var_auto_update.set(1) apply(SketchPanel.__init__, (self, master, main_window, doc) +args, kw) receivers.append((SELECTION, 'selection_changed')) receivers.append((EDITED, 'selection_changed')) def selection_changed(self, *args): if self.var_auto_update.get(): self.Update() def create_std_buttons(self, master, update_from = 1): button_frame = Frame(master) button = Checkbutton(button_frame, text = _("Auto Update"), variable = self.var_auto_update) button.pack(side = TOP, expand = 1, fill = X) if update_from: button = UpdatedButton(button_frame, text = _("Update From..."), command = self.update_from_object) button.pack(side = TOP, expand = 1, fill = X) button = UpdatedButton(button_frame, text = _("Apply"), command = self.do_apply, sensitivecb = self.can_apply) button.pack(side = LEFT, expand = 1, fill = X) self.Subscribe(SELECTION, button.Update) button = UpdatedButton(button_frame, text = _("Close"), command = self.close_dlg) button.pack(side = RIGHT, expand = 1, fill = X) return button_frame def update_from_object(self): self.main_window.canvas.PickObject(self.update_from_object_cb) def update_from_object_cb(self, obj): pass can_apply = SketchPanel.doc_has_selection def SetDocument(self, doc): SketchPanel.SetDocument(self, doc) self.selection_changed()
class CheckbuttonEntry(BaseWiget): def __init__(self, parent, **kw): BaseWiget.__init__(self,parent, **kw) self.old_value = "" self.var = IntVar() self.cbtn = Checkbutton(self, text=self.caption, variable=self.var) self.cbtn.grid(row=1, column=0) self.var.trace("w", self._onChangeVariable) self.old_value = self.getValue() self.onEndSetupContent() #------------- интерфейс -------------# def setValue(self, value): print "setValue", value if self.old_value == value: return self.old_value = value self.var.set(value) def getValue(self): return self.var.get() def getDictValue(self): raise NotImplementedError def forceSave(self): """принудительное сохранение""" self._onEndInput() #------------- внутренние методы -------------# def _onEndInput(self): value = self.getValue() if self.old_value != value: self.onValueChangeEndByUser(self.old_value, value) self.old_value = value def _onChangeVariable(self, *event): value = self.getValue() if self.old_value == value: return self._onEndInput()
def download(sw, vol, _OUTDIR, _DRYRUN, imgarray=[]): if (_DRYRUN == False): try: idb = IntVar() sdb = StringVar() sdb.set("Volume " + str(vol) + "\t\t 0/" + str(len(imgarray))) h = sw.addBar(len(imgarray), idb, sdb) except Exception as e: print e # print "++++ Downloading Volume "+str(vol) outdir = _OUTDIR + "vol_" + str(vol) + "/" if (not os.path.exists(_OUTDIR)): try: print "mkdir " + _OUTDIR os.mkdir(_OUTDIR) except Exception as error: print error if (not os.path.exists(outdir)): try: print "mkdir " + outdir os.mkdir(outdir) except Exception as error: print error num = 1 for img in imgarray: if num < 10: cnum = "00" elif num < 100: cnum = "0" cnum = cnum + str(num) web.download(img, outdir + cnum + ".jpg", None) idb.set(num) sdb.set("Volume " + str(vol) + "\t\t " + str(num) + "/" + str(len(imgarray))) num = num + 1 sw.delBar(h) else: print "---- DRY run! Skip downloading\n"
def init(): """初始化页面""" global user, offset, photo, url, buy_house, buy_car, age, height, salary, \ education, company, industry, school, position, satisfy, appearance get_user(offset) image_url = u'{}&quality=85&thumbnail=410y410'.format(user['avatar']) place_image(image_url) photo = Label(master, image=tk_image) photo.place(anchor=u'nw', x=10, y=40) url = Label(master, text=user['url'], font=Font(size=20, weight='bold')) url.place(anchor=u'nw', x=10, y=5) buy_house = Label(master, text=BUY_HOUSE.get(user['house']) or user['house']) buy_house.place(anchor=u'nw', x=490, y=50) buy_car = Label(master, text=BUY_CAR.get(user['car']) or user['car']) buy_car.place(anchor=u'nw', x=490, y=75) age = Label(master, text=user['age']) age.place(anchor=u'nw', x=490, y=100) height = Label(master, text=user['height']) height.place(anchor=u'nw', x=490, y=125) salary = Label(master, text=SALARY.get(user['salary']) or user['salary']) salary.place(anchor=u'nw', x=490, y=150) education = Label(master, text=EDUCATION.get(user['education']) or user['education']) education.place(anchor=u'nw', x=490, y=175) company = Label(master, text=user['company'] if user['company'] else u'--') company.place(anchor=u'nw', x=490, y=200) industry = Label(master, text=INDUSTRY.get(user['industry']) or user['industry']) industry.place(anchor=u'nw', x=490, y=225) school = Label(master, text=user['school'] if user['school'] else u'--') school.place(anchor=u'nw', x=490, y=250) position = Label(master, text=POSITION.get(user['position']) or user['position']) position.place(anchor=u'nw', x=490, y=275) satisfy = IntVar() satisfy.set(int(user.get(u'satisfy', -1))) satisfied = Radiobutton(master, text=u"满意", variable=satisfy, value=1, command=set_satisfy) not_satisfied = Radiobutton(master, text=u"不满意", variable=satisfy, value=0, command=set_satisfy) satisfied.place(anchor=u'nw', x=450, y=10) not_satisfied.place(anchor=u'nw', x=510, y=10) appearance = IntVar() appearance.set(int(user.get(u'appearance', -1))) for i in range(1, 11): score_i = Radiobutton(master, text=str(i), variable=appearance, value=i, command=set_appearance) score_i.place(anchor=u'nw', x=i * 40 - 30, y=460)
class SetDefaultPropertiesDlg(SKModal): title = _("Set Default Properties") def __init__(self, master, category): self.category = category SKModal.__init__(self, master, name = 'setdefaults') def build_dlg(self): top = self.top label = Label(top, name = 'label', text = _("Please select the object categories whose " "default properties you want to change")) label.pack(side = TOP, anchor = W) frame = Frame(top) frame.pack(side = TOP) self.var_graphics = IntVar(top) if self.category != 'font': self.var_graphics.set(1) button = Checkbutton(frame, text = _("Graphics Objects"), state = (self.category == 'font' and DISABLED or NORMAL), variable = self.var_graphics) button.pack(side = TOP, anchor = W) self.var_text = IntVar(top) if self.category == 'font': self.var_text.set(1) button = Checkbutton(frame, text = _("Text Objects"), state = (self.category == 'line' and DISABLED or NORMAL), variable = self.var_text) button.pack(side = TOP, anchor = W) but_frame = Frame(top) but_frame.pack(side = TOP, fill = BOTH, expand = 1) button = Button(but_frame, text = _("OK"), command = self.ok) button.pack(side = LEFT, expand = 1) button = Button(but_frame, text = _("Cancel"), command = self.cancel) button.pack(side = RIGHT, expand = 1) def ok(self, *args): which_properties = (self.var_graphics.get(), self.var_text.get()) self.close_dlg(which_properties)
class Checked(object): def __init__(self, parent_frame, check_text, set_checked=False, on_check_callback=None, on_uncheck_callback=None): self._checked_value = IntVar(value=1 if set_checked else 0) self._check = Checkbutton(parent_frame, text=check_text, variable=self._checked_value, command=self._on_check, anchor=W, justify=LEFT, width=15) self._check.pack(side=TOP) self._on_check_callback = on_check_callback self._on_uncheck_callback = on_uncheck_callback self._check_text = check_text def _on_check(self): if self._checked_value.get() == 1: #print '%s Checked' % self._check_text if self._on_check_callback: self._on_check_callback() else: #print '%s Un-hecked' % self._check_text if self._on_uncheck_callback: self._on_uncheck_callback() def display(self, show=True): if show: self._check.pack(side=TOP) else: self._check.pack_forget() def get_checked(self): return True if self._checked_value.get() == 1 else False def set_checked(self, is_checked): if is_checked: self._checked_value.set(1) else: self._checked_value.set(0) checked = property(fget=get_checked, fset=set_checked)
def __init__(self, parent): self.parent = parent top = self.top = Toplevel(parent.root) Label(top, text="Secret Key(base32):").grid(columnspan=3) base32_key = Entry(top) base32_key.grid(row=1, column=0, columnspan=3) challenge_response_slot = IntVar() challenge_response_slot_widgets = ( Radiobutton( top, text='slot 1', variable=challenge_response_slot, value=1, ).grid(row=3, column=0), Radiobutton( top, text='slot 2', variable=challenge_response_slot, value=2, ).grid(row=3, column=1), ) require_button = IntVar() require_button_widget = Checkbutton(top, text='Button press required', variable=require_button, ).grid(row=2, columnspan=3) require_button.set(1) submit = Button(top, text="Program", command=lambda: self._program_confirm( challenge_response_slot.get(), base32_key.get(), require_button.get() ) ).grid(row=4, column=1) cancel = Button( top, text="Cancel", command=self._program_cancel ).grid(row=4, column=0)
def __init__(self, parent=None, picks=[], side=TOP, anchor=W): Frame.__init__(self, parent) from Tkinter import IntVar, Checkbutton, Button, BOTTOM, TOP from Tkinter import RIGHT, YES import sys self.vars = [] for pick in picks: var = IntVar() var.set(1) # change to 1 to set all checkboxes to true at start chk = Checkbutton(self, text=pick, variable=var) # chk.pack(side=side, anchor=anchor, expand=YES) chk.pack(side=TOP, anchor=anchor, expand=YES) self.vars.append(var) # print(type(self.vars)) self.vars[0].set(0) def combine_funcs(*funcs): def combined_func(*args, **kwargs): for f in funcs: f(*args, **kwargs) return combined_func def allstates(printit): # print(list(calc.state())) # global check # check = list(calc.state()) # check = {} for pick in picks: # check[pick] = calc.state()[picks.index(pick)] # print(picks.index(pick)) check[pick] = self.vars[picks.index(pick)].get() if printit == 1: print(check) return check Buttonframe = Frame(self) Button(Buttonframe, text='QUIT', command=sys.exit).pack(side=RIGHT) Button(Buttonframe, text='OK', command=combine_funcs(lambda: allstates(0), parent.destroy)).pack(side=RIGHT) Buttonframe.pack(side=BOTTOM)
class FrequencyBandSettings (): ''' Used to pass common settings ''' def __init__(self): self.channel = {} self.channel[ChannelTypes.LEFT] = IntVar() self.channel[ChannelTypes.MID] = IntVar() self.channel[ChannelTypes.RIGHT] = IntVar() self.channel[ChannelTypes.BACK] = IntVar() self.showLabels = IntVar() self.frequencyBand = StringVar() self.channel[ChannelTypes.LEFT].set(1) self.channel[ChannelTypes.MID].set(1) self.channel[ChannelTypes.RIGHT].set(1) self.channel[ChannelTypes.BACK].set(1) self.showLabels.set(1) self.frequencyBand.set(FrequencyBands.ALPHA) def getCopy(self): copy = FrequencyBandSettings(); copy.channel[ChannelTypes.LEFT].set(self.channel[ChannelTypes.LEFT].get()) copy.channel[ChannelTypes.MID].set(self.channel[ChannelTypes.MID].get()) copy.channel[ChannelTypes.RIGHT].set(self.channel[ChannelTypes.RIGHT].get()) copy.channel[ChannelTypes.BACK].set(self.channel[ChannelTypes.BACK].get()) copy.showLabels.set(self.showLabels.get()) copy.frequencyBand = self.frequencyBand return copy def update(self, other): self.channel[ChannelTypes.LEFT].set(other.channel[ChannelTypes.LEFT].get()) self.channel[ChannelTypes.MID].set(other.channel[ChannelTypes.MID].get()) self.channel[ChannelTypes.RIGHT].set(other.channel[ChannelTypes.RIGHT].get()) self.channel[ChannelTypes.BACK].set(other.channel[ChannelTypes.BACK].get()) self.showLabels.set(other.showLabels.get()) self.frequencyBand = other.frequencyBand def get_showLabels(self): if self.showLabels.get()==1: return True else: return False
def __init__(self, parent, paned_window, **kwargs): Frame.__init__(self, paned_window) self.parent = parent self.df_column_frame = ScrolledFrame(self, vertflex='expand') self.graph_frame = ScrolledFrame(self, horizflex='expand', vertflex='expand') self.plot_figure = kwargs['plot'] if 'plot' in kwargs else None self.plot_title = kwargs['plot_title'] if 'plot_title' in kwargs else 'Line Plot' self.y_label = kwargs['y_label'] if 'y_label' in kwargs else 'y' self.df = kwargs['df'] if 'df' in kwargs else DataFrame() # If the dataframe wasn't passed in, then create an empty dataframe plot_selected_avg = ModelRunnerPlots.get_avg_plot(self.plot_title, self.y_label, self.df, None) self.plot_figure = plot_selected_avg self.graph_canvas = FigureCanvasTkAgg(plot_selected_avg, master=self.graph_frame.interior()) self.col_list = list() for col in self.df.columns: if col != 'year' and 'Average' not in col: col_var = IntVar() col_var.set(0) col_checkbox = Checkbutton(self.df_column_frame.interior(), text=col, variable=col_var, command=self.on_col_check) self.col_list.append([col_var, col_checkbox, col]) avg_dataframe, dataframe = ModelRunnerPlots.find_avg_dataframe(self.df) for col in avg_dataframe.columns: if col != 'year': col_var = IntVar() col_var.set(0) col_checkbox = Checkbutton(self.df_column_frame.interior(), text=col, variable=col_var, command=self.on_col_check) self.col_list.append([col_var, col_checkbox, col]) self.log_filename_frame = Frame(self) self.log_label = Label(self.log_filename_frame, text='Logfile: ' + kwargs['log_filename']) if 'log_filename' in kwargs else None self.button_frame = Frame(self) self.close_button = Button(self.button_frame, text='Close', command=self.on_close) self.save_button = Button(self.button_frame, text='Save', command=self.on_save)
class SpectrumSettings: ''' Used to pass common settings ''' def __init__(self): self.channel = {} self.channel[ChannelTypes.LEFT] = IntVar() self.channel[ChannelTypes.MID] = IntVar() self.channel[ChannelTypes.RIGHT] = IntVar() self.channel[ChannelTypes.BACK] = IntVar() self.showLabels = IntVar() self.channel[ChannelTypes.LEFT].set(1) self.channel[ChannelTypes.MID].set(1) self.channel[ChannelTypes.RIGHT].set(1) self.channel[ChannelTypes.BACK].set(1) self.showLabels.set(1) def getCopy(self): copy = SpectrumSettings(); copy.channel[ChannelTypes.LEFT].set(self.channel[ChannelTypes.LEFT].get()) copy.channel[ChannelTypes.MID].set(self.channel[ChannelTypes.MID].get()) copy.channel[ChannelTypes.RIGHT].set(self.channel[ChannelTypes.RIGHT].get()) copy.channel[ChannelTypes.BACK].set(self.channel[ChannelTypes.BACK].get()) copy.showLabels.set(self.showLabels.get()) return copy def update(self, other): self.channel[ChannelTypes.LEFT].set(other.channel[ChannelTypes.LEFT].get()) self.channel[ChannelTypes.MID].set(other.channel[ChannelTypes.MID].get()) self.channel[ChannelTypes.RIGHT].set(other.channel[ChannelTypes.RIGHT].get()) self.channel[ChannelTypes.BACK].set(other.channel[ChannelTypes.BACK].get()) self.showLabels.set(other.showLabels.get()) def get_showLabels(self): if self.showLabels.get()==1: return True else: return False
class SetDefaultPropertiesDlg(SKModal): title = _("Set Default Properties") def __init__(self, master, category): self.category = category SKModal.__init__(self, master, name='setdefaults') def build_dlg(self): root = self.top top = TFrame(root, style='FlatFrame', borderwidth=13) top.pack(side=TOP) label = TLabel(top, text=_("Please select the object categories whose\n default properties you want to change")) label.pack(side=TOP, anchor=W) frame = TFrame(top, style='FlatFrame', borderwidth=10) frame.pack(side=TOP) self.var_graphics_style = IntVar(top) self.var_graphics_style.set(0) if self.category != 'font': self.var_graphics_style.set(1) button = TCheckbutton(frame, text=_("Graphics Objects"), state=(self.category == 'font' and DISABLED or NORMAL), variable=self.var_graphics_style) button.pack(side=TOP, anchor=W) self.var_text_style = IntVar(top) self.var_text_style.set(0) if self.category == 'font': self.var_text_style.set(1) button = TCheckbutton(frame, text=_("Text Objects"), state=(self.category == 'line' and DISABLED or NORMAL), variable=self.var_text_style) button.pack(side=TOP, anchor=W) label = TLabel(top, style="HLine") label.pack(side=TOP, fill=BOTH) but_frame = TFrame(top, style='FlatFrame') but_frame.pack(side=TOP, fill=BOTH, expand=1) button = TButton(but_frame, text=_("Cancel"), command=self.cancel) button.pack(side=RIGHT, expand=1) button = TButton(but_frame, text=_("OK"), command=self.ok) button.pack(side=RIGHT, expand=1) root.resizable (width=0, height=0) def ok(self, *args): graph = self.var_graphics_style.get() text = self.var_text_style.get() self.close_dlg((graph, text))
class Application(object): def __init__(self, root): self.counter = IntVar() self.counter.set(0) self.label = Label(root, width=5, font=("Helvetica", 20, "bold italic"), textvariable=self.counter) self.label.pack(side="left") self.up = Button(root, text="up", background="RED", command=self.increment) self.up.pack(side="left") self.down = Button(root, text="down", background="GREEN", command=self.decrement) self.down.pack(side="left") def increment(self): self.counter.set(self.counter.get() + 1) def decrement(self): self.counter.set(max(0, self.counter.get() - 1))
class commGUI(object): def callback(self): sendComm(self.name + str(self.value.get()), self.conn) def __init__(self, parent, values, connt, name): # state = "disabled" self.style = MainWindowStyles() self.value = IntVar(0) self.value.set(values) self.name = name self.conn = connt _frame = Frame(parent, **self.style.Frame) Button(_frame, text=name, anchor="w", command=self.callback, **self.style.SettingButton).pack(side=LEFT, fill="x") Entry(_frame, width=5, textvariable=str(self.value), **self.style.Entry).pack(side=RIGHT, fill="x") _frame.pack(side="left", padx=5, pady=5)
def init(main_frame): global orgVar, keyVar, maxVar, resultVar, copyVar, levelVar Label(main_frame, text="Organisation").grid(row=0, column=0) Label(main_frame, text="Key").grid(row=1, column=0) Label(main_frame, text="Max chars").grid(row=2, column=0) Label(main_frame, text="Strength").grid(row=3, column=0) Label(main_frame, text="Password").grid(row=4, column=0) Label(main_frame, text="Copy").grid(row=5, column=0) orgVar = addTextField(main_frame, 0, 1, "halifax") keyVar = addTextField(main_frame, 1, 1, "g1ga50ft") maxVar = addTextField(main_frame, 2, 1, "") radio_subframe = Frame(main_frame) radio_subframe.grid(row=3, column=1, sticky="w") levelVar = IntVar() levelVar.set(0) addRadioButton(radio_subframe, label="Std", value=0, variable=levelVar, position=0) addRadioButton(radio_subframe, label="High", value=1, variable=levelVar, position=1) resultVar = addTextField(main_frame, 4, 1, "", 0) copyVar = addTextField(main_frame, 5, 1, "", 0)
def set_tk_var(): global method method = StringVar() method.set(read_config("Config", "Method", "str")) global server server = StringVar() server.set(read_config("Config", "Server", "str")) global shelltype shelltype = StringVar() shelltype.set(read_config("Config", "ShellType", "str")) global parameter parameter = StringVar() parameter.set(read_config("Config", "Parameter", "str")) global thread_num thread_num = IntVar() thread_num.set(read_config("Config", "ThreadNumber", "int")) global req_delay req_delay = DoubleVar() req_delay.set(read_config("Config", "RequestDelay", "float")) global time_out time_out = DoubleVar() time_out.set(read_config("Config", "RequestTimeout", "float")) global random_ua random_ua = BooleanVar() random_ua.set(read_config("Config", "RandomUserAgent", "boolean")) global con_close con_close = BooleanVar() con_close.set(read_config("Config", "ConnectionClose", "boolean")) global keep_alive keep_alive = BooleanVar() keep_alive.set(read_config("Config", "KeepAlive0", "boolean")) global custom_hdr custom_hdr = BooleanVar() custom_hdr.set(read_config("Config", "CustomRequestHeader", "boolean")) global custom_hdr_data custom_hdr_data = StringVar() custom_hdr_data.set(read_config("Config", "CustomRequestHeaderData", "str"))
class MaximumNumberOfIterations(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent max_iteration_laber = Label(self, text='Max iteration: ') max_iteration_laber.pack(side='left') max_iteration_options = [500 + i * 500 for i in range(15)] self.selected_maximum = IntVar(self, value=DEFAULT_MAX_ITERATIONS) option_menu = OptionMenu(self, self.selected_maximum, *max_iteration_options, command=self._on_maximum_selection) option_menu.pack(side='right') def get(self): return self.selected_maximum.get() def reset(self): self.selected_maximum.set(DEFAULT_MAX_ITERATIONS) def _on_maximum_selection(self, selected_maximum): print "Selected max number of iteration: ", selected_maximum
class MaximumNumberOfIterations(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent max_iteration_laber = Label(self, text = 'Max iteration: ') max_iteration_laber.pack(side = 'left') max_iteration_options = [500 + i*500 for i in range(15)] self.selected_maximum = IntVar(self, value = DEFAULT_MAX_ITERATIONS) option_menu = OptionMenu(self, self.selected_maximum, *max_iteration_options, command = self._on_maximum_selection) option_menu.pack(side = 'right') def get(self): return self.selected_maximum.get() def reset(self): self.selected_maximum.set(DEFAULT_MAX_ITERATIONS) def _on_maximum_selection(self, selected_maximum): print "Selected max number of iteration: ", selected_maximum
class Application(object): def __init__(self, root): self.counter = IntVar() self.counter.set(0) self.label = Label(root, textvariable=self.counter) self.label.pack(side="left") self.up = Button(root, text="up", command=self.increment) self.up.pack(side="left") self.down = Button(root, text="down", command=self.decrement) self.down.pack(side="left") def increment(self): self.counter.set(self.counter.get() + 1) def decrement(self): self.counter.set(max(0, self.counter.get() - 1))
class Application(object): def __init__(self, root): self.counter = IntVar() self.counter.set(0) self.label = Label(root, textvariable=self.counter) self.label.pack() self.up = Button(root, text="up", command=self.increment) self.up.pack() self.down = Button(root, text="down", command=self.decrement) self.down.pack() def increment(self): self.counter.set(self.counter.get() + 1) def decrement(self): self.counter.set(max(0, self.counter.get() - 1))
class Candidate(object): def __init__(self, id, name="", points=0): self.name = StringVar() self.points = IntVar() self.id = id if points != 0: self.points.set(points) if name == "": self.name.set("Player " + str(self.id + 1)) else: self.name.set(name) def addPoints(self, points): oldPoints = self.points.get() oldPoints += points self.points.set(oldPoints) def subPoints(self, points): oldPoints = self.points.get() oldPoints -= points self.points.set(oldPoints)
class UI(Tk): def __init__(self): Tk.__init__(self) self.geometry('%dx%d+500+500' % (WIDTH,HEIGHT)) self.title('GooMPy') self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.canvas.pack() self.bind("<Key>", self.check_quit) self.bind('<B1-Motion>', self.drag) self.bind('<Button-1>', self.click) self.label = Label(self.canvas) self.radiogroup = Frame(self.canvas) self.radiovar = IntVar() self.maptypes = ['roadmap', 'terrain', 'satellite', 'hybrid'] self.add_radio_button('Road Map', 0) self.add_radio_button('Terrain', 1) self.add_radio_button('Satellite', 2) self.add_radio_button('Hybrid', 3) self.zoom_in_button = self.add_zoom_button('+', +1) self.zoom_out_button = self.add_zoom_button('-', -1) self.zoomlevel = ZOOM maptype_index = 0 self.radiovar.set(maptype_index) self.goompy = GooMPy(WIDTH, HEIGHT, LATITUDE, LONGITUDE, ZOOM, MAPTYPE) self.restart() def add_zoom_button(self, text, sign): button = Button(self.canvas, text=text, width=1, command=lambda:self.zoom(sign)) return button def reload(self): self.coords = None self.redraw() self['cursor'] = '' def restart(self): # A little trick to get a watch cursor along with loading self['cursor'] = 'watch' self.after(1, self.reload) def add_radio_button(self, text, index): maptype = self.maptypes[index] Radiobutton(self.radiogroup, text=maptype, variable=self.radiovar, value=index, command=lambda:self.usemap(maptype)).grid(row=0, column=index) def click(self, event): self.coords = event.x, event.y def drag(self, event): self.goompy.move(self.coords[0]-event.x, self.coords[1]-event.y) self.image = self.goompy.getImage() self.redraw() self.coords = event.x, event.y def redraw(self): self.image = self.goompy.getImage() self.image_tk = ImageTk.PhotoImage(self.image) self.label['image'] = self.image_tk self.label.place(x=0, y=0, width=WIDTH, height=HEIGHT) self.radiogroup.place(x=0,y=0) x = int(self.canvas['width']) - 50 y = int(self.canvas['height']) - 80 self.zoom_in_button.place(x= x, y=y) self.zoom_out_button.place(x= x, y=y+30) def usemap(self, maptype): self.goompy.useMaptype(maptype) self.restart() def zoom(self, sign): newlevel = self.zoomlevel + sign if newlevel > 0 and newlevel < 22: self.zoomlevel = newlevel self.goompy.useZoom(newlevel) self.restart() def check_quit(self, event): if ord(event.char) == 27: # ESC exit(0)
class CFGDemo(object): def __init__(self, grammar, text): self._grammar = grammar self._text = text # Set up the main window. self._top = Tk() self._top.title('Context Free Grammar Demo') # Base font size self._size = IntVar(self._top) self._size.set(12) # = medium # Set up the key bindings self._init_bindings(self._top) # Create the basic frames frame1 = Frame(self._top) frame1.pack(side='left', fill='y', expand=0) self._init_menubar(self._top) self._init_buttons(self._top) self._init_grammar(frame1) self._init_treelet(frame1) self._init_workspace(self._top) #////////////////////////////////////////////////// # Initialization #////////////////////////////////////////////////// def _init_bindings(self, top): top.bind('<Control-q>', self.destroy) def _init_menubar(self, parent): pass def _init_buttons(self, parent): pass def _init_grammar(self, parent): self._prodlist = ProductionList(parent, self._grammar, width=20) self._prodlist.pack(side='top', fill='both', expand=1) self._prodlist.focus() self._prodlist.add_callback('select', self._selectprod_cb) self._prodlist.add_callback('move', self._selectprod_cb) def _init_treelet(self, parent): self._treelet_canvas = Canvas(parent, background='white') self._treelet_canvas.pack(side='bottom', fill='x') self._treelet = None def _init_workspace(self, parent): self._workspace = CanvasFrame(parent, background='white') self._workspace.pack(side='right', fill='both', expand=1) self._tree = None self.reset_workspace() #////////////////////////////////////////////////// # Workspace #////////////////////////////////////////////////// def reset_workspace(self): c = self._workspace.canvas() fontsize = int(self._size.get()) node_font = ('helvetica', -(fontsize+4), 'bold') leaf_font = ('helvetica', -(fontsize+2)) # Remove the old tree if self._tree is not None: self._workspace.remove_widget(self._tree) # The root of the tree. start = self._grammar.start().symbol() rootnode = TextWidget(c, start, font=node_font, draggable=1) # The leaves of the tree. leaves = [] for word in self._text: leaves.append(TextWidget(c, word, font=leaf_font, draggable=1)) # Put it all together into one tree self._tree = TreeSegmentWidget(c, rootnode, leaves, color='white') # Add it to the workspace. self._workspace.add_widget(self._tree) # Move the leaves to the bottom of the workspace. for leaf in leaves: leaf.move(0,100) #self._nodes = {start:1} #self._leaves = dict([(l,1) for l in leaves]) def workspace_markprod(self, production): pass def _markproduction(self, prod, tree=None): if tree is None: tree = self._tree for i in range(len(tree.subtrees())-len(prod.rhs())): if tree['color', i] == 'white': self._markproduction for j, node in enumerate(prod.rhs()): widget = tree.subtrees()[i+j] if (isinstance(node, Nonterminal) and isinstance(widget, TreeSegmentWidget) and node.symbol == widget.node().text()): pass # matching nonterminal elif (isinstance(node, (str, unicode)) and isinstance(widget, TextWidget) and node == widget.text()): pass # matching nonterminal else: break else: # Everything matched! print 'MATCH AT', i #////////////////////////////////////////////////// # Grammar #////////////////////////////////////////////////// def _selectprod_cb(self, production): canvas = self._treelet_canvas self._prodlist.highlight(production) if self._treelet is not None: self._treelet.destroy() # Convert the production to a tree. rhs = production.rhs() for (i, elt) in enumerate(rhs): if isinstance(elt, Nonterminal): elt = Tree(elt) tree = Tree(production.lhs().symbol(), *rhs) # Draw the tree in the treelet area. fontsize = int(self._size.get()) node_font = ('helvetica', -(fontsize+4), 'bold') leaf_font = ('helvetica', -(fontsize+2)) self._treelet = tree_to_treesegment(canvas, tree, node_font=node_font, leaf_font=leaf_font) self._treelet['draggable'] = 1 # Center the treelet. (x1, y1, x2, y2) = self._treelet.bbox() w, h = int(canvas['width']), int(canvas['height']) self._treelet.move((w-x1-x2)/2, (h-y1-y2)/2) # Mark the places where we can add it to the workspace. self._markproduction(production) def destroy(self, *args): self._top.destroy() def mainloop(self, *args, **kwargs): self._top.mainloop(*args, **kwargs)
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 gui(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.centerUI(w=600,h=250) def initUI(self): self.parent.title("FIND BLR COEFFICIENT VALUE") self.pack(fill=BOTH, expand=True) self.columnconfigure(0, weight=1) # self.rowconfigure(0, weight=1) # weight attibute is used to make them growable ###### GUI Control Variables ###### self.LIMIT_L = IntVar() self.LIMIT_H = IntVar() self.PULSE_R = IntVar() self.PULSE_L = IntVar() self.pulse_height = DoubleVar() self.hdf5_file = StringVar() self.PMT = IntVar() self.EVENT = IntVar() self.amplitude_range = DoubleVar() self.delta = DoubleVar() self.noise_sigma = DoubleVar() self.coeff = DoubleVar() #self.DRAW = BooleanVar() search = Image.open("next_logo.jpg") search_temp = search.resize((170, 200), Image.ANTIALIAS) search_aux = ImageTk.PhotoImage(search_temp) label1 = Label(self, image=search_aux) label1.image = search_aux label1.grid(row=0, column=0, columnspan=10, rowspan=10, sticky=E+W+S+N) self.hdf5_file.set("2052.h5.z") e1 = Entry(self, textvariable=self.hdf5_file, width=30) e1.grid(row=1,column=1, sticky=W, columnspan=5, pady=5) e1_label = Label(self, text="HDF5 file") e1_label.grid(row=0,column=1,sticky=W, columnspan=5, pady=5) self.PMT.set("0") sb1 = Spinbox(self, from_=0, to=12, width=3, textvariable=self.PMT) sb1.grid(row=3,column=2, sticky=W) sb1_label = Label(self, text="PMT") sb1_label.grid(row=2,column=2, padx=0, sticky=W) self.EVENT.set("0") sb1 = Spinbox(self, from_=0, to=1000, width=5, textvariable=self.EVENT) sb1.grid(row=3,column=3, sticky=W) sb1_label = Label(self, text="EVENT") sb1_label.grid(row=2,column=3, padx=0, sticky=W) self.LIMIT_L.set("19000") sb1 = Spinbox(self, from_=0, to=100000, width=5, textvariable=self.LIMIT_L) sb1.grid(row=5,column=2, sticky=W) sb1_label = Label(self, text="ROI Start ") sb1_label.grid(row=4,column=2, padx=0, sticky=W) self.LIMIT_H.set("22500") sb1 = Spinbox(self, from_=0, to=100000, width=5, textvariable=self.LIMIT_H) sb1.grid(row=5,column=3, sticky=W) sb1_label = Label(self, text="ROI End ") sb1_label.grid(row=4,column=3, padx=0, sticky=W) self.PULSE_R.set("20142") sb1 = Spinbox(self, from_=0, to=100000, width=8, textvariable=self.PULSE_R) sb1.grid(row=5,column=4, sticky=E) sb1_label = Label(self, text=" Pulse Rise") sb1_label.grid(row=4,column=4, padx=0, sticky=E) self.PULSE_L.set("1200") sb1 = Spinbox(self, from_=0, to=5000, width=8, textvariable=self.PULSE_L) sb1.grid(row=5,column=5, sticky=E) sb1_label = Label(self, text=" Pulse Length") sb1_label.grid(row=4,column=5, padx=0, sticky=E) sb1_label = Label(self, text=" ") sb1_label.grid(row=2,column=7, padx=0, sticky=W) sb1_label = Label(self, text=" ") sb1_label.grid(row=6,column=7, padx=0, sticky=W) self.pulse_height.set("545.5") sb1 = Entry(self, width=8, textvariable=self.pulse_height) sb1.grid(row=7,column=3, sticky=E) sb1_label = Label(self, text=" Amplitude") sb1_label.grid(row=6,column=3, padx=0, sticky=E) self.amplitude_range.set("2") sb1 = Entry(self, width=8, textvariable=self.amplitude_range) sb1.grid(row=7,column=4, sticky=E) sb1_label = Label(self, text=" Loop Range") sb1_label.grid(row=6,column=4, padx=0, sticky=E) self.delta.set("0.1") sb1 = Entry(self, width=8, textvariable=self.delta) sb1.grid(row=7,column=5, sticky=E) sb1_label = Label(self, text=" Loop Delta") sb1_label.grid(row=6,column=5, padx=0, sticky=E) self.noise_sigma.set("4") sb1 = Entry(self, width=3, textvariable=self.noise_sigma) sb1.grid(row=5,column=6, sticky=E) sb1_label = Label(self, text=" Noise Threshold") sb1_label.grid(row=4,column=6, padx=0, sticky=E) sb_coeff_label = Label(self, text= "Coefficient ") sb_coeff_label.grid(row=0,column=6, padx=0, sticky=E) self.sb_coeff = Label(self) self.sb_coeff.grid(row=1,column=6, padx=0, sticky=E) # MAIN BUTTONS obtn = Button(self, text="GO!!", command=self.find_C) obtn.grid(row=14, column=4, sticky=E, pady=10) cbtn = Button(self, text="Quit", command=self.quit) cbtn.grid(row=14, column=5, sticky=E, pady=10) hbtn = Button(self, text="Help", command=self.help_f) hbtn.grid(row=14, column=0, sticky=W, pady=10) def help_f(self): top = Toplevel() top.title("HELP") msg = Message(top, width= 500, text="COEFF Calibration Procedure: \n \ Input Start Point and Length of the pulse \n \ Input an initial guess of the pulse amplitude \n \ Use a ROI with at least 1000 samples of baseline \n \ and 1000 samples after pulse end \n \ Adjust loop range and step until a graph error \n \ with a minimum is observed \n \ Refine the search to increase precision") msg.pack() button = Button(top, text="Close", command=top.destroy) button.pack() def find_C(self): draw = False LIMIT_L = self.LIMIT_L.get() #19000 LIMIT_H = self.LIMIT_H.get() #22500 PULSE_R = self.PULSE_R.get() #20142 PULSE_L = self.PULSE_L.get() #1200 pulse_height = self.pulse_height.get() #545 hdf5_file = self.hdf5_file.get() #'2052.h5.z' PMT = self.PMT.get() event = self.EVENT.get() amplitude_range = self.amplitude_range.get() #2 delta = self.delta.get() #0.1 noise_sigma = self.noise_sigma.get() #4 coeff_aux = fc.find_coeff(LIMIT_L, LIMIT_H, PULSE_R, PULSE_L, pulse_height, hdf5_file, PMT, event, amplitude_range, delta, noise_sigma, draw) plt.show() self.sb_coeff.configure(text=str(coeff_aux)) def centerUI(self,w,h): sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw-w)/2 y = (sh-h)/2 self.parent.geometry('%dx%d+%d+%d' % (w,h,x,y))
class RecursiveDescentApp(object): """ A graphical tool for exploring the recursive descent parser. The tool displays the parser's tree and the remaining text, and allows the user to control the parser's operation. In particular, the user can expand subtrees on the frontier, match tokens on the frontier against the text, and backtrack. A "step" button simply steps through the parsing process, performing the operations that ``RecursiveDescentParser`` would use. """ def __init__(self, grammar, sent, trace=0): self._sent = sent self._parser = SteppingRecursiveDescentParser(grammar, trace) # Set up the main window. self._top = Tk() self._top.title('Recursive Descent Parser Application') # Set up key bindings. self._init_bindings() # Initialize the fonts. self._init_fonts(self._top) # Animations. animating_lock is a lock to prevent the demo # from performing new operations while it's animating. self._animation_frames = IntVar(self._top) self._animation_frames.set(5) self._animating_lock = 0 self._autostep = 0 # The user can hide the grammar. self._show_grammar = IntVar(self._top) self._show_grammar.set(1) # Create the basic frames. self._init_menubar(self._top) self._init_buttons(self._top) self._init_feedback(self._top) self._init_grammar(self._top) self._init_canvas(self._top) # Initialize the parser. self._parser.initialize(self._sent) # Resize callback self._canvas.bind('<Configure>', self._configure) ######################################### ## Initialization Helpers ######################################### def _init_fonts(self, root): # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html> self._sysfont = tkFont.Font(font=Button()["font"]) root.option_add("*Font", self._sysfont) # TWhat's our font size (default=same as sysfont) self._size = IntVar(root) self._size.set(self._sysfont.cget('size')) self._boldfont = tkFont.Font(family='helvetica', weight='bold', size=self._size.get()) self._font = tkFont.Font(family='helvetica', size=self._size.get()) if self._size.get() < 0: big = self._size.get()-2 else: big = self._size.get()+2 self._bigfont = tkFont.Font(family='helvetica', weight='bold', size=big) def _init_grammar(self, parent): # Grammar view. self._prodframe = listframe = Frame(parent) self._prodframe.pack(fill='both', side='left', padx=2) self._prodlist_label = Label(self._prodframe, font=self._boldfont, text='Available Expansions') self._prodlist_label.pack() self._prodlist = Listbox(self._prodframe, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._prodlist.pack(side='right', fill='both', expand=1) self._productions = list(self._parser.grammar().productions()) for production in self._productions: self._prodlist.insert('end', (' %s' % production)) self._prodlist.config(height=min(len(self._productions), 25)) # Add a scrollbar if there are more than 25 productions. if len(self._productions) > 25: listscroll = Scrollbar(self._prodframe, orient='vertical') self._prodlist.config(yscrollcommand = listscroll.set) listscroll.config(command=self._prodlist.yview) listscroll.pack(side='left', fill='y') # If they select a production, apply it. self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select) def _init_bindings(self): # Key bindings are a good thing. self._top.bind('<Control-q>', self.destroy) self._top.bind('<Control-x>', self.destroy) self._top.bind('<Escape>', self.destroy) self._top.bind('e', self.expand) #self._top.bind('<Alt-e>', self.expand) #self._top.bind('<Control-e>', self.expand) self._top.bind('m', self.match) self._top.bind('<Alt-m>', self.match) self._top.bind('<Control-m>', self.match) self._top.bind('b', self.backtrack) self._top.bind('<Alt-b>', self.backtrack) self._top.bind('<Control-b>', self.backtrack) self._top.bind('<Control-z>', self.backtrack) self._top.bind('<BackSpace>', self.backtrack) self._top.bind('a', self.autostep) #self._top.bind('<Control-a>', self.autostep) self._top.bind('<Control-space>', self.autostep) self._top.bind('<Control-c>', self.cancel_autostep) self._top.bind('<space>', self.step) self._top.bind('<Delete>', self.reset) self._top.bind('<Control-p>', self.postscript) #self._top.bind('<h>', self.help) #self._top.bind('<Alt-h>', self.help) self._top.bind('<Control-h>', self.help) self._top.bind('<F1>', self.help) #self._top.bind('<g>', self.toggle_grammar) #self._top.bind('<Alt-g>', self.toggle_grammar) #self._top.bind('<Control-g>', self.toggle_grammar) self._top.bind('<Control-g>', self.edit_grammar) self._top.bind('<Control-t>', self.edit_sentence) def _init_buttons(self, parent): # Set up the frames. self._buttonframe = buttonframe = Frame(parent) buttonframe.pack(fill='none', side='bottom', padx=3, pady=2) Button(buttonframe, text='Step', background='#90c0d0', foreground='black', command=self.step,).pack(side='left') Button(buttonframe, text='Autostep', background='#90c0d0', foreground='black', command=self.autostep,).pack(side='left') Button(buttonframe, text='Expand', underline=0, background='#90f090', foreground='black', command=self.expand).pack(side='left') Button(buttonframe, text='Match', underline=0, background='#90f090', foreground='black', command=self.match).pack(side='left') Button(buttonframe, text='Backtrack', underline=0, background='#f0a0a0', foreground='black', command=self.backtrack).pack(side='left') # Replace autostep... # self._autostep_button = Button(buttonframe, text='Autostep', # underline=0, command=self.autostep) # self._autostep_button.pack(side='left') def _configure(self, event): self._autostep = 0 (x1, y1, x2, y2) = self._cframe.scrollregion() y2 = event.height - 6 self._canvas['scrollregion'] = '%d %d %d %d' % (x1,y1,x2,y2) self._redraw() def _init_feedback(self, parent): self._feedbackframe = feedbackframe = Frame(parent) feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3) self._lastoper_label = Label(feedbackframe, text='Last Operation:', font=self._font) self._lastoper_label.pack(side='left') lastoperframe = Frame(feedbackframe, relief='sunken', border=1) lastoperframe.pack(fill='x', side='right', expand=1, padx=5) self._lastoper1 = Label(lastoperframe, foreground='#007070', background='#f0f0f0', font=self._font) self._lastoper2 = Label(lastoperframe, anchor='w', width=30, foreground='#004040', background='#f0f0f0', font=self._font) self._lastoper1.pack(side='left') self._lastoper2.pack(side='left', fill='x', expand=1) def _init_canvas(self, parent): self._cframe = CanvasFrame(parent, background='white', #width=525, height=250, closeenough=10, border=2, relief='sunken') self._cframe.pack(expand=1, fill='both', side='top', pady=2) canvas = self._canvas = self._cframe.canvas() # Initially, there's no tree or text self._tree = None self._textwidgets = [] self._textline = None def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label='Reset Parser', underline=0, command=self.reset, accelerator='Del') filemenu.add_command(label='Print to Postscript', underline=0, command=self.postscript, accelerator='Ctrl-p') filemenu.add_command(label='Exit', underline=1, command=self.destroy, accelerator='Ctrl-x') menubar.add_cascade(label='File', underline=0, menu=filemenu) editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label='Edit Grammar', underline=5, command=self.edit_grammar, accelerator='Ctrl-g') editmenu.add_command(label='Edit Text', underline=5, command=self.edit_sentence, accelerator='Ctrl-t') menubar.add_cascade(label='Edit', underline=0, menu=editmenu) rulemenu = Menu(menubar, tearoff=0) rulemenu.add_command(label='Step', underline=1, command=self.step, accelerator='Space') rulemenu.add_separator() rulemenu.add_command(label='Match', underline=0, command=self.match, accelerator='Ctrl-m') rulemenu.add_command(label='Expand', underline=0, command=self.expand, accelerator='Ctrl-e') rulemenu.add_separator() rulemenu.add_command(label='Backtrack', underline=0, command=self.backtrack, accelerator='Ctrl-b') menubar.add_cascade(label='Apply', underline=0, menu=rulemenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_checkbutton(label="Show Grammar", underline=0, variable=self._show_grammar, command=self._toggle_grammar) viewmenu.add_separator() viewmenu.add_radiobutton(label='Tiny', variable=self._size, underline=0, value=10, command=self.resize) viewmenu.add_radiobutton(label='Small', variable=self._size, underline=0, value=12, command=self.resize) viewmenu.add_radiobutton(label='Medium', variable=self._size, underline=0, value=14, command=self.resize) viewmenu.add_radiobutton(label='Large', variable=self._size, underline=0, value=18, command=self.resize) viewmenu.add_radiobutton(label='Huge', variable=self._size, underline=0, value=24, command=self.resize) menubar.add_cascade(label='View', underline=0, menu=viewmenu) animatemenu = Menu(menubar, tearoff=0) animatemenu.add_radiobutton(label="No Animation", underline=0, variable=self._animation_frames, value=0) animatemenu.add_radiobutton(label="Slow Animation", underline=0, variable=self._animation_frames, value=10, accelerator='-') animatemenu.add_radiobutton(label="Normal Animation", underline=0, variable=self._animation_frames, value=5, accelerator='=') animatemenu.add_radiobutton(label="Fast Animation", underline=0, variable=self._animation_frames, value=2, accelerator='+') menubar.add_cascade(label="Animate", underline=1, menu=animatemenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label='About', underline=0, command=self.about) helpmenu.add_command(label='Instructions', underline=0, command=self.help, accelerator='F1') menubar.add_cascade(label='Help', underline=0, menu=helpmenu) parent.config(menu=menubar) ######################################### ## Helper ######################################### def _get(self, widget, treeloc): for i in treeloc: widget = widget.subtrees()[i] if isinstance(widget, TreeSegmentWidget): widget = widget.node() return widget ######################################### ## Main draw procedure ######################################### def _redraw(self): canvas = self._canvas # Delete the old tree, widgets, etc. if self._tree is not None: self._cframe.destroy_widget(self._tree) for twidget in self._textwidgets: self._cframe.destroy_widget(twidget) if self._textline is not None: self._canvas.delete(self._textline) # Draw the tree. helv = ('helvetica', -self._size.get()) bold = ('helvetica', -self._size.get(), 'bold') attribs = {'tree_color': '#000000', 'tree_width': 2, 'node_font': bold, 'leaf_font': helv,} tree = self._parser.tree() self._tree = tree_to_treesegment(canvas, tree, **attribs) self._cframe.add_widget(self._tree, 30, 5) # Draw the text. helv = ('helvetica', -self._size.get()) bottom = y = self._cframe.scrollregion()[3] self._textwidgets = [TextWidget(canvas, word, font=self._font) for word in self._sent] for twidget in self._textwidgets: self._cframe.add_widget(twidget, 0, 0) twidget.move(0, bottom-twidget.bbox()[3]-5) y = min(y, twidget.bbox()[1]) # Draw a line over the text, to separate it from the tree. self._textline = canvas.create_line(-5000, y-5, 5000, y-5, dash='.') # Highlight appropriate nodes. self._highlight_nodes() self._highlight_prodlist() # Make sure the text lines up. self._position_text() def _redraw_quick(self): # This should be more-or-less sufficient after an animation. self._highlight_nodes() self._highlight_prodlist() self._position_text() def _highlight_nodes(self): # Highlight the list of nodes to be checked. bold = ('helvetica', -self._size.get(), 'bold') for treeloc in self._parser.frontier()[:1]: self._get(self._tree, treeloc)['color'] = '#20a050' self._get(self._tree, treeloc)['font'] = bold for treeloc in self._parser.frontier()[1:]: self._get(self._tree, treeloc)['color'] = '#008080' def _highlight_prodlist(self): # Highlight the productions that can be expanded. # Boy, too bad tkinter doesn't implement Listbox.itemconfig; # that would be pretty useful here. self._prodlist.delete(0, 'end') expandable = self._parser.expandable_productions() untried = self._parser.untried_expandable_productions() productions = self._productions for index in range(len(productions)): if productions[index] in expandable: if productions[index] in untried: self._prodlist.insert(index, ' %s' % productions[index]) else: self._prodlist.insert(index, ' %s (TRIED)' % productions[index]) self._prodlist.selection_set(index) else: self._prodlist.insert(index, ' %s' % productions[index]) def _position_text(self): # Line up the text widgets that are matched against the tree numwords = len(self._sent) num_matched = numwords - len(self._parser.remaining_text()) leaves = self._tree_leaves()[:num_matched] xmax = self._tree.bbox()[0] for i in range(0, len(leaves)): widget = self._textwidgets[i] leaf = leaves[i] widget['color'] = '#006040' leaf['color'] = '#006040' widget.move(leaf.bbox()[0] - widget.bbox()[0], 0) xmax = widget.bbox()[2] + 10 # Line up the text widgets that are not matched against the tree. for i in range(len(leaves), numwords): widget = self._textwidgets[i] widget['color'] = '#a0a0a0' widget.move(xmax - widget.bbox()[0], 0) xmax = widget.bbox()[2] + 10 # If we have a complete parse, make everything green :) if self._parser.currently_complete(): for twidget in self._textwidgets: twidget['color'] = '#00a000' # Move the matched leaves down to the text. for i in range(0, len(leaves)): widget = self._textwidgets[i] leaf = leaves[i] dy = widget.bbox()[1] - leaf.bbox()[3] - 10.0 dy = max(dy, leaf.parent().node().bbox()[3] - leaf.bbox()[3] + 10) leaf.move(0, dy) def _tree_leaves(self, tree=None): if tree is None: tree = self._tree if isinstance(tree, TreeSegmentWidget): leaves = [] for child in tree.subtrees(): leaves += self._tree_leaves(child) return leaves else: return [tree] ######################################### ## Button Callbacks ######################################### def destroy(self, *e): self._autostep = 0 if self._top is None: return self._top.destroy() self._top = None def reset(self, *e): self._autostep = 0 self._parser.initialize(self._sent) self._lastoper1['text'] = 'Reset Application' self._lastoper2['text'] = '' self._redraw() def autostep(self, *e): if self._animation_frames.get() == 0: self._animation_frames.set(2) if self._autostep: self._autostep = 0 else: self._autostep = 1 self._step() def cancel_autostep(self, *e): #self._autostep_button['text'] = 'Autostep' self._autostep = 0 # Make sure to stop auto-stepping if we get any user input. def step(self, *e): self._autostep = 0; self._step() def match(self, *e): self._autostep = 0; self._match() def expand(self, *e): self._autostep = 0; self._expand() def backtrack(self, *e): self._autostep = 0; self._backtrack() def _step(self): if self._animating_lock: return # Try expanding, matching, and backtracking (in that order) if self._expand(): pass elif self._parser.untried_match() and self._match(): pass elif self._backtrack(): pass else: self._lastoper1['text'] = 'Finished' self._lastoper2['text'] = '' self._autostep = 0 # Check if we just completed a parse. if self._parser.currently_complete(): self._autostep = 0 self._lastoper2['text'] += ' [COMPLETE PARSE]' def _expand(self, *e): if self._animating_lock: return old_frontier = self._parser.frontier() rv = self._parser.expand() if rv is not None: self._lastoper1['text'] = 'Expand:' self._lastoper2['text'] = rv self._prodlist.selection_clear(0, 'end') index = self._productions.index(rv) self._prodlist.selection_set(index) self._animate_expand(old_frontier[0]) return 1 else: self._lastoper1['text'] = 'Expand:' self._lastoper2['text'] = '(all expansions tried)' return 0 def _match(self, *e): if self._animating_lock: return old_frontier = self._parser.frontier() rv = self._parser.match() if rv is not None: self._lastoper1['text'] = 'Match:' self._lastoper2['text'] = rv self._animate_match(old_frontier[0]) return 1 else: self._lastoper1['text'] = 'Match:' self._lastoper2['text'] = '(failed)' return 0 def _backtrack(self, *e): if self._animating_lock: return if self._parser.backtrack(): elt = self._parser.tree() for i in self._parser.frontier()[0]: elt = elt[i] self._lastoper1['text'] = 'Backtrack' self._lastoper2['text'] = '' if isinstance(elt, Tree): self._animate_backtrack(self._parser.frontier()[0]) else: self._animate_match_backtrack(self._parser.frontier()[0]) return 1 else: self._autostep = 0 self._lastoper1['text'] = 'Finished' self._lastoper2['text'] = '' return 0 def about(self, *e): ABOUT = ("NLTK Recursive Descent Parser Application\n"+ "Written by Edward Loper") TITLE = 'About: Recursive Descent Parser Application' try: from tkMessageBox import Message Message(message=ABOUT, title=TITLE).show() except: ShowText(self._top, TITLE, ABOUT) def help(self, *e): self._autostep = 0 # The default font's not very legible; try using 'fixed' instead. try: ShowText(self._top, 'Help: Recursive Descent Parser Application', (__doc__ or '').strip(), width=75, font='fixed') except: ShowText(self._top, 'Help: Recursive Descent Parser Application', (__doc__ or '').strip(), width=75) def postscript(self, *e): self._autostep = 0 self._cframe.print_to_file() def mainloop(self, *args, **kwargs): """ Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes. """ if in_idle(): return self._top.mainloop(*args, **kwargs) def resize(self, size=None): if size is not None: self._size.set(size) size = self._size.get() self._font.configure(size=-(abs(size))) self._boldfont.configure(size=-(abs(size))) self._sysfont.configure(size=-(abs(size))) self._bigfont.configure(size=-(abs(size+2))) self._redraw() ######################################### ## Expand Production Selection ######################################### def _toggle_grammar(self, *e): if self._show_grammar.get(): self._prodframe.pack(fill='both', side='left', padx=2, after=self._feedbackframe) self._lastoper1['text'] = 'Show Grammar' else: self._prodframe.pack_forget() self._lastoper1['text'] = 'Hide Grammar' self._lastoper2['text'] = '' # def toggle_grammar(self, *e): # self._show_grammar = not self._show_grammar # if self._show_grammar: # self._prodframe.pack(fill='both', expand='y', side='left', # after=self._feedbackframe) # self._lastoper1['text'] = 'Show Grammar' # else: # self._prodframe.pack_forget() # self._lastoper1['text'] = 'Hide Grammar' # self._lastoper2['text'] = '' def _prodlist_select(self, event): selection = self._prodlist.curselection() if len(selection) != 1: return index = int(selection[0]) old_frontier = self._parser.frontier() production = self._parser.expand(self._productions[index]) if production: self._lastoper1['text'] = 'Expand:' self._lastoper2['text'] = production self._prodlist.selection_clear(0, 'end') self._prodlist.selection_set(index) self._animate_expand(old_frontier[0]) else: # Reset the production selections. self._prodlist.selection_clear(0, 'end') for prod in self._parser.expandable_productions(): index = self._productions.index(prod) self._prodlist.selection_set(index) ######################################### ## Animation ######################################### def _animate_expand(self, treeloc): oldwidget = self._get(self._tree, treeloc) oldtree = oldwidget.parent() top = not isinstance(oldtree.parent(), TreeSegmentWidget) tree = self._parser.tree() for i in treeloc: tree = tree[i] widget = tree_to_treesegment(self._canvas, tree, node_font=self._boldfont, leaf_color='white', tree_width=2, tree_color='white', node_color='white', leaf_font=self._font) widget.node()['color'] = '#20a050' (oldx, oldy) = oldtree.node().bbox()[:2] (newx, newy) = widget.node().bbox()[:2] widget.move(oldx-newx, oldy-newy) if top: self._cframe.add_widget(widget, 0, 5) widget.move(30-widget.node().bbox()[0], 0) self._tree = widget else: oldtree.parent().replace_child(oldtree, widget) # Move the children over so they don't overlap. # Line the children up in a strange way. if widget.subtrees(): dx = (oldx + widget.node().width()/2 - widget.subtrees()[0].bbox()[0]/2 - widget.subtrees()[0].bbox()[2]/2) for subtree in widget.subtrees(): subtree.move(dx, 0) self._makeroom(widget) if top: self._cframe.destroy_widget(oldtree) else: oldtree.destroy() colors = ['gray%d' % (10*int(10*x/self._animation_frames.get())) for x in range(self._animation_frames.get(),0,-1)] # Move the text string down, if necessary. dy = widget.bbox()[3] + 30 - self._canvas.coords(self._textline)[1] if dy > 0: for twidget in self._textwidgets: twidget.move(0, dy) self._canvas.move(self._textline, 0, dy) self._animate_expand_frame(widget, colors) def _makeroom(self, treeseg): """ Make sure that no sibling tree bbox's overlap. """ parent = treeseg.parent() if not isinstance(parent, TreeSegmentWidget): return index = parent.subtrees().index(treeseg) # Handle siblings to the right rsiblings = parent.subtrees()[index+1:] if rsiblings: dx = treeseg.bbox()[2] - rsiblings[0].bbox()[0] + 10 for sibling in rsiblings: sibling.move(dx, 0) # Handle siblings to the left if index > 0: lsibling = parent.subtrees()[index-1] dx = max(0, lsibling.bbox()[2] - treeseg.bbox()[0] + 10) treeseg.move(dx, 0) # Keep working up the tree. self._makeroom(parent) def _animate_expand_frame(self, widget, colors): if len(colors) > 0: self._animating_lock = 1 widget['color'] = colors[0] for subtree in widget.subtrees(): if isinstance(subtree, TreeSegmentWidget): subtree.node()['color'] = colors[0] else: subtree['color'] = colors[0] self._top.after(50, self._animate_expand_frame, widget, colors[1:]) else: widget['color'] = 'black' for subtree in widget.subtrees(): if isinstance(subtree, TreeSegmentWidget): subtree.node()['color'] = 'black' else: subtree['color'] = 'black' self._redraw_quick() widget.node()['color'] = 'black' self._animating_lock = 0 if self._autostep: self._step() def _animate_backtrack(self, treeloc): # Flash red first, if we're animating. if self._animation_frames.get() == 0: colors = [] else: colors = ['#a00000', '#000000', '#a00000'] colors += ['gray%d' % (10*int(10*x/(self._animation_frames.get()))) for x in range(1, self._animation_frames.get()+1)] widgets = [self._get(self._tree, treeloc).parent()] for subtree in widgets[0].subtrees(): if isinstance(subtree, TreeSegmentWidget): widgets.append(subtree.node()) else: widgets.append(subtree) self._animate_backtrack_frame(widgets, colors) def _animate_backtrack_frame(self, widgets, colors): if len(colors) > 0: self._animating_lock = 1 for widget in widgets: widget['color'] = colors[0] self._top.after(50, self._animate_backtrack_frame, widgets, colors[1:]) else: for widget in widgets[0].subtrees(): widgets[0].remove_child(widget) widget.destroy() self._redraw_quick() self._animating_lock = 0 if self._autostep: self._step() def _animate_match_backtrack(self, treeloc): widget = self._get(self._tree, treeloc) node = widget.parent().node() dy = (1.0 * (node.bbox()[3] - widget.bbox()[1] + 14) / max(1, self._animation_frames.get())) self._animate_match_backtrack_frame(self._animation_frames.get(), widget, dy) def _animate_match(self, treeloc): widget = self._get(self._tree, treeloc) dy = ((self._textwidgets[0].bbox()[1] - widget.bbox()[3] - 10.0) / max(1, self._animation_frames.get())) self._animate_match_frame(self._animation_frames.get(), widget, dy) def _animate_match_frame(self, frame, widget, dy): if frame > 0: self._animating_lock = 1 widget.move(0, dy) self._top.after(10, self._animate_match_frame, frame-1, widget, dy) else: widget['color'] = '#006040' self._redraw_quick() self._animating_lock = 0 if self._autostep: self._step() def _animate_match_backtrack_frame(self, frame, widget, dy): if frame > 0: self._animating_lock = 1 widget.move(0, dy) self._top.after(10, self._animate_match_backtrack_frame, frame-1, widget, dy) else: widget.parent().remove_child(widget) widget.destroy() self._animating_lock = 0 if self._autostep: self._step() def edit_grammar(self, *e): CFGEditor(self._top, self._parser.grammar(), self.set_grammar) def set_grammar(self, grammar): self._parser.set_grammar(grammar) self._productions = list(grammar.productions()) self._prodlist.delete(0, 'end') for production in self._productions: self._prodlist.insert('end', (' %s' % production)) def edit_sentence(self, *e): sentence = " ".join(self._sent) title = 'Edit Text' instr = 'Enter a new sentence to parse.' EntryDialog(self._top, sentence, instr, self.set_sentence, title) def set_sentence(self, sentence): self._sent = sentence.split() #[XX] use tagged? self.reset()
class TreeView(object): def __init__(self, *trees): from math import sqrt, ceil self._trees = trees self._top = Tk() self._top.title('NLTK') self._top.bind('<Control-x>', self.destroy) self._top.bind('<Control-q>', self.destroy) cf = self._cframe = CanvasFrame(self._top) self._top.bind('<Control-p>', self._cframe.print_to_file) # Size is variable. self._size = IntVar(self._top) self._size.set(12) bold = ('helvetica', -self._size.get(), 'bold') helv = ('helvetica', -self._size.get()) # Lay the trees out in a square. self._width = int(ceil(sqrt(len(trees)))) self._widgets = [] for i in range(len(trees)): widget = TreeWidget(cf.canvas(), trees[i], node_font=bold, leaf_color='#008040', node_color='#004080', roof_color='#004040', roof_fill='white', line_color='#004040', draggable=1, leaf_font=helv) widget.bind_click_trees(widget.toggle_collapsed) self._widgets.append(widget) cf.add_widget(widget, 0, 0) self._layout() self._cframe.pack(expand=1, fill='both') self._init_menubar() def _layout(self): i = x = y = ymax = 0 width = self._width for i in range(len(self._widgets)): widget = self._widgets[i] (oldx, oldy) = widget.bbox()[:2] if i % width == 0: y = ymax x = 0 widget.move(x-oldx, y-oldy) x = widget.bbox()[2] + 10 ymax = max(ymax, widget.bbox()[3] + 10) def _init_menubar(self): menubar = Menu(self._top) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label='Print to Postscript', underline=0, command=self._cframe.print_to_file, accelerator='Ctrl-p') filemenu.add_command(label='Exit', underline=1, command=self.destroy, accelerator='Ctrl-x') menubar.add_cascade(label='File', underline=0, menu=filemenu) zoommenu = Menu(menubar, tearoff=0) zoommenu.add_radiobutton(label='Tiny', variable=self._size, underline=0, value=10, command=self.resize) zoommenu.add_radiobutton(label='Small', variable=self._size, underline=0, value=12, command=self.resize) zoommenu.add_radiobutton(label='Medium', variable=self._size, underline=0, value=14, command=self.resize) zoommenu.add_radiobutton(label='Large', variable=self._size, underline=0, value=28, command=self.resize) zoommenu.add_radiobutton(label='Huge', variable=self._size, underline=0, value=50, command=self.resize) menubar.add_cascade(label='Zoom', underline=0, menu=zoommenu) self._top.config(menu=menubar) def resize(self, *e): bold = ('helvetica', -self._size.get(), 'bold') helv = ('helvetica', -self._size.get()) xspace = self._size.get() yspace = self._size.get() for widget in self._widgets: widget['node_font'] = bold widget['leaf_font'] = helv widget['xspace'] = xspace widget['yspace'] = yspace if self._size.get() < 20: widget['line_width'] = 1 elif self._size.get() < 30: widget['line_width'] = 2 else: widget['line_width'] = 3 self._layout() def destroy(self, *e): if self._top is None: return self._top.destroy() self._top = None def mainloop(self, *args, **kwargs): """ Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes. """ if in_idle(): return self._top.mainloop(*args, **kwargs)
class CoreGUI(object): def __init__(self, parent, doc_dir): self.doc_dir = doc_dir self.parent = parent self.InitUI() self.show_poss_vals = False self.show_forced_vals = False self.use_SD = False self.out = StdoutRedirector(self.text_box) sys.stdout = self.out def main(self): ''' The body of the execution. It is split up so that the GUI freezes as little as possible, but it will still freeze during several portions (some potentially quite long) :return: ''' self.start_button.config(text='Running...') self.start_button.config(command=None) self.graph_button.grid_remove() self.start_button.grid_remove() self.start_button.grid(row=15, columnspan=3, column=0) debug = bool(self.debug.get()) if debug: print "Starting Data Recreation..." var = eval( compile(self.variance.get(), '<string>', 'eval', __future__.division.compiler_flag)) var_precision = abs( eval( compile(self.variance_precision.get(), '<string>', 'eval', __future__.division.compiler_flag))) if self.use_SD: min_var = max(0, (var - var_precision))**2 max_var = (var + var_precision)**2 var = (min_var + max_var) / 2 var_precision = (max_var - min_var) / 2 self.rd = RecreateData(self.min_score.get(), self.max_score.get(), self.num_subjects.get(), eval( compile(self.mean.get(), '<string>', 'eval', __future__.division.compiler_flag)), var, debug=debug, mean_precision=eval( compile(self.mean_precision.get(), '<string>', 'eval', __future__.division.compiler_flag)), variance_precision=var_precision) # self.rd.recreateData(check_val=self.getForcedVals(), poss_vals=self.poss_vals.getPossVals(), # multiprocess=True, find_first=(not bool(self.find_all.get()))) self.parent.after(5, self.main_2) def main_2(self): debug = bool(self.debug.get()) mean_var_pairs = self.rd._recreateData_piece_1( check_val=self.getForcedVals(), poss_vals=self.poss_vals.getPossVals(), multiprocess=True, find_first=(bool(self.find_first.get()))) partial_3 = wrapped_partial(self.main_3, mean_var_pairs) self.parent.after(5, partial_3) def main_3(self, mean_var_pairs): debug = bool(self.debug.get()) solution_spaces = self.rd._recreateData_piece_2( mean_var_pairs, check_val=self.getForcedVals(), poss_vals=self.poss_vals.getPossVals(), multiprocess=True, find_first=(bool(self.find_first.get()))) partial_4 = wrapped_partial(self.main_4, solution_spaces) self.parent.after(5, partial_4) def main_4(self, solution_spaces): debug = bool(self.debug.get()) if (bool(self.find_first.get())): self.rd._findFirst_piece_1(solution_spaces, check_val=self.getForcedVals(), poss_vals=self.poss_vals.getPossVals(), multiprocess=True, find_first=(bool( self.find_first.get()))) self.parent.after(5, self.main_6) else: init_bases, init_base_vecs, param_tuples = self.rd._findAll_piece_1_multi_proc( solution_spaces, check_val=self.getForcedVals(), poss_vals=self.poss_vals.getPossVals(), multiprocess=True, find_first=(bool(self.find_first.get()))) partial_5 = wrapped_partial(self.main_5, init_bases, init_base_vecs, param_tuples) self.parent.after(5, partial_5) def main_5(self, init_bases, init_base_vecs, param_tuples): debug = bool(self.debug.get()) self.rd._findAll_piece_2_multi_proc( init_bases, init_base_vecs, param_tuples, check_val=self.getForcedVals(), poss_vals=self.poss_vals.getPossVals(), multiprocess=True, find_first=(bool(self.find_first.get()))) self.parent.after(5, self.main_6) def main_6(self): debug = bool(self.debug.get()) self.start_button.config(text='Start') self.start_button.config(command=self.main) self.graph_button.grid() self.start_button.grid_remove() self.start_button.grid(row=15, columnspan=1, column=0) if len(self.rd.sols) > 0: self.rd.getDataSimple() if debug: print str( sum([len(x) for x in self.rd.simpleData.itervalues() ])) + " unique solutions found." index = 0 for params in self.rd.simpleData: if index > 100: break print "At mean, variance", params, ":" for simpleSol in self.rd.simpleData[params]: if index > 100: break index += 1 print simpleSol else: if debug: print str(len( self.rd.getDataSimple())) + " unique solutions found." def graph(self): self.rd.graphData() def _showOrHidePossVals(self): self.show_poss_vals = not self.show_poss_vals if self.show_poss_vals: self.poss_vals.grid() else: self.poss_vals.grid_remove() def _showOrHideForcedVals(self): self.show_forced_vals = not self.show_forced_vals if self.show_forced_vals: self.forced_vals.grid() else: self.forced_vals.grid_remove() def _switch_SD_Var(self): self.use_SD = not self.use_SD if self.use_SD: self.SD_Button.config(text='Switch to Variance Instead of SD') self.variance_label.config(text='Standard Deviation') self.variance.set(0.0) self.variance_precision_label.config(text='SD Precision') self.variance_precision.set(0.0) else: self.SD_Button.config(text='Switch to SD Instead of Variance') self.variance_label.config(text='Variance') self.variance.set(0.0) self.variance_precision_label.config(text='Variance Precision') self.variance_precision.set(0.0) def getForcedVals(self): current_forced = re.split('[,\s]+', self.forced_vals.get("1.0", "end-1c")) forced_vals = [ int(math.floor(eval(forced))) for forced in current_forced if len(forced) and (forced == '0' or (forced if forced.find('..') > -1 else forced. lstrip('-+').rstrip('0').rstrip('.')).isdigit()) and math.floor(eval(forced)) == eval(forced) ] forced_vals.sort() return forced_vals def clearInputFields(self): self.variance.set(0.0) self.mean.set(0.0) self.min_score.set(0) self.max_score.set(0) self.variance_precision.set(0.0) self.mean_precision.set(0.0) self.num_subjects.set(0) def clearOutputField(self): self.text_box.delete('1.0', END) def clearAll(self): self.clearInputFields() self.clearOutputField() def InitUI(self): from PIL import Image from PIL import ImageTk self.parent.lift() # image = Image.open("Corvid.png") # help_image = Image.open("Question.png") # photo = ImageTk.PhotoImage(image) # help_photo = ImageTk.PhotoImage(help_image) # img = PhotoImage(file="Corvid.png") # self.parent.tk.call('wm', 'iconphoto', self.parent._w, photo) self.parent.wm_title(string="CORVIDS") self.window = MenuItems(self.parent) self.window.addMenu("clearMenu", "Clear") self.window.addTopLevelMenuItem(self.window.fileMenu, "Load Settings", self.myLoadFunc(self.window), hotKey="<Control-o>") self.window.addTopLevelMenuItem(self.window.fileMenu, "Save Settings", self.mySaveFunc(self.window), hotKey="<Control-s>") self.window.addTopLevelMenuItem(self.window.fileMenu, "Load Model", self.myLoadModelFunc(self.window), hotKey="<Control-m>") self.window.addTopLevelMenuItem(self.window.fileMenu, "Save Model", self.mySaveModelFunc(self.window), hotKey="<Control-M>") self.window.addTopLevelMenuItem(self.window.fileMenu, "Save Data", self.mySaveDataFunc(self.window), hotKey="<Control-d>") self.window.addTopLevelMenuItem(self.window.clearMenu, "Clear Input Fields", self.clearInputFields) self.window.addTopLevelMenuItem(self.window.clearMenu, "Clear Output Field", self.clearOutputField) self.window.addTopLevelMenuItem(self.window.clearMenu, "Clear All", self.clearAll) self.window.addQuit() description_col = 0 field_col = 2 help_col = 1 self.debug = IntVar() self.debug.set(1) Checkbutton(self.parent, text="Show Progress", variable=self.debug).grid(column=description_col, row=0, sticky=W) self.find_first = IntVar() self.find_first.set(0) Checkbutton(self.parent, text="Stop After First Solution", variable=self.find_first).grid(column=field_col, row=0, sticky=E) Label(self.parent, text="Minimum Value", anchor='e').grid(row=1, column=description_col, sticky=N + S + E + W) self.min_score = IntVar() self.min_entry = Entry(self.parent, textvariable=self.min_score) self.min_entry.grid(row=1, column=field_col, sticky=E + W, padx=15) min_value_help = Button( self.parent, text="?", font=('TkDefaultFont', 8), command=doc_call_wrapper( "minimum-value", self.doc_dir)) #width=14, height=14)#, text="?") # min_value_help.config(image=help_photo) # min_value_help.image = help_photo min_value_help.grid(row=1, column=help_col, sticky=E + W) Label(self.parent, text="Maximum Value", anchor='e').grid(row=2, column=description_col, sticky=N + S + E + W) self.max_score = IntVar() self.max_entry = Entry(self.parent, textvariable=self.max_score) self.max_entry.grid(row=2, column=field_col, sticky=E + W, padx=15) max_value_help = Button( self.parent, text="?", font=('TkDefaultFont', 8), command=doc_call_wrapper( "maximum-value", self.doc_dir)) #width=14, height=14)#, text="?") # max_value_help.config(image=help_photo) # max_value_help.image = help_photo max_value_help.grid(row=2, column=help_col, sticky=E + W) Label(self.parent, text="Mean", anchor='e').grid(row=3, column=description_col, sticky=N + S + E + W) self.mean = StringVar() self.mean.set(0.0) self.mean_entry = Entry(self.parent, textvariable=self.mean) self.mean_entry.grid(row=3, column=field_col, sticky=E + W, padx=15) mean_help = Button( self.parent, text="?", font=('TkDefaultFont', 8), command=doc_call_wrapper( "mean", self.doc_dir)) #width=14, height=14)#, text="?") # mean_help.config(image=help_photo) # mean_help.image = help_photo mean_help.grid(row=3, column=help_col, sticky=E + W) Label(self.parent, text="Mean Precision", anchor='e').grid(row=4, column=description_col, sticky=N + S + E + W) self.mean_precision = StringVar() self.mean_precision.set(0.0) self.mean_precision_entry = Entry(self.parent, textvariable=self.mean_precision) self.mean_precision_entry.grid(row=4, column=field_col, sticky=E + W, padx=15) mean_precision_help = Button( self.parent, text="?", font=('TkDefaultFont', 8), command=doc_call_wrapper( "mean-precision", self.doc_dir)) #width=14, height=14)#, text="?") # mean_precision_help.config(image=help_photo) # mean_precision_help.image = help_photo mean_precision_help.grid(row=4, column=help_col, sticky=E + W) self.SD_Button = Button(self.parent, text="Switch to SD Instead of Variance", command=self._switch_SD_Var) self.SD_Button.grid(row=5, columnspan=3, column=description_col, sticky=E + W) self.variance_label = Label(self.parent, text="Variance", anchor='e') self.variance_label.grid(row=6, column=description_col, sticky=N + S + E + W) self.variance = StringVar() self.variance.set(0.0) self.variance_entry = Entry(self.parent, textvariable=self.variance) self.variance_entry.grid(row=6, column=field_col, sticky=E + W, padx=15) variance_help = Button( self.parent, text="?", font=('TkDefaultFont', 8), command=doc_call_wrapper( "variance", self.doc_dir)) #width=14, height=14)#, text="?") # variance_help.config(image=help_photo) # variance_help.image = help_photo variance_help.grid(row=6, column=help_col, sticky=E + W) self.variance_precision_label = Label(self.parent, text="Variance Precision", anchor='e') self.variance_precision_label.grid(row=7, column=description_col, sticky=N + S + E + W) self.variance_precision = StringVar() self.variance_precision.set(0.0) self.variance_precision_entry = Entry( self.parent, textvariable=self.variance_precision) self.variance_precision_entry.grid(row=7, column=field_col, sticky=E + W, padx=15) variance_precision_help = Button( self.parent, text="?", font=('TkDefaultFont', 8), command=doc_call_wrapper( "variance-precision", self.doc_dir)) #width=14, height=14)#, text="?") # variance_precision_help.config(image=help_photo) # variance_precision_help.image = help_photo variance_precision_help.grid(row=7, column=help_col, sticky=E + W) Label(self.parent, text="Number of Subjects", anchor='e').grid(row=8, column=description_col, sticky=N + S + E + W) self.num_subjects = IntVar() self.num_subjects_entry = Entry(self.parent, textvariable=self.num_subjects) self.num_subjects_entry.grid(row=8, column=field_col, sticky=E + W, padx=15) num_subjects_help = Button( self.parent, text="?", font=('TkDefaultFont', 8), command=doc_call_wrapper( "number-of-subjects", self.doc_dir)) #width=14, height=14)#, text="?") # num_subjects_help.config(image=help_photo) # num_subjects_help.image = help_photo num_subjects_help.grid(row=8, column=help_col, sticky=E + W) Label(self.parent, text="Possible Values", anchor='e').grid(row=9, column=description_col, sticky=N + S + E + W) # Button(self.parent, text="Possible Values", command=self._showOrHidePossVals).grid(row=8, columnspan=2, column=description_col, sticky=E+W) Button(self.parent, text="Show/Hide", command=self._showOrHidePossVals).grid(row=9, column=field_col, sticky=E + W, padx=15) self.poss_vals = PossValsText(self.parent, min_value=self.min_score, max_value=self.max_score, wrap='word', height=11, width=50) self.poss_vals.grid(row=10, columnspan=3, column=description_col, sticky=N + S + E + W) self.poss_vals.grid_remove() # poss_vals_frame = Frame(self.parent, height=10, width=10) # poss_vals_frame.grid(row=10, column=help_col, sticky=E+W) # poss_vals_help = Button(poss_vals_frame, text="?", font=('TkDefaultFont', 8)) #width=14, height=16)#, text="?") # poss_vals_help.pack() poss_vals_help = Button( self.parent, text="?", font=('TkDefaultFont', 8), command=doc_call_wrapper( "possible-values", self.doc_dir)) #width=14, height=16)#, text="?") # poss_vals_help.config(image=help_photo) # poss_vals_help.image = help_photo poss_vals_help.grid(row=9, column=help_col, sticky=E + W) Label(self.parent, text="Forced Values", anchor='e').grid(row=11, column=description_col, sticky=N + S + E + W) Button(self.parent, text="Show/Hide", command=self._showOrHideForcedVals).grid(row=11, column=field_col, sticky=E + W, padx=15) # Button(self.parent, text="Forced Values", command=self._showOrHideForcedVals).grid(row=10, columnspan=2, column=description_col, sticky=E+W) self.forced_vals = Text(self.parent, wrap='word', height=12, width=50) self.forced_vals.grid(row=12, columnspan=3, column=description_col, sticky=N + S + E + W) self.forced_vals.grid_remove() # forced_vals_frame = Frame(self.parent, height=10, width=10) # forced_vals_frame.grid(row=10, column=help_col, sticky=E+W) forced_vals_help = Button( self.parent, text="?", font=('TkDefaultFont', 8), command=doc_call_wrapper( "forced-values", self.doc_dir)) #width=14, height=16)#, text="?") # forced_vals_help.config(image=help_photo) # forced_vals_help.image = help_photo forced_vals_help.grid(row=11, column=help_col, sticky=E + W) Label(self.parent, text="Output:").grid(row=13, columnspan=3, column=description_col, sticky=E + W) # self.outputFrame = tk.Frame(self.parent) self.parent.columnconfigure(0, weight=1) self.parent.rowconfigure(14, weight=1) self.text_box = Text(self.parent, wrap='word', height=11, width=50) self.text_box.grid(row=14, columnspan=3, column=0, sticky=N + S + E + W) self.start_button = Button(self.parent, text="Start", command=self.main) self.start_button.grid(row=15, columnspan=3, column=0) self.graph_button = Button(self.parent, text="Graph", command=self.graph) self.graph_button.grid(row=15, column=field_col) self.graph_button.grid_remove() def setSettings(self, settings_file_full_path): ''' Takes a path and a filename and sets the simulation to that, informing the user that it has been loaded. :param settings_file_full_path: from root directory to filename and extension :return: ''' if self.debug.get(): print "Loading settings from " + settings_file_full_path self.settings_file = settings_file_full_path input_file = open(self.settings_file, 'rb') settings = cPickle.load(input_file) assert isinstance(settings, RecreateDataGUISettings) input_file.close() self.debug.set(settings.debug) self.min_score.set(settings.min_score) self.max_score.set(settings.max_score) self.poss_vals.delete("1.0", "end") self.poss_vals.insert("1.0", settings.poss_vals) self.mean.set(settings.mean) self.mean_precision.set(settings.mean_precision) if self.use_SD != settings.use_SD: self._switch_SD_Var() self.variance.set(settings.variance) self.variance_precision.set(settings.variance_precision) self.num_subjects.set(settings.num_samples) self.forced_vals.delete("1.0", "end") self.forced_vals.insert("1.0", settings.check_vals) def saveSettings(self, settings_file_full_path): if self.debug.get(): print "Saving settings to " + settings_file_full_path self.settings_file = settings_file_full_path settings_save_file = open(self.settings_file, 'wb') settings = RecreateDataGUISettings( self.debug.get(), self.min_score.get(), self.max_score.get(), self.poss_vals.get("1.0", "end-1c"), self.mean.get(), self.mean_precision.get(), self.variance.get(), self.variance_precision.get(), self.num_subjects.get(), self.forced_vals.get("1.0", "end-1c"), self.use_SD) cPickle.dump(settings, settings_save_file) settings_save_file.close() def saveModel(self, model_file_full_path): if self.debug.get(): print "Saving model to " + model_file_full_path self.model_file = model_file_full_path model_save_file = open(self.model_file, 'wb') cPickle.dump(self.rd, model_save_file) model_save_file.close() def loadModel(self, model_file_full_path): if self.debug.get(): print "Loading model from " + model_file_full_path self.model_file = model_file_full_path model_read_file = open(self.model_file, 'rb') self.rd = cPickle.load(model_read_file) assert isinstance(self.rd, RecreateData) model_read_file.close() self.graph_button.grid() self.start_button.grid_remove() self.start_button.grid(row=14, columnspan=1, column=0) def saveData(self, data_file_full_path): if self.debug.get(): print "Saving data to " + data_file_full_path self.data_file = data_file_full_path data_save_file = open(self.data_file, 'wb') if len(self.rd.sols) == 0: data_save_file.close() return dataStr = "" for param, solutions in self.rd.simpleData.iteritems(): dataStr += str(param) + ":\n" for sol in solutions: dataStr += "\t" + str(sol) + "\n" data_save_file.write(dataStr.strip()) data_save_file.close() def myLoadFunc_lambda(self, environment): lambda_new_window("openerWindow", environment, "Load Settings") lambda_make_file_loader(environment, "openerWindow", "opener", self.setSettings) def myLoadFunc(self, environment): return lambda environment=environment: self.myLoadFunc_lambda( environment) def mySaveFunc_lambda(self, environment): lambda_new_window("openerWindow", environment, "Save Settings") lambda_make_file_saver(environment, "openerWindow", "opener", self.saveSettings) def mySaveFunc(self, environment): return lambda environment=environment: self.mySaveFunc_lambda( environment) def mySaveDataFunc_lambda(self, environment): lambda_new_window("openerWindow", environment, "Save Data") lambda_make_file_saver(environment, "openerWindow", "opener", self.saveData) def mySaveDataFunc(self, environment): return lambda environment=environment: self.mySaveDataFunc_lambda( environment) def mySaveModelFunc_lambda(self, environment): lambda_new_window("openerWindow", environment, "Save Model") lambda_make_file_saver(environment, "openerWindow", "opener", self.saveModel) def mySaveModelFunc(self, environment): return lambda environment=environment: self.mySaveModelFunc_lambda( environment) def myLoadModelFunc_lambda(self, environment): lambda_new_window("openerWindow", environment, "Load Model") lambda_make_file_loader(environment, "openerWindow", "opener", self.loadModel) def myLoadModelFunc(self, environment): return lambda environment=environment: self.myLoadModelFunc_lambda( environment)
class AuthPage(BasePage): def __init__(self, parent, controller): self.is_auth = False self.mutex = Lock() BasePage.__init__(self, parent, controller) def prepare(self): mode = self.mode.get() user = self.userVar.get() pwd = self.pwdVar.get() if mode is 1 and user and pwd: self.confirm(mode, user, pwd) self.userInput.focus_force() def printErr(self, message): self.errLog.config(text=message) def entryToggle(self, toggle, target): if (toggle): for t in target: t.configure(state='normal') else: for t in target: t.configure(state='disabled') def confirm(self, mode, user, pwd): self.mutex.acquire() try: if mode == 1 and not self.is_auth: # mode:1 flash from pvt # TODO: the GUI do not updated due to the correct way to update the UI in tk is to use the after method. self.logger.log('Logging into server...', status_callback=self.printErr) if self.controller.setAuth(user, pwd): self.is_auth = True self.ok.config(state="disabled") self.userInput.config(state="disabled") self.pwdInput.config(state="disabled") self.controller.transition(self) else: self.printErr("Auththentication failed") else: # mode:2, flash from local pass finally: self.mutex.release() def pressReturnKey(self, event=None): if len(self.userVar.get()) > 0 and len(self.pwdVar.get()) > 0: self.confirm(self.mode.get(), self.userVar.get(), self.pwdVar.get()) elif len(self.userVar.get()) == 0: self.logger.log('Please enter username.', status_callback=self.printErr) self.userInput.focus_set() else: self.logger.log('Please enter password.', status_callback=self.printErr) self.pwdInput.focus_set() def setupView(self, title="Test Auth Page", user='', pwd_ori=''): self.mode = IntVar() self.mode.set(1) Label(self, width=25).grid(row=1, column=0, columnspan=2) self.errLog = Label(self, text="") self.errLog.grid(row=4, column=1, columnspan=3, rowspan=3, sticky="NWSE") self.userVar = StringVar() self.pwdVar = StringVar() Label(self, text="Account").grid(row=2, column=1, sticky='E') self.userInput = Entry(self, textvariable=self.userVar, width="30") self.userInput.grid(row=2, column=2, columnspan=2, sticky="W") Label(self, text="Password").grid(row=3, column=1, sticky='E') self.pwdInput = Entry(self, textvariable=self.pwdVar, show="*", width="30") self.pwdInput.grid(row=3, column=2, columnspan=2, sticky="W") self.userVar.set(user) self.pwdVar.set(pwd_ori) Label(self, text=' Welcome to fxos flash tool', font=TITLE_FONT).grid(row=0, column=1, columnspan=3, sticky="WE") Radiobutton(self, state='disabled', text='Download build from pvt', variable=self.mode, value=1, command=lambda: self.entryToggle( True, [self.userInput, self.pwdInput])).grid( row=1, column=2, columnspan=2, sticky="E") Radiobutton(self, state='disabled', text='Flash build from local', variable=self.mode, value=2, command=lambda: self.entryToggle( False, [self.userInput, self.pwdInput])).grid( row=1, column=4, sticky="W") self.ok = Button(self, text='Next', command=lambda: self.confirm(self.mode.get( ), self.userVar.get(), self.pwdVar.get())) self.ok.grid(row=4, column=4, sticky="W") self.userInput.bind('<Return>', self.pressReturnKey) self.pwdInput.bind('<Return>', self.pressReturnKey) self.ok.bind('<Return>', self.pressReturnKey)
class Game: """ This is our Game - everything important is handled here """ def __init__(self, parent): self.parent = parent self.level = 1 # create a board self.board = Board(self.parent, 100, "#ECECEC") # hex color gray self.board.draw_board() # create players self.player1 = Player("Human") self.player2 = Player("Computer") self.level_var = IntVar() # setting the player to Human as the Human starts self.player = self.player1 self.initialize_controls() self.layout() def initialize_controls(self, rest=False): label_text = StringVar() label_text.set("It is a %s's turn" % self.player.name) self.board.canvas.bind('<Button-1>', self.move) self.label = Label(self.board.container, textvariable=label_text) self.level1 = Radiobutton(self.board.container, text="Easy", variable=self.level_var, value=1, command=self.update_level) self.level2 = Radiobutton(self.board.container, text="Medium", variable=self.level_var, value=2, command=self.update_level) self.level3 = Radiobutton(self.board.container, text="Hard", variable=self.level_var, value=3, command=self.update_level) self.reset_button = Button(self.board.container, text="Reset", width=25, command=self.restart) def layout(self): # register buttons to board's container self.label.grid() self.level1.grid(row=0, column=1, sticky=W) self.level2.grid(row=1, column=1, sticky=W) self.level3.grid(row=2, column=1, sticky=W) self.level_var.set(self.level) self.reset_button.grid(row=4, sticky=E) def update_level(self): self.level = self.level_var.get() def restart(self): ''' Restart the game from the very beginning, reinitialize everything ''' self.board.container.destroy() self.player1.clean_moves() self.player2.clean_moves() self.board = Board(self.parent, 100, "#ECECEC") self.board.draw_board() self.player = self.player1 self.initialize_controls(rest=True) self.layout() def move(self, event): """ This method is called when the button is clicked :param event: this is a mouse click with coordinates """ if self.player.name == "Computer": self.computers_move() else: self.humans_move(event) def computers_move(self): xy_key = self.make_a_move(self.level) if xy_key is None: # something went wrong # need to handle it correctly self.result("We can't make a move any more!", "error") return x, y = self.board.translate_cells_dict_key_to_text_coords(xy_key) self.board.canvas.create_text(x, y, text="O", font=("Purisa", 60)) # update the unused cells dictionary self.player.add_move(self.board.unused_cells_dict[xy_key]) self.board.update_unused_cells_dict(xy_key) if self.check_if_won(): return self.player = self.player1 def humans_move(self, event): """ This function handles :param event: this is a click event """ if len(self.board.get_unused_cells_dict()) == 0: self.result("The game is over! Click Reset button", "info") return # a little logic to get the top left corner coords to draw the text floor_x, floor_y = self.board.get_floor_coord(event.x, event.y) xy_key = self.board.convert_coord_to_key(floor_x, floor_y) if not self.board.check_if_key_available(xy_key): self.result( "This cell is already busy - please, make another move", "warning") return x, y = self.board.translate_cells_dict_key_to_text_coords(xy_key) self.board.canvas.create_text(x, y, text="X", font=("Purisa", 60)) # update the unused cells dictionary self.player.add_move(self.board.unused_cells_dict[xy_key]) self.board.update_unused_cells_dict(xy_key) if self.check_if_won(): return self.player = self.player2 # imitate a button click for a computer move # with the event = None self.move(None) def make_a_move(self, level): """ Here we make a move according to the computer intelligence level """ unused_cells = self.board.get_unused_cells_dict() # if there's no more unused cells left # we can't move if len(unused_cells) == 0: return None cell_key = "" cells_list = unused_cells.keys() if level == 1: cell_key = choice(cells_list) if level == 3: # if it is the first move if len(unused_cells) == 8: corner_values = [1, 3, 7, 9] # if the first move was made in the corner if any(x in corner_values for x in self.player1.moves): return "11" # else if the center field is taken elif "11" not in unused_cells.keys(): tmp_unused_cells = [] for key, value in unused_cells.iteritems(): if value in corner_values: tmp_unused_cells.append(key) return choice(tmp_unused_cells) if level == 2 or level == 3: # check if there's any pair where we can win tmp_cell_key_computer = self.check_twos(self.player2) if tmp_cell_key_computer == []: # if there's no such pair we need to prevent human from winning tmp_cell_key_human = self.check_twos(self.player1) if tmp_cell_key_human == []: cell_key = choice(cells_list) else: cell_key = choice(tmp_cell_key_human) else: cell_key = choice(tmp_cell_key_computer) return cell_key def check_twos(self, player): result_list = [] for item in self.board.winning_combos: tmp_twos_dict = [[item[1], item[2]], [item[0], item[2]], [item[0], item[1]]] if tmp_twos_dict[0][0] in player.moves and tmp_twos_dict[0][ 1] in player.moves: result_list.append(item[0]) if tmp_twos_dict[1][0] in player.moves and tmp_twos_dict[1][ 1] in player.moves: result_list.append(item[1]) if tmp_twos_dict[2][0] in player.moves and tmp_twos_dict[2][ 1] in player.moves: result_list.append(item[2]) result_keys = self.board.convert_vals_to_keys(result_list) return result_keys def check_if_won(self): ''' Here we define if the current user wins the game or is t a tie ''' # if we did not do the 3 moves yet we could not have won if len(self.player.moves) < 3: return False for combo in self.board.winning_combos: if combo[0] in self.player.moves and \ combo[1] in self.player.moves and \ combo[2] in self.player.moves: self.result("%s wins!" % self.player.name, "info") self.board.unused_cells_dict = {} return True if len(self.board.get_unused_cells_dict()) == 0: self.result("It's a TIE!!!!", "info") return True def result(self, text, show_opt): ''' This function is gonna show the message box above the board ''' if show_opt == "info": tkMessageBox.showinfo(title="Congraulations!", message=text) elif show_opt == "warning": tkMessageBox.showwarning(title="Warning!", message=text) elif show_opt == "error": tkMessageBox.showerror(title="Error!!!", message=text)
class InterfaceParametres(Frame): """!Interface principale de l'outil de projection des modes expérimentaux sur les modes numériques permet la sélection et de calcul des modes en air et écoulement""" def __init__(self, root, objects, macro, mess, ): """!Constructeur """ Frame.__init__( self, root, relief='sunken', borderwidth=1) # Première frame self.mess = mess self.root = root self.logiciel = StringVar() self.salome_port = IntVar() self.machine_locale_name = self.get_machine_name() self.type_visu = StringVar() self.user = StringVar() self.protocole = StringVar() self.machine_name = self.machine_locale_name self.salome_widgets = [] self.distant_widgets = [] self.protocole_ok = None self.logiciel_courbes = None self.macro = macro self.objects = objects self.param_visu = self self.is_resu1 = IntVar() self.is_resu2 = IntVar() self.use_nume_mass = IntVar() self.proj_champ_meth = StringVar() self.proj_svd_param = StringVar() self.calculs = CalcEssaiExpansion(macro, mess, objects) self.type_resu_exp = StringVar() self.term = [] self.mac_windows = [] self.afreq = None self.anum = None self.resu_num = None # base d'expansion (instance de ModeMeca) self.resu_exp = None # donnees exp (instance de ModeMeca ou de DynaHarmo) self.interface_param() def setup(self): """!Appelée par le gestionnaire de tab lors de l'affichage""" mdo = self.objects mdo.recup_objects() self.menu_resu1.update( mdo.get_resultats_name(), self.var_resu1, self.visu1_changed) self.menu_resu2.update( mdo.get_resultats_name(), self.var_resu2, self.visu2_changed) pass def teardown(self): """!Appelée par le gestionnaire de tab lors du masquage (passage à un autre tab)""" return def _observabilite_changed(self): nom_resu = self.nom_obs_resu.get() if nom_resu.strip() != 'Choisir': resu = self.objects.get_resultats(nom_resu) nom_modele = self.nom_obs_modele.get() if nom_modele.strip() != 'Choisir': modele = self.objects.get_model(nom_modele) self.obs_noeuds.set_resultat(resu.modele) self.obs_mailles.set_resultat(resu.modele) def interface_param(self): """!Fonction principale de création de l'interface""" self.columnconfigure(0, weight=1) self.rowconfigure(2, weight=1) l = Label(self, text=u" CALC_ESSAI : Paramètres de visualisation", padx=270, pady=5, font=("Helvetica", "16")) l.grid(row=0, sticky='nsew') select_box = self.interface_parametres(self) select_box.grid(row=1, sticky='nsew') visu_param = self.interface_visu(self) visu_param.grid(row=3, sticky='nsew') self.main = self def interface_selection(self, root): self.var_resu_num = StringVar() self.menu_resu_num = MyMenu( f, options=self.objects.get_mode_meca_name(), var=self.var_resu_num, cmd=self.num_changed) self.var_resu_exp = StringVar() self.menu_resu_exp = MyMenu( f, options=self.objects.get_resultats_name(), var=self.var_resu_exp, cmd=self.exp_changed) return f def interface_visu(self, root): """!Création de l'interface de visualisation permet de choisir d'afficher les matrices MAC ou les modes avec gmsh gère la compatibilité des choix de l'utilisateur (les calculs de MAC ne sont pas tous possibles) """ mdo = self.objects f = Frame(root, relief='sunken', borderwidth=1) Label(f, text=" ").grid( row=0, column=1, columnspan=3, sticky='w' + 'e') Label(f, text=" ").grid( row=2, column=1, columnspan=3, sticky='w' + 'e') f.columnconfigure(0, weight=3) f.columnconfigure(1, weight=3) f1 = Frame(f) f1.grid(row=1, column=0, sticky='ew') f1.columnconfigure(1, weight=4) f1.columnconfigure(2, weight=4) bir1 = Checkbutton(f1, variable=self.is_resu1, command=self.cb_changed) bir1.grid(row=0, column=0, sticky='e', padx=20) bir2 = Checkbutton(f1, variable=self.is_resu2, command=self.cb_changed) bir2.grid(row=1, column=0, sticky='e', padx=20) Label(f1, text=u"Résultat 1").grid(row=0, column=1, sticky='w') self.var_resu1 = StringVar() self.menu_resu1 = MyMenu(f1, options=mdo.get_resultats_name(), var=self.var_resu1, cmd=self.visu1_changed) self.menu_resu1.grid(row=0, column=2, sticky='ew', padx=20) Label(f1, text=u"Résultat 2").grid(row=1, column=1, sticky='w') self.var_resu2 = StringVar() self.menu_resu2 = MyMenu(f1, options=mdo.get_resultats_name(), var=self.var_resu2, cmd=self.visu2_changed) self.menu_resu2.grid(row=1, column=2, sticky='ew', padx=20) f2 = Frame(f) f2.grid(row=1, column=1) self.mac_button = Button( f2, text=" MAC ", command=self.view_macs, state='disabled') self.mac_button.grid(row=1, column=2, sticky='ew') self.phi_button = Button( f2, text=u"Déformées", command=self.view_modes, state='disabled') self.phi_button.grid(row=2, column=2, sticky='ew') self.frf_button = Button(f2, text=" FRF ", command=self.view_frf) self.frf_button.grid(row=3, column=2, sticky='ew') self.frf_button = Button( f1, text=" Observation ", command=self.view_obs_1) self.frf_button.grid(row=0, column=3, sticky='ew') self.frf_button = Button( f1, text=" Observation ", command=self.view_obs_2) self.frf_button.grid(row=1, column=3, sticky='ew') return f def visu1_changed(self): """ desactivation du bouton concernant le visu1""" self.is_resu1.set(1) self.check_state() def visu2_changed(self): """ desactivation du bouton concernant le visu1""" self.is_resu2.set(1) self.check_state() def cb_changed(self): self.check_state() def check_state(self): """Verifie la compatibilite des bases pour le MAC et l'existence des donnees necessaires pour la visu des deformees et des FRF""" mdo = self.objects # Y a-t-il un MAC a calculer ? if (self.is_resu1.get() and not self.is_resu2.get()) or (self.is_resu2.get() and not self.is_resu1.get()): self.mac_button.configure(state='normal') elif self.is_resu1.get() and self.is_resu2.get(): resu1 = mdo.get_resultats(self.var_resu1.get()) resu2 = mdo.get_resultats(self.var_resu2.get()) if resu1.modele_name.strip() and resu1.modele_name == resu2.modele_name: self.mac_button.configure(state='normal') else: self.mac_button.configure(state='disabled') else: self.mac_button.configure(state='disabled') # Y a-t-il des deformees a representer ? if self.is_resu1.get() or self.is_resu2.get(): self.phi_button.configure(state='normal') else: self.phi_button.configure(state='disabled') def view_frf(self): """lancement d'une fenetre de visualisation des frf""" mdo = self.objects resu1 = None resu2 = None if self.is_resu1.get(): resu1 = mdo.get_resultats(self.var_resu1.get()) if self.is_resu2.get(): resu2 = mdo.get_resultats(self.var_resu2.get()) fenetre = DispFRFDialogue( self.mess, self.objects, self.param_visu, resu1, resu2) def view_obs_1(self): if self.is_resu1.get(): self.view_obs(self.var_resu1) else: self.mess.disp_mess(u"Choisir un résultat") return self.setup() def view_obs_2(self): if self.is_resu2.get(): self.view_obs(self.var_resu2) else: self.mess.disp_mess(u"Choisir un résultat") return self.setup() def view_obs(self, var_resu): """lancement d'une fenetre d'observation""" mdo = self.objects resu = mdo.get_resultats(var_resu.get()) fenetre = DispObs(self, self.mess, self.objects, resu) fenetre.set_resu(resu.nom) def view_modes(self, *args): """!Visualisation des modes par GMSH ou Salome""" mdo = self.objects l_resultat = [] l_modele = [] if self.is_resu1.get(): resu1 = mdo.get_resultats(self.var_resu1.get()) l_resultat.append(resu1.obj) if self.is_resu2.get(): resu2 = mdo.get_resultats(self.var_resu2.get()) l_resultat.append(resu2.obj) term = self.param_visu.visu_resu(resultat=l_resultat) self.term.append(term) return def view_macs(self): """!Creation d'une nouvelle fenetre de visu MAC""" mdo = self.objects resu1 = None resu2 = None if self.is_resu1.get() and self.is_resu2.get(): resu1 = mdo.get_resultats(self.var_resu1.get()) resu2 = mdo.get_resultats(self.var_resu2.get()) elif self.is_resu1.get(): resu1 = mdo.get_resultats(self.var_resu1.get()) resu2 = mdo.get_resultats(self.var_resu1.get()) elif self.is_resu2.get(): resu1 = mdo.get_resultats(self.var_resu2.get()) resu2 = mdo.get_resultats(self.var_resu2.get()) mac = self.calculs.calc_mac_mode(resu1, resu2, norme=None) self.param_visu.visu_mac(mac, resu1, resu2) def activate_salome_widgets(self): StateActivate(self.salome_widgets) def desactivate_salome_widgets(self): StateDesactivate(self.salome_widgets) def interface_parametres(self, root): """!Création de l'interface de choix des logiciels de visualisation On permet à l'utilisateur de choisir Gmsh/Xmgrace ou Salome """ main_param = Frame(root) main_param.rowconfigure(1, weight=1) main_param.columnconfigure(0, weight=1) f = Frame(main_param, relief='sunken', borderwidth=1) # les parametres vont dans 'f' logiciels_frame = Frame(f, borderwidth=4) label_parametres_salome = Label( logiciels_frame, text=u"Paramètres Salome") label_parametres_salome.grid(row=2, column=1, columnspan=2) self.salome_widgets.append(label_parametres_salome) label_port = Label(logiciels_frame, text=u"Port") label_port.grid(row=3, column=1, sticky='w') self.salome_widgets.append(label_port) entry_salome_port = Entry( logiciels_frame, textvariable=self.salome_port) entry_salome_port.grid(row=3, column=2) self.salome_widgets.append(entry_salome_port) self.salome_port.set(self.get_runnig_salome_port()) self.ce_salome = None liste_etudes = StudyList( logiciels_frame, self, u"choix de l'étude Salomé") liste_etudes.grid(row=4, column=2, sticky='w') self.salome_widgets.append(liste_etudes.liste) self.salome_widgets.append(liste_etudes.titre) liste_etudes.actualiser() label_choix_logiciel = Label( logiciels_frame, text=u"Choix du logiciel") label_choix_logiciel.grid(row=0, column=0, columnspan=3) button_gmsh = Radiobutton( logiciels_frame, text=u"Gmsh/Xmgrace", value="Gmsh/Xmgrace", variable=self.logiciel, command=self.desactivate_salome_widgets) button_gmsh.grid(row=1, column=0, sticky='w') button_salome = Radiobutton( logiciels_frame, text=u"Salomé", value="Salome", variable=self.logiciel, command=self.activate_salome_widgets) button_salome.grid(row=2, column=0, rowspan=3, sticky='w') self.logiciel.set("Salome") logiciels_frame.grid(row=1) f.grid(row=1, sticky='w' + 'e' + 's' + 'n') return main_param def get_user(self): import getpass user = getpass.getuser() return user def get_machine_name(self): """! Recupere le nom de la machine distante pour les parametres corba""" # on retourne le nom de la machine locale # XXX on ne peut pas utiliser un salome distant, # il faudrait un utilisateur et un chemin import socket machine_name = socket.gethostname() return machine_name def is_salome_launched(self): """! Determine si Salome est lance""" ok = False ret = os.system("ps auxw | grep -v grep | grep omniNames > /dev/null") if ret != 256: # Salome est lance ok = True return ok def get_runnig_salome_port(self): """! Recupere le port CORBA sur lequel est lance Salome pour les parametres corba""" salome_port = 2810 if self.is_salome_launched(): try: cmd = "ps auxw | grep -v grep | grep omniNames" p = Popen([cmd], shell=True, stdout=PIPE) data = p.communicate()[0] # On recupere la derniere ligne de ps pour avoir le dernier # numero de port l_data = data.split("\n") last_line = l_data[-2] omniNames_params = last_line.split(" ") idx = omniNames_params.index("-start") + 1 salome_port = int(omniNames_params[idx]) except: msg = u"Problème lors de la détermination du port Salome.\n" msg += u"Veuillez déterminer manuellement le port de Salome, en tapant ceci dans l'interpréteur python embarqué de Salome:\n" msg += u"import NSparam\n" msg += u"NSparam.getNSparams()" self.mess.disp_mess(msg) return salome_port def save_parameters(self, do_check_protocole=True): """! Sauvegarde les parametres dans une classe parente pour qu'ils soient communs a tous les onglets """ self.machine_name = self.machine_locale_name def get_logiciel(self): self.save_parameters() if self.logiciel.get() == "Gmsh/Xmgrace": return CalcEssaiGmsh(self.mess) else: if self.ce_salome: return self.ce_salome else: return CalcEssaiSalome( self.mess, self.machine_name, self.salome_port.get(), self.user.get(), self.protocole.get(), self.protocole_ok, self) pass def get_logiciel_courbes(self): # Les courbes sont transferees par CORBA # => Pas besoin de verifier le protocole rcp/scp self.save_parameters(do_check_protocole=False) if self.logiciel.get() == "Gmsh/Xmgrace": return CalcEssaiXmgrace() else: if self.ce_salome_courbes: return self.ce_salome_courbes else: return CalcEssaiSalomeCourbes(self.mess, self.machine_name, self.salome_port.get(), self) pass def visu_studylist(self): self.ce_salome = CalcEssaiSalome( self.mess, self.machine_name, self.salome_port.get(), self.user.get(), self.protocole.get(), self.protocole_ok, self) self.ce_salome_courbes = CalcEssaiSalomeCourbes( self.mess, self.machine_name, self.salome_port.get(), self) studylist = self.ce_salome.studylist() return studylist def set_study(self, study): self.ce_salome.study_name = study self.ce_salome_courbes.study_name = study self.mess.disp_mess( u"Les courbes et vues seront affichées dans l'étude Salomé " + study) # fonction proxy vers le bon logiciel def visu_resu(self, resultat, nume_mode=None): logiciel = self.get_logiciel() self.param_visu.type_visu.set('deformee') term = logiciel.visu_resu(resultat, nume_mode) return term def visu_mac(self, mac, resu1, resu2): logiciel = self.get_logiciel() term = logiciel.visu_mac(mac, resu1, resu2) return term def visu_courbe( self, l_x, ll_y, couleur=None, titre='Courbe', l_legende=None, legende_x="Abscisses", legende_y="Ordonnées", unite_x="ua", unite_y="ua"): self.logiciel_courbes = self.get_logiciel_courbes() self.logiciel_courbes.affiche(l_x, ll_y, couleur, titre, l_legende, legende_x, legende_y, unite_x, unite_y) pass def quit(self): for term in self.term: if term is not None: term.Fermer()
class TkApp: def __init__(self, ncffile, options): master = self.root = Tk() self.ncffile = ncffile self.options = options self.plotted_variables = set() frame = Frame(master) frame.grid(row = 0) codeframe = Frame(master) codeframe.grid(row = 1) metaframe = Frame(master) metaframe.grid(row = 2) goframe = Frame(frame) goframe.grid(column = 3, row = 1) var_label = Label(frame, text = 'Select Variable') var_label.grid(column = 0, row = 0) var_scrollbar = Scrollbar(frame, orient = VERTICAL) var_scrollbar.grid(column = 1, row = 1, sticky = N + S) self.var = Listbox(frame, selectmode = EXTENDED, exportselection = 0, yscrollcommand = var_scrollbar.set) self.var.grid(column = 0, row = 1) var_scrollbar.config(command = self.var.yview) what_to_do = Label(frame, text = 'Execute') what_to_do.grid(column = 2, row = 0) self.method_list = Listbox(frame, selectmode = SINGLE, exportselection = 0) self.method_list.grid(column = 2, row = 1) self.pre_txt = StringVar() pre_label = Label(codeframe, text = 'Before any figures, execute code') self.pre_txt.set(_pre_code) pre_label.grid(row = 2, sticky = 'W') self.pre = Entry(codeframe, width = 120, textvariable = self.pre_txt) self.pre.grid(row =3, sticky = 'E') self.before_txt = StringVar() self.before_txt.set(_before_code) before_label = Label(codeframe, text = 'Before each figure, execute code') before_label.grid(row = 4, sticky = 'W') self.before = Entry(codeframe, width = 120, textvariable = self.before_txt) self.before.grid(row =5, sticky = 'E') self.after_txt = StringVar() self.after_txt.set(_after_code) after_label = Label(codeframe, text = 'After each figure, execute code') after_label.grid(row = 6, sticky = 'W') self.after = Entry(codeframe, width = 120, textvariable = self.after_txt) self.after.grid(row =7, sticky = 'E') self.post_txt = StringVar() self.post_txt.set(_post_code) post_label = Label(codeframe, text = 'After all figures, execute code') post_label.grid(row = 8, sticky = 'W') self.post = Entry(codeframe, width = 120, textvariable = self.post_txt) self.post.grid(row = 9, sticky = 'E') options_label = Label(goframe, text = 'Options:') options_label.grid(column = 0, row = 1, sticky = 'W') self.logscale = IntVar() self.logscale.set(0) c = Checkbutton(goframe, text = "log-scale?", variable = self.logscale) c.grid(column = 0, row = 2, sticky = 'W') self.coastlines = IntVar() self.coastlines.set(_coastlines_opt) coastlines = Checkbutton(goframe, text = "coastlines?", variable = self.coastlines, justify = LEFT) coastlines.grid(column = 0, row = 3, sticky = 'W') self.countries = IntVar() self.countries.set(_countries_opt) countries = Checkbutton(goframe, text = "countries?", variable = self.countries, justify = LEFT) countries.grid(column = 0, row = 4, sticky = 'W') self.states = IntVar() self.states.set(_states_opt) states = Checkbutton(goframe, text = "states?", variable = self.states, justify = LEFT) states.grid(column = 0, row = 5, sticky = 'W') self.counties = IntVar() self.counties.set(_counties_opt) counties = Checkbutton(goframe, text = "counties?", variable = self.counties, justify = LEFT) counties.grid(column = 0, row = 6, sticky = 'W') self.execute_button = Button(goframe, text = "Make Figure", command = self.execute) self.execute_button.grid(row = 0, column = 0, sticky = 'W') self.methods = ['mapplot', 'presslat', 'presslon', 'time-lat', 'profile', 'timeseries', 'pressx', 'tileplot', 'plot'] method_labels= ['lat-lon', 'press-lat', 'press-lon', 'time-lat', 'Vertical Profile', 'Time Series', 'press-? (2-D)', 'Tile Plot (2-D)', 'Plot (1-D)'] for method in method_labels: self.method_list.insert(END, method) var_keys = [k for k, v in self.ncffile.variables.items() if k not in ('time', 'latitude', 'longitude', 'latitude_bounds', 'longitude_bounds', 'time_bounds', 'tau0', 'tau1', 'TFLAG')] var_keys.sort() self.vars = [] for spc in var_keys: self.var.insert(END, spc) self.vars.append(spc) meta_label = Label(metaframe, text = 'Common Data Language Header:') meta_label.grid(column = 0, row = 0, sticky = 'W') meta_scrollbar = Scrollbar(metaframe, orient = VERTICAL) meta_scrollbar.grid(column = 1, row = 1, sticky = N + S) self.meta = Text(metaframe, height=10, width=118, bg='white', relief='flat', yscrollcommand = meta_scrollbar.set) self.meta.grid(column = 0, row = 1, sticky = 'W') from PseudoNetCDF.pncdump import pncdump try: from StringIO import StringIO except ImportError: from io import StringIO pdump = StringIO("") try: name = ', '.join(options.ifile) except: name = 'ifile' pncdump(self.ncffile, header = True, outfile = pdump, ) pdump.seek(0, 0) self.meta.insert(END, pdump.read()) self.meta.config(state=DISABLED) help = Button(goframe, text = 'Help', command = self.help) help.grid(column = 0, row = 7) quit = Button(goframe, text = 'Quit', command = self.quit) quit.grid(column = 0, row = 8) master.mainloop() def help(self): print("pl is pylab: details at matplotlib;") def quit(self): self.root.destroy() def _get_var(self, list): items = list.curselection() try: items = map(int, items) except: pass items = [self.vars[i] for i in items] return items def get_var(self): return self._get_var(self.var) def get_methods(self): items = self.method_list.curselection() try: items = map(int, items) except: pass items = [self.methods[i] for i in items] return items def execute(self): os.system('clear') vars = self.get_var() self.plotted_variables = self.plotted_variables.union(vars) methods, = self.get_methods() self.options.logscale = bool(self.logscale.get()) self.options.coastlines = bool(self.coastlines.get()) self.options.countries = bool(self.countries.get()) self.options.states = bool(self.states.get()) self.options.counties = bool(self.counties.get()) self.options.pre_txt = self.pre_txt.get() self.options.before_txt = self.before_txt.get() self.options.after_txt = self.after_txt.get() self.options.post_txt = self.post_txt.get() plotwithopts(self.ncffile, methods, vars, self.options)