def test_invalid_value_domain(self): v = BooleanVar(self.root, name='name') self.root.globalsetvar('name', 'value') with self.assertRaises(TclError): v.get() self.root.globalsetvar('name', '1.0') with self.assertRaises(TclError): v.get()
def test_invalid_value_domain(self): v = BooleanVar(self.root, name="name") self.root.globalsetvar("name", "value") with self.assertRaises(TclError): v.get() self.root.globalsetvar("name", "1.0") with self.assertRaises(TclError): v.get()
def test_invalid_value_domain(self): false = 0 if self.root.wantobjects() else "0" v = BooleanVar(self.root, name="name") with self.assertRaises(TclError): v.set("value") self.assertEqual(self.root.globalgetvar("name"), false) self.root.globalsetvar("name", "value") with self.assertRaises(TclError): v.get() self.root.globalsetvar("name", "1.0") with self.assertRaises(TclError): v.get()
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Checkbutton") self.pack(fill=BOTH, expand=True) self.var = BooleanVar() cb = Checkbutton(self, text="Show title", variable=self.var, command=self.onClick) cb.select() cb.place(x=50, y=30) def onClick(self): if self.var.get() == True: self.master.title("Checkbutton") else: self.master.title("")
class MenuItem(object): def __init__(self, menu, title, **kwargs): self._menu = menu if kwargs.get('checkbox'): # Checkbox menu item self._checkvar = BooleanVar() self._checkvar.set(kwargs.get('checked', False)) self._menu._ctrl.add_checkbutton(label=title, command=self._on_check, variable=self._checkvar) else: # NOTE: For whatever reason, lambdas do not work in this case... self._menu._ctrl.add_command(label=title, command=self._on_click) if kwargs.get('on_click'): self.on_click = kwargs['on_click'] def _on_check(self): """Handler for keeping on_click virtual with checkbox option""" self.on_click(self._checkvar.get()) def _on_click(self): """Handler for keeping on_click virtual""" self.on_click() def on_click(self): pass def __exit__(self, *args): pass def __enter__(self, *args): return self
class MeasureFrame(LabelFrame): def __init__(self, master, tracker, text="Measuring", *args, **kwargs): LabelFrame.__init__(self, master, text=text, *args, **kwargs) self.tracker = tracker self.config_frame = NamedEntryFrame(self, (OBS_INTERVAL, NUM_SAMPLES, NUM_OBSS), parsers={OBS_INTERVAL: float, NUM_SAMPLES: int, NUM_OBSS: int}) self.config_frame.grid() self.save_frame = LabelFrame(self, text="Saving") self.dest_selector = FileSelectionFrame(self.save_frame, ask_mode="save") self.dest_selector.grid(row=0, column=0, columnspan=2) self.save_button = Button(self.save_frame, text="Save", command=bg_caller(self.save)) self.save_button.grid(row=1, column=0) self.appending_var = BooleanVar() self.append_checkbutton = Checkbutton(self.save_frame, text="Append", variable=self.appending_var) self.append_checkbutton.grid(row=1, column=1) self.save_frame.grid() def measure(self, only_accurate=True): try: interval = self.config_frame.get(OBS_INTERVAL) samples = self.config_frame.get(NUM_SAMPLES) num_obss = self.config_frame.get(NUM_OBSS) except ValueError: logger.error("Could not parse input fields.") data = self.tracker.measure(observation_interval=interval, samples_per_observation=samples, number_of_observations=num_obss) if only_accurate: accurate_data = [point for point in data if point.status == point.DATA_ACCURATE] num_invalid = len(data) - len(accurate_data) if num_invalid > 0: logger.warning("Hiding {} inaccurate data points." .format(num_invalid)) return accurate_data else: return data def save(self, only_accurate=True): dest = self.dest_selector.path_var.get() if not dest: logger.error("Must select a destination file.") return data = self.measure(only_accurate=only_accurate) w = csv.writer(open(dest, 'a' if self.appending_var.get() else 'w')) for point in data: w.writerow((point.time, point.position.r, point.position.theta, point.position.phi)) logger.info("Saved measurements into {!r}".format(dest))
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Checkbutton") self.pack(fill=BOTH, expand=True) self.var = BooleanVar() cb = Checkbutton(self, text="Show title", variable=self.var, command=self.onClick) cb.select() cb.place(x=50, y=50) def onClick(self): if self.var.get() == True: self.master.title("Checkbutton") else: self.master.title("")
def test_get(self): v = BooleanVar(self.root, True, "name") self.assertIs(v.get(), True) self.root.globalsetvar("name", "0") self.assertIs(v.get(), False) self.root.globalsetvar("name", 42 if self.root.wantobjects() else 1) self.assertIs(v.get(), True) self.root.globalsetvar("name", 0) self.assertIs(v.get(), False) self.root.globalsetvar("name", 42L if self.root.wantobjects() else 1L) self.assertIs(v.get(), True) self.root.globalsetvar("name", 0L) self.assertIs(v.get(), False) self.root.globalsetvar("name", "on") self.assertIs(v.get(), True) self.root.globalsetvar("name", u"0") self.assertIs(v.get(), False) self.root.globalsetvar("name", u"on") self.assertIs(v.get(), True)
def test_default(self): v = BooleanVar(self.root) self.assertEqual(False, v.get())
class FontChooser(ttkSimpleDialog.Dialog): BASIC = 1 ALL = 2 def __init__(self, parent, defaultfont=None, showstyles=None): self._family = StringVar(value="Century Schoolbook L") self._sizeString = StringVar(value="20") self._weight = StringVar(value=tkFont.NORMAL) self._slant = StringVar(value=tkFont.ROMAN) self._isUnderline = BooleanVar(value=False) self._isOverstrike = BooleanVar(value=False) if defaultfont: self._initialize(defaultfont) self._currentFont = tkFont.Font(font=self.getFontTuple()) self._showStyles = showstyles self.sampleText = None ttkSimpleDialog.Dialog.__init__(self, parent, "Font Chooser") def _initialize(self, aFont): if not isinstance(aFont, tkFont.Font): aFont = tkFont.Font(font=aFont) fontOpts = aFont.actual() self._family.set(fontOpts["family"]) self._sizeString.set(fontOpts["size"]) self._weight.set(fontOpts["weight"]) self._slant.set(fontOpts["slant"]) self._isUnderline.set(fontOpts["underline"]) self._isOverstrike.set(fontOpts["overstrike"]) def body(self, master): theRow = 0 ttkLabel(master, text="Font Family").grid(row=theRow, column=0) ttkLabel(master, text="Font Size").grid(row=theRow, column=2) theRow += 1 # Font Families fontList = ttk.Combobox(master, height=10, textvariable=self._family) fontList.grid(row=theRow, column=0, columnspan=2, sticky=N + S + E + W, padx=10) rawfamilyList = list(tkFont.families()) rawfamilyList.sort() # print rawfamilyList familyList = [] for family in rawfamilyList: if family[0] == "@": continue familyList.append(family) fontList.configure(values=familyList) fontList.bind("<<ComboboxSelected>>", self.selectionChanged) # Font Sizes sizeList = ttk.Combobox(master, height=10, width=5, textvariable=self._sizeString) sizeList.grid(row=theRow, column=2, columnspan=2, sticky=N + S + E + W, padx=10) sizes = [] for size in xrange(10, 50): sizes.append(str(size)) sizeList.configure(values=sizes) sizeList.bind("<<ComboboxSelected>>", self.selectionChanged) # Styles if self._showStyles is not None: theRow += 1 if self._showStyles in (FontChooser.ALL, FontChooser.BASIC): ttkLabel(master, text="Styles", anchor=W).grid(row=theRow, column=0, pady=10, sticky=W) theRow += 1 ttkCheckbutton( master, text="bold", command=self.selectionChanged, offvalue="normal", onvalue="bold", variable=self._weight, ).grid(row=theRow, column=0) ttkCheckbutton( master, text="italic", command=self.selectionChanged, offvalue="roman", onvalue="italic", variable=self._slant, ).grid(row=theRow, column=1) if self._showStyles == FontChooser.ALL: ttkCheckbutton( master, text="underline", command=self.selectionChanged, offvalue=False, onvalue=True, variable=self._isUnderline, ).grid(row=theRow, column=2) ttkCheckbutton( master, text="overstrike", command=self.selectionChanged, offvalue=False, onvalue=True, variable=self._isOverstrike, ).grid(row=theRow, column=3) # Sample Text theRow += 1 ttkLabel(master, text="Sample Text", anchor=W).grid(row=theRow, column=0, pady=10, sticky=W) theRow += 1 self.sampleText = Text(master, height=11, width=70) self.sampleText.insert(INSERT, "ABC...XYZ\nabc....xyz", "fontStyle") self.sampleText.config(state=DISABLED) self.sampleText.tag_config("fontStyle", font=self._currentFont) self.sampleText.grid(row=theRow, column=0, columnspan=4, padx=10) def apply(self): self.result = self.getFontTuple() def selectionChanged(self, something=None): self._currentFont.configure( family=self._family.get(), size=self._sizeString.get(), weight=self._weight.get(), slant=self._slant.get(), underline=self._isUnderline.get(), overstrike=self._isOverstrike.get(), ) if self.sampleText: self.sampleText.tag_config("fontStyle", font=self._currentFont) def getFontString(self): family = self._family.get() size = int(self._sizeString.get()) styleList = [] if self._weight.get() == tkFont.BOLD: styleList.append("bold") if self._slant.get() == tkFont.ITALIC: styleList.append("italic") if self._isUnderline.get(): styleList.append("underline") if self._isOverstrike.get(): styleList.append("overstrike") if len(styleList) == 0: return family + " " + str(size) else: xx = "" for x in styleList: xx = xx + " " + x return family + " " + str(size) + " " + xx def getFontTuple(self): family = self._family.get() size = int(self._sizeString.get()) styleList = [] if self._weight.get() == tkFont.BOLD: styleList.append("bold") if self._slant.get() == tkFont.ITALIC: styleList.append("italic") if self._isUnderline.get(): styleList.append("underline") if self._isOverstrike.get(): styleList.append("overstrike") if len(styleList) == 0: return family, size else: return family, size, " ".join(styleList)
class channel_plot: ''' ''' def __init__(self, interface, toplevel=False, start_t=False, stop_t=False): ''' ''' self.abort = False if not start_t: start_t = datetime.utcnow() - timedelta(hours=2) if not stop_t: stop_t = datetime.utcnow() self.update_pending = False self.pype = interface self.plot_dicts = {} if isinstance(start_t, datetime): self.start_t = StringVar(value=start_t.strftime(time_format)) elif isinstance(start_t, str): self.start_t = StringVar(value=start_t) else: raise TypeError('start_t must be string or datetime') if isinstance(stop_t, datetime): self.stop_t = StringVar(value=stop_t.strftime(time_format)) elif isinstance(stop_t, str): self.stop_t = StringVar(value=stop_t) else: raise TypeError('stop_t must be string or datetime') self.time_interval = [self.start_t.get(), self.stop_t.get()] self.ymin = DoubleVar() self.ymax = DoubleVar() if toplevel: self.toplevel = toplevel else: self.toplevel = Tk.Tk() self.status_var = StringVar(value='initializing') self._SetupCanvas() self._BuildGui() if not toplevel: Tk.mainloop() def _BuildGui(self): ''' ''' self.removei = IntVar(value=0) self.relative_start_time = BooleanVar(value=False) self.relative_stop_time = BooleanVar(value=False) self.continuous_updates = BooleanVar(value=False) self.ManualLimits = BooleanVar(value=False) self.LogYScale = BooleanVar(value=False) self.ShowGrid = BooleanVar(value=False) self.ConnectedPts = BooleanVar(value=True) Button(self.toplevel, text="Add Line", command=self._AddSubplot ).grid(row=0, column=1) self._AddSubplot() Button(self.toplevel, text="Gas Line Temps", command=self._PlotGasLines ).grid(row=0, column=2) Button(self.toplevel, text="Amps+Cell Temps", command=self._PlotCell ).grid(row=0, column=3) Label(self.toplevel, text='Start Time').grid(row=4, column=1) start_entry = Entry(self.toplevel, textvariable=self.start_t) start_entry.bind('<Return>', self.Update) start_entry.bind('<KP_Enter>', self.Update, '+') start_entry.grid(row=4, column=2, columnspan=2) Checkbutton(self.toplevel, text='Hours ago', variable=self.relative_start_time).grid(row=4, column=4, sticky='W') Label(self.toplevel, text='Stop Time').grid(row=5, column=1) stop_entry = Entry(self.toplevel, textvariable=self.stop_t) stop_entry.bind('<Return>', self.Update) stop_entry.bind('<KP_Enter>', self.Update, '+') stop_entry.grid(row=5, column=2, columnspan=2) Checkbutton(self.toplevel, text='Now', variable=self.relative_stop_time).grid(row=5, column=4, sticky='W') Label(self.toplevel, text='Y limits (min-max)').grid(row=7, column=1) ymin = Entry(self.toplevel, textvariable=self.ymin) ymin.grid(row=7, column=2) ymin.bind('<Return>', self.Update) ymin.bind('<KP_Enter>', self.Update, '+') ymax = Entry(self.toplevel, textvariable=self.ymax) ymax.grid(row=7, column=3) ymax.bind('<Return>', self.Update) ymax.bind('<KP_Enter>', self.Update, '+') Checkbutton(self.toplevel, text='Manual Y-limits', variable=self.ManualLimits ).grid(row=8, column=1) Checkbutton(self.toplevel, text='Log Y-scale', variable=self.LogYScale ).grid(row=8, column=2) Checkbutton(self.toplevel, text='Show Grid', variable=self.ShowGrid ).grid(row=9, column=1) Checkbutton(self.toplevel, text='Connected Points', variable=self.ConnectedPts ).grid(row=9, column=2) Button(self.toplevel, text="Update All", command=self.Update ).grid(row=10, column=1) Button(self.toplevel, text="Save Plot", command=self.SaveFigure ).grid(row=10, column=2) Button(self.toplevel, text="Save Json", command=self.SaveJson ).grid(row=10, column=3) Checkbutton(self.toplevel, text='Continuous (Button above to start)', variable=self.continuous_updates ).grid(row=11, column=1, columnspan=2) self.status_var.set('done') Label(self.toplevel, textvariable=self.status_var).grid(row=20, column=1, columnspan=2) def _SetupCanvas(self): ''' ''' self.figure = Figure() self.figure.subplots_adjust(left=0.15, bottom=0.2) self.subfigure = self.figure.add_subplot(1,1,1) self.notebook = Notebook(self.toplevel) self.notebook.grid(row=1, column=1, rowspan=3, columnspan=3, sticky='nsew') self.canvas = FigureCanvasTkAgg(self.figure, master=self.toplevel) self.canvas.show() self.canvas.get_tk_widget().grid(row=0, column=0, rowspan=10) def _AddSubplot(self): ''' ''' plotnum = len(self.notebook.tabs()) self.plot_dicts[plotnum] = {} frame = Frame(self.notebook) frame.pack(side='top', fill='both', expand='y') self.plot_dicts[plotnum]['xname'] = StringVar(value='None') self.plot_dicts['xunit'] = False self.plot_dicts[plotnum]['yname'] = StringVar(value='None') self.plot_dicts['yunit'] = False Label(frame, text='X Channel').grid(row=0, column=0) Label(frame, text='Y Channel').grid(row=1, column=0) OptionMenu(frame, self.plot_dicts[plotnum]['xname'], "None", "time", "dpph_field", *self.pype.EligibleLoggers() ).grid(row=0, column=1, sticky='ew') OptionMenu(frame, self.plot_dicts[plotnum]['yname'], "None", "dpph_field", *self.pype.EligibleLoggers() ).grid(row=1, column=1, sticky='ew') self.notebook.add(frame, text='line:'+str(plotnum)) def _SetStartStop(self, event=None): ''' ''' try: if self.relative_stop_time.get(): stop_time = datetime.utcnow() else: stop_time = datetime.strptime(self.stop_t.get(), time_format) if self.relative_start_time.get(): hours = float(self.start_t.get()) start = datetime.utcnow() - timedelta(hours=hours) else: start = datetime.strptime(self.start_t.get(), time_format) assert (start < stop_time) self.time_interval[0] = start.strftime(time_format) self.time_interval[1] = stop_time.strftime(time_format) except ValueError: showwarning('Warning', 'invalid time format, must match yyyy-mm-ddThh:mm:ssZ') raise TimeFormatError("invalid start or stop time format") except AssertionError: showwarning('Warning', 'time order error, stop time must be after start time') raise TimeOrderError("stop time must be after start time") def Update(self, event=None, tab='All', unpend=False): ''' Call whatever sequence is needed to update local data and redraw the plot ''' if self.abort: self.abort = False return if unpend: self.update_pending = False self.status_var.set('updating!') if tab == 'All': tab = range(len(self.notebook.tabs())) elif isinstance(tab, int): tab = [tab] else: raise ValueError('tab should be "All" or an int') try: self._SetStartStop(event=None) except: print('SetStartStop problems') self.abort = True self.subfigure.clear() for tabi in tab: if tabi > len(self.subfigure.get_lines()): print('wtf') elif tabi == len(self.subfigure.get_lines()): self._UpdateData(tab=tabi) self._MakePlot(tab=tabi) else: self._UpdateExisting(tab=tabi) self.figure.legends = [] self.figure.legend(*self.subfigure.get_legend_handles_labels()) self.figure.legends[0].draggable(True) self.canvas.draw() self.status_var.set('updated at: ' + datetime.utcnow().strftime(time_format)) if (self.continuous_updates.get() and self.relative_stop_time.get() and not self.update_pending): self.update_pending = True self.toplevel.after(10000, lambda: self.Update(unpend=True)) def _UpdateData(self, tab=0): ''' ''' try: yname = self.plot_dicts[tab]['yname'].get() ychdat = self.pype.GetTimeSeries(yname, self.time_interval[0], self.time_interval[1]) if self.plot_dicts[tab]['xname'].get() == 'time': xchdat = (ychdat[0], ychdat[0], 'time' * len(ychdat[0])) else: xname = self.plot_dicts[tab]['xname'].get() xchdat = self.pype.GetTimeSeries(xname, self.time_interval[0], self.time_interval[1]) if tab > 0 and ychdat[0]: assert xchdat[2][0] == self.plot_dicts['xunit'], 'x units' assert ychdat[2][0] == self.plot_dicts['yunit'], 'y units' self.xdata = [] self.ydata = [] if ychdat[0]: for tx, x in zip(xchdat[0], xchdat[1]): xtmp = False ytmp = False dt = timedelta(seconds=60) for ty, y in zip(ychdat[0], ychdat[1]): if abs(ty - tx) < dt: dt = abs(ty - tx) xtmp = x ytmp = y if xtmp and ytmp: self.xdata.append(xtmp) self.ydata.append(ytmp) [self.xdata, self.ydata] = zip(*sorted(zip(self.xdata, self.ydata))) self.plot_dicts['xunit'] = xchdat[2][0] self.plot_dicts['yunit'] = ychdat[2][0] except AssertionError as e: print('*'*60, '\n the', e[0], 'do not match the 0th line', '*'*60) def _UpdateExisting(self, tab=0): ''' ''' try: yname = self.plot_dicts[tab]['yname'].get() ychdat = self.pype.GetTimeSeries(yname, self.time_interval[0], self.time_interval[1]) if self.plot_dicts[tab]['xname'].get() == 'time': xchdat = (ychdat[0], ychdat[0], 'time' * len(ychdat[0])) else: xname = self.plot_dicts[tab]['xname'].get() xchdat = self.pype.GetTimeSeries(xname, self.time_interval[0], self.time_interval[1]) if tab > 0 and ychdat[0]: assert xchdat[2][0] == self.plot_dicts['xunit'], 'x units' assert ychdat[2][0] == self.plot_dicts['yunit'], 'y units' self.xdata = [] self.ydata = [] if ychdat[0]: for tx, x in zip(xchdat[0], xchdat[1]): xtmp = False ytmp = False dt = timedelta(seconds=60) for ty, y in zip(ychdat[0], ychdat[1]): if abs(ty - tx) < dt: dt = abs(ty - tx) xtmp = x ytmp = y if xtmp and ytmp: self.xdata.append(xtmp) self.ydata.append(ytmp) [self.xdata, self.ydata] = zip(*sorted(zip(self.xdata, self.ydata))) self.plot_dicts['xunit'] = xchdat[2][0] self.plot_dicts['yunit'] = ychdat[2][0] this_line = self.subfigure.get_lines()[tab] this_line.set_xdata(array(self.xdata)) this_line.set_ydata(array(self.ydata)) except AssertionError as e: print('*'*60, '\n the', e[0], 'do not match the 0th line', '*'*60) def _MakePlot(self, tab=0): ''' ''' if self.ConnectedPts.get(): plotformat='o-' else: plotformat='o' if self.plot_dicts[tab]['xname'].get() == 'time': self.subfigure.plot_date(self.xdata, self.ydata, plotformat, label=self.plot_dicts[tab]['yname'].get()) self.subfigure.set_xticklabels(self.subfigure.get_xticklabels(), rotation=-45) self.subfigure.xaxis.set_major_formatter(dates.DateFormatter( "%m/%d %H:%M")) self.subfigure.yaxis.set_major_formatter(ticker.ScalarFormatter( useOffset=False)) else: self.subfigure.plot(self.xdata, self.ydata, plotformat, label=self.plot_dicts[tab]['yname'].get()) self.subfigure.set_title(self.plot_dicts[tab]['yname'].get() + ' vs ' + self.plot_dicts[tab]['xname'].get() + '\n from ' + self.time_interval[0] + ' to ' + self.time_interval[1]) xname = self.plot_dicts[tab]['xname'].get().replace('_', ' ') xunit = '[' + str(self.plot_dicts['xunit']) + ']' self.subfigure.set_xlabel(xname + ' ' + xunit) yname = self.plot_dicts[tab]['yname'].get().replace('_', ' ') yunit = '[' + str(self.plot_dicts['yunit']) + ']' self.subfigure.set_ylabel(yname + ' ' + yunit) tickformat = ticker.ScalarFormatter(useOffset=False) if self.ManualLimits.get(): self.subfigure.set_ylim(bottom=self.ymin.get(), top=self.ymax.get()) if self.LogYScale.get(): self.subfigure.set_yscale('log') if self.ShowGrid.get(): self.subfigure.grid(b=True, which='major') self.subfigure.grid(b=True, which='minor') def _PlotGasLines(self): ''' ''' gas_lines = ['left_gas_line_lower_t', 'left_gas_line_upper_t', 'right_gas_line_lower_t', 'right_gas_line_upper_t'] self._PlotSet(gas_lines) def _PlotCell(self): ''' ''' sensors = ['kh2_temp', 'kh3_temp', 'waveguide_cell_body_temp', 'coldhead_temp'] self._PlotSet(sensors) def _PlotSet(self, channels): ''' Plots a set of channels on common axes ''' for plotn, channel in enumerate(channels): if (len(self.plot_dicts)-2) <= plotn: self._AddSubplot() self.plot_dicts[plotn]['xname'].set('time') self.plot_dicts[plotn]['yname'].set(channel) self.start_t.set('3') self.relative_start_time.set(True) self.relative_stop_time.set(True) self.continuous_updates.set(True) self.Update() def SaveFigure(self): ''' ''' file_extensions = [('vectorized', '.eps'), ('adobe', '.pdf'), ('image', '.png'), ('all', '.*')] outfile = asksaveasfilename(defaultextension='.pdf', filetypes=file_extensions) self.figure.savefig(outfile) def SaveJson(self): ''' ''' outfile = asksaveasfile(defaultextension='.json') outdict = {'xunit':self.plot_dicts['xunit'], 'yunit':self.plot_dicts['yunit'] } for tab in range(len(self.plot_dicts)-2): outdict[tab] = {} outdict[tab]['xname']=self.plot_dicts[tab]['xname'].get() outdict[tab]['yname']=self.plot_dicts[tab]['yname'].get() this_line = self.subfigure.get_lines()[tab] if outdict['xunit'] == 't': outdict[tab]['xdata'] = [str(t) for t in this_line.get_xdata()] else: outdict[tab]['xdata'] = list(this_line.get_xdata()) outdict[tab]['ydata'] = list(this_line.get_ydata()) dump(outdict, outfile, indent=4) outfile.close()
class MenuBar(Menu): def __init__(self, master, visible=True): self.root = master Menu.__init__(self, master.root) self.sc3_plugins = BooleanVar() self.sc3_plugins.set(SC3_PLUGINS) self.listening = BooleanVar() self.listening.set(False) # Set font self.config(font="CodeFont") # File menu filemenu = Menu(self, tearoff=0) filemenu.add_command(label="New Document", command=self.root.newfile, accelerator="Ctrl+N") filemenu.add_command(label="Open", command=self.root.openfile, accelerator="Ctrl+O") filemenu.add_command(label="Save", command=self.root.save, accelerator="Ctrl+S") filemenu.add_command(label="Save As...", command=self.root.saveAs) self.add_cascade(label="File", menu=filemenu) # Edit menu editmenu = Menu(self, tearoff=0) editmenu.add_command(label="Undo", command=self.root.undo, accelerator="Ctrl+Z") editmenu.add_command(label="Redo", command=self.root.redo, accelerator="Ctrl+Y") editmenu.add_separator() editmenu.add_command(label="Cut", command=self.root.edit_cut, accelerator="Ctrl+X") editmenu.add_command(label="Copy", command=self.root.edit_copy, accelerator="Ctrl+C") editmenu.add_command(label="Paste", command=self.root.edit_paste, accelerator="Ctrl+V") editmenu.add_command(label="Select All", command=self.root.selectall, accelerator="Ctrl+A") editmenu.add_separator() editmenu.add_command(label="Increase Font Size", command=self.root.zoom_in, accelerator="Ctrl+=") editmenu.add_command(label="Decrease Font Size", command=self.root.zoom_out, accelerator="Ctrl+-") editmenu.add_separator() editmenu.add_command(label="Toggle Menu", command=self.root.toggle_menu, accelerator="Ctrl+M") editmenu.add_checkbutton(label="Toggle Window Transparency", command=self.root.toggle_transparency, variable=self.root.transparent) self.add_cascade(label="Edit", menu=editmenu) # Code menu ctrl = "Command" if SYSTEM == MAC_OS else "Ctrl" # Note: Alt renders properly to look like Option, so we don't need a # conditional for those shortcuts codemenu = Menu(self, tearoff=0) codemenu.add_command(label="Evaluate Block", command=self.root.exec_block, accelerator="{}+Return".format(ctrl)) codemenu.add_command(label="Evaluate Line", command=self.root.exec_line, accelerator="Alt+Return") codemenu.add_command(label="Clear Scheduling Clock", command=self.root.killall, accelerator="{}+.".format(ctrl)) codemenu.add_separator() codemenu.add_command(label="Toggle Console", command=self.root.toggle_console) codemenu.add_command(label="Export Console Log", command=self.root.export_console) codemenu.add_separator() codemenu.add_checkbutton(label="Use SC3 Plugins", command=self.root.toggle_sc3_plugins, variable=self.sc3_plugins) codemenu.add_separator() codemenu.add_checkbutton(label="Listen for connections", command=self.allow_connections, variable=self.listening) self.add_cascade(label="Language", menu=codemenu) # Help helpmenu = Menu(self, tearoff=0) helpmenu.add_command(label="Visit FoxDot Homepage", command=self.root.openhomepage) helpmenu.add_command(label="Documentation", command=self.root.opendocumentation) helpmenu.add_separator() helpmenu.add_command(label="Open Samples Folder", command=self.root.open_samples_folder) helpmenu.add_command(label="Open config file (advanced)", command=self.root.open_config_file) ## settingsmenu.add_command(label="Change Colours...", command=self.root.toggleMenu) self.add_cascade(label="Help & Settings", menu=helpmenu) # Tutorials tutorialmenu = Menu(self, tearoff=0) for tutorial in GET_TUTORIAL_FILES(): filename = os.path.basename(tutorial).replace(".py", "") data = filename.split("_") num = data[0] name = " ".join(data[1:]).title() tutorialmenu.add_command(label="Load Tutorial {}: {}".format( num, name), command=partial(self.root.loadfile, tutorial)) self.add_cascade(label="Tutorials", menu=tutorialmenu) # Add to root self.visible = visible if self.visible: master.root.config(menu=self) def toggle(self): self.root.root.config(menu=self if not self.visible else 0) self.visible = not self.visible return def allow_connections(self): """ Starts a new instance of ServerManager.TempoServer and connects it with the clock """ if self.listening.get() == True: Clock = FoxDotCode.namespace["Clock"] Clock.start_tempo_server(TempoServer) print("Listening for connections on {}".format(Clock.tempo_server)) else: Clock = FoxDotCode.namespace["Clock"] Clock.kill_tempo_server() print("Closed connections") return
class SearchEngine: """Handles searching a text widget for Find, Replace, and Grep.""" def __init__(self, root): '''Initialize Variables that save search state. The dialogs bind these to the UI elements present in the dialogs. ''' self.root = root # need for report_error() self.patvar = StringVar(root, '') # search pattern self.revar = BooleanVar(root, False) # regular expression? self.casevar = BooleanVar(root, False) # match case? self.wordvar = BooleanVar(root, False) # match whole word? self.wrapvar = BooleanVar(root, True) # wrap around buffer? self.backvar = BooleanVar(root, False) # search backwards? # Access methods def getpat(self): return self.patvar.get() def setpat(self, pat): self.patvar.set(pat) def isre(self): return self.revar.get() def iscase(self): return self.casevar.get() def isword(self): return self.wordvar.get() def iswrap(self): return self.wrapvar.get() def isback(self): return self.backvar.get() # Higher level access methods def setcookedpat(self, pat): "Set pattern after escaping if re." # called only in SearchDialog.py: 66 if self.isre(): pat = re.escape(pat) self.setpat(pat) def getcookedpat(self): pat = self.getpat() if not self.isre(): # if True, see setcookedpat pat = re.escape(pat) if self.isword(): pat = r"\b%s\b" % pat return pat def getprog(self): "Return compiled cooked search pattern." pat = self.getpat() if not pat: self.report_error(pat, "Empty regular expression") return None pat = self.getcookedpat() flags = 0 if not self.iscase(): flags = flags | re.IGNORECASE try: prog = re.compile(pat, flags) except re.error as what: args = what.args msg = args[0] col = arg[1] if len(args) >= 2 else -1 self.report_error(pat, msg, col) return None return prog def report_error(self, pat, msg, col=-1): # Derived class could override this with something fancier msg = "Error: " + str(msg) if pat: msg = msg + "\nPattern: " + str(pat) if col >= 0: msg = msg + "\nOffset: " + str(col) tkMessageBox.showerror("Regular expression error", msg, master=self.root) def search_text(self, text, prog=None, ok=0): '''Return (lineno, matchobj) or None for forward/backward search. This function calls the right function with the right arguments. It directly return the result of that call. Text is a text widget. Prog is a precompiled pattern. The ok parameteris a bit complicated as it has two effects. If there is a selection, the search begin at either end, depending on the direction setting and ok, with ok meaning that the search starts with the selection. Otherwise, search begins at the insert mark. To aid progress, the search functions do not return an empty match at the starting position unless ok is True. ''' if not prog: prog = self.getprog() if not prog: return None # Compilation failed -- stop wrap = self.wrapvar.get() first, last = get_selection(text) if self.isback(): if ok: start = last else: start = first line, col = get_line_col(start) res = self.search_backward(text, prog, line, col, wrap, ok) else: if ok: start = first else: start = last line, col = get_line_col(start) res = self.search_forward(text, prog, line, col, wrap, ok) return res def search_forward(self, text, prog, line, col, wrap, ok=0): wrapped = 0 startline = line chars = text.get("%d.0" % line, "%d.0" % (line+1)) while chars: m = prog.search(chars[:-1], col) if m: if ok or m.end() > col: return line, m line = line + 1 if wrapped and line > startline: break col = 0 ok = 1 chars = text.get("%d.0" % line, "%d.0" % (line+1)) if not chars and wrap: wrapped = 1 wrap = 0 line = 1 chars = text.get("1.0", "2.0") return None def search_backward(self, text, prog, line, col, wrap, ok=0): wrapped = 0 startline = line chars = text.get("%d.0" % line, "%d.0" % (line+1)) while 1: m = search_reverse(prog, chars[:-1], col) if m: if ok or m.start() < col: return line, m line = line - 1 if wrapped and line < startline: break ok = 1 if line <= 0: if not wrap: break wrapped = 1 wrap = 0 pos = text.index("end-1c") line, col = map(int, pos.split(".")) chars = text.get("%d.0" % line, "%d.0" % (line+1)) col = len(chars) - 1 return None
class SearchEngine: def __init__(self, root): self.root = root # State shared by search, replace, and grep; # the search dialogs bind these to UI elements. self.patvar = StringVar(root) # search pattern self.revar = BooleanVar(root) # regular expression? self.casevar = BooleanVar(root) # match case? self.wordvar = BooleanVar(root) # match whole word? self.wrapvar = BooleanVar(root) # wrap around buffer? self.wrapvar.set(1) # (on by default) self.backvar = BooleanVar(root) # search backwards? # Access methods def getpat(self): return self.patvar.get() def setpat(self, pat): self.patvar.set(pat) def isre(self): return self.revar.get() def iscase(self): return self.casevar.get() def isword(self): return self.wordvar.get() def iswrap(self): return self.wrapvar.get() def isback(self): return self.backvar.get() # Higher level access methods def getcookedpat(self): pat = self.getpat() if not self.isre(): pat = re.escape(pat) if self.isword(): pat = r"\b%s\b" % pat return pat def getprog(self): pat = self.getpat() if not pat: self.report_error(pat, "Empty regular expression") return None pat = self.getcookedpat() flags = 0 if not self.iscase(): flags = flags | re.IGNORECASE try: prog = re.compile(pat, flags) except re.error, what: try: msg, col = what except: msg = str(what) col = -1 self.report_error(pat, msg, col) return None return prog
class CellularAutomataMain(Tk): GRID_WIDTH_PX = DisplayConfiguration.CA_CANVAS_MAX_PIX_X GRID_HEIGHT_PX = DisplayConfiguration.CA_CANVAS_MAX_PIX_Y def __init__(self, width_cells=DisplayConfiguration.DEFAULT_WIDTH, *args, **kwargs): Tk.__init__(self, *args, **kwargs) self.resizable(width=False, height=False) self.state = {'rules': None, 'rules_file': None, 'grid': None} self.random_start = BooleanVar(self) self.random_start.trace('w', self.random_start_callback) #Load blank grid self.width_cells = width_cells self.height_cells = width_cells # Default setting should probably have the grid be square. canvas_width = self.GRID_WIDTH_PX-80 canvas_height = self.GRID_HEIGHT_PX-80 self.state['grid'] = build_blank_grid(width_cells, width_cells) self.grid_display = GridDisplay(self, self.state['grid'], self.GRID_WIDTH_PX, self.GRID_HEIGHT_PX, width=canvas_width, height=canvas_height, relief=GROOVE, bd=4) self.grid_display.grid(row=0, column=0, padx=20, pady=20) #Build top menus self.menubar = Menu(self) try: self.config(menu=self.Menu) except AttributeError: self.tk.call(self, 'config', '-menu', self.menubar) self.file_menu = Menu(self, tearoff=False) self.file_menu.add_command(label="Load Ruleset", command=self.load_dialogue) self.file_menu.add_separator() self.file_menu.add_command(label="Save Automata (Image)", command=self.save_image_dialogue) self.file_menu.add_separator() self.file_menu.add_command(label="Quit", command=self.quit) self.menubar.add_cascade(menu=self.file_menu, label='File') self.config_menu = Menu(self, tearoff=False) self.config_menu.add_command(label='Set Dimensions', command=self.config_dimensions) self.config_menu.add_checkbutton(label='Set Grid Wrap') self.config_menu.add_checkbutton(label='Random Start Row', variable=self.random_start) self.bg_color_menu = self.build_selector_menu(GridDisplay.ALLOWED_COLORS, self.grid_display.set_bg_color, lambda: self.grid_display.draw_grid(self.state['grid']), 'white') self.fill_color_menu = self.build_selector_menu(GridDisplay.ALLOWED_COLORS, self.grid_display.set_fill_color, lambda: self.grid_display.draw_grid(self.state['grid']), 'black') self.config_menu.add_cascade(menu=self.bg_color_menu, label="Set Background Color...") self.config_menu.add_cascade(menu=self.fill_color_menu, label="Set Fill Color...") self.config_menu.add_separator() self.config_menu.add_command(label='Configure Plug-ins') self.plugin_menu = Menu(self) self.config_menu.add_cascade(menu=self.plugin_menu, label="Plugins...") self.menubar.add_cascade(menu=self.config_menu, label='Configure') self.menubar.add_command(label="About", command=self.about) #Load status bar self.status_bar_var = StringVar(self) self.status_bar_var.set('Initialized.') self.status_bar = Label(self, textvar=self.status_bar_var, relief=SUNKEN, justify=LEFT, anchor=W) self.status_bar.grid(row=1, column=0, sticky="EW", padx=2, pady=2) #Build plugin manager disp_logger.info('Loading plug-in manager') self.status_bar_var.set('Loading plug-in manager...') self.plugin_manager = PluginManager() self.plugin_manager.setPluginPlaces(['../plugins/']) self.plugin_manager.collectPlugins() disp_logger.info('Plug-in manager loaded. {} plug-ins were loaded.' ''.format(len(self.plugin_manager.getAllPlugins()))) def load_dialogue(self): new_rule_filename = tkFileDialog.askopenfilename(parent=self, title='Open Rule File', defaultextension=".txt", filetypes=[('Rules Files', '*.txt'), ('All Files', '*')]) if not new_rule_filename: return try: self.load(new_rule_filename) except: disp_logger.exception('Faulted loading rules file!') def save_image_dialogue(self): automata_image_filename = tkFileDialog.asksaveasfilename(parent=self, title='Save Automata Image', defaultextension='.eps', filetypes=[('Postscript', '.eps'), ('PNG', '.png'), ('JPEG', '.jpg')]) if not automata_image_filename: return try: #TODO: Should we be converting, or should I have a local image representation instead? if not automata_image_filename.endswith('.eps'): self.grid_display.postscript(file='tmp.eps') img = Image.open('tmp.eps') img.save(automata_image_filename) os.remove('tmp.eps') else: self.grid_display.postscript(file=automata_image_filename) self.status_bar_var.set('Saved automata image file as: {}'.format(automata_image_filename)) except: disp_logger.exception('Faulted saving automata image!') def load(self, rule_file): disp_logger.info('Attempting to load new rules file: {}'.format(rule_file)) rules = load_rules(rule_file) self.state['rules'] = rules self.state['rules_file'] = rule_file self._build_grid(rules) self.status_bar_var.set('Loaded rules file: {}'.format(rule_file)) def _build_grid(self, rules): grid = [] if self.random_start.get(): start_row = build_random_start_row(self.width_cells) else: start_row = build_default_start_row(self.width_cells) grid.append(start_row) grid.extend(evolve_system_multi(start_row, rules, self.height_cells)) self.state['grid'] = grid self.grid_display.draw_grid(grid) def config_dimensions(self): new_width, new_height = DimensionsDialog(self, title='Set Automata Dimensions', prompt='Set Automata Dimensions', x_name='Width', y_name='Height', x_default=self.width_cells, y_default=self.height_cells) if not new_width or not new_height: return disp_logger.info('Resizing automata to new width: {}, height: {}'.format(new_width, new_height)) self.width_cells = new_width self.height_cells = new_height self._build_grid(self.state['rules']) def random_start_callback(self, *args): self._build_grid(self.state['rules']) @staticmethod def about(): tkMessageBox.showinfo('About', '{app} ({ver})\nby {auth}, 2014' ''.format(ver=__version__, auth=__author__, app=__application_name__)) def build_selector_menu(self, choices, set_fxn, update_fxn=None, default=None): new_menu = Menu(self) choice_map = {} def build_selector_trace(var): def callback(*args): set_fxn(choice_map[var.get()]) if update_fxn: update_fxn() return callback if not default: default = choices[0] new_var = StringVar(new_menu) new_var.set(str(default)) new_var.trace('w', build_selector_trace(new_var)) for choice in choices: choice_map[str(choice)] = choice new_menu.add_radiobutton(label=str(choice).capitalize(), variable=new_var, value=str(choice)) return new_menu
class App(Frame): def __init__(self, master=None): self.master = master Frame.__init__(self, master, relief=SUNKEN, bd=2) self.gcode = [] self.slicing = False self.printing = False self.connected = False self.monitorTemp = False self.paused = False self.sdpresent = False self.sdlisting = False self.sdchecking = False self.sdprinting = False self.sdpaused = False self.sduploading = False self.sdbytes = 0 self.sdmaxbytes = 0 self.insidelisting = False self.readingFirmware = False self.sdfiles = [] self.bedtemp = float(0) self.bedtarget = float(0) self.exttemp = float(0) self.exttarget = float(0) self.acceleration = 0 self.m114count = 0 self.speedcount = 0 self.location = [0, 0, 0, 0] self.pausePoint = [0, 0, 0, 0] self.percent = 0.0 self.ets = "??" self.gcodeInfo = None self.GCodeFile = None self.StlFile = None self.Profile = None self.printStartLine = 0 self.startTime = 0 self.endTime = 0 self.elapsedTime = 0 self.FanSpeed = 0 self.FeedMultiply = 100 self.ExtrudeMultiply = 100 self.timingReport = None self.filamentReport = None self.measurementsReport = None self.macroButtons = None self.rpt1re = re.compile(" *T:([0-9\.]+) *E:[0-9\.]+ *B:([0-9\.]+)") self.rpt2re = re.compile(" *T:([0-9\.]+) *E:[0-9\.]+ *W:.*") self.locrptre = re.compile("^X:([0-9\.\-]+)Y:([0-9\.\-]+)Z:([0-9\.\-]+)E:([0-9\.\-]+) *Count") self.speedrptre = re.compile("Fan speed:([0-9]+) Feed Multiply:([0-9]+) Extrude Multiply:([0-9]+)") self.sdre = re.compile("SD printing byte *([0-9]+) *\/ *([0-9]+)") self.printer = printcore() self.settings = Settings() self.settings.cmdFolder = cmd_folder self.logger = Logger(self) if self.settings.speedcommand is not None: allow_while_printing.append(self.settings.speedcommand) self.acceleration = self.settings.acceleration self.dataLoggers = {} for d in DLLIST: self.dataLoggers[d] = DataLogger(self, d) self.skeinforge = Skeinforge(self.settings) self.slic3r = Slic3r(self.settings) self.httpServer = RepRapServer(self, self.printer, self.settings, self.logger, self.settings.port) self.menubar = Menu(self) self.filemenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="File", menu=self.filemenu) self.filemenu.add_command(label="Slice", command=self.openSTLFile) self.filemenu.add_command(label="Load GCode", command=self.openGCodeFile) self.slicemenuindex = self.filemenu.index("Slice") self.loadgcodemenuindex = self.filemenu.index("Load GCode") self.filemenu.add_separator() self.filemenu.add_command(label="Exit", command=self.quitApp) self.editmenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Edit", menu=self.editmenu) self.editmenu.add_command(label="Settings", command=self.editSettings) self.editmenu.add_command(label="Firmware Settings", command=self.FirmwareSettings) self.editmenu.add_separator() self.editmenu.add_command(label=GCODE_MENU_TEXT, command=self.doGEdit, state=DISABLED) self.slicermenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Slicer", menu=self.slicermenu) self.rbSlicer = StringVar() self.slicermenu.add_radiobutton( label="Skeinforge", command=self.selSlicer, value=SKEINFORGE, variable=self.rbSlicer ) self.slicermenu.add_command(label="Settings", command=self.skeinforgeSettings) self.slicermenu.add_command(label="Choose Profile", command=self.chooseSFProfile) self.SFprofileindex = self.slicermenu.index("Choose Profile") self.setSFProfileMenuText() self.slicermenu.add_command(label="Alterations", command=self.doEditAlterations) self.slicermenu.add_separator() self.slicermenu.add_radiobutton(label="Slic3r", command=self.selSlicer, value=SLIC3R, variable=self.rbSlicer) self.slicermenu.add_command(label="Settings", command=self.slic3rSettings) self.slicermenu.add_command(label="Choose Profile", command=self.chooseS3Profile) self.S3profileindex = self.slicermenu.index("Choose Profile") self.setS3ProfileMenuText() self.rbSlicer.set(self.settings.slicer) self.macromenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Macros", menu=self.macromenu) self.macromenu.add_command(label="New", command=self.doNewMacro) self.macromenu.add_command(label="Edit", command=self.doEditMacro) self.macromenu.add_command(label="Delete", command=self.doDelMacro) self.macromenu.add_separator() self.cbShowMacroButtons = BooleanVar() self.cbShowMacroButtons.set(self.settings.showmacrobuttons) self.macromenu.add_checkbutton( label="Show Macro Buttons", command=self.doShowButtons, onvalue=True, offvalue=False, variable=self.cbShowMacroButtons, ) self.macromenu.add_separator() self.runmacromenu = Menu(self.macromenu, tearoff=0) self.loadMacros() self.macromenu.add_cascade(label="Run", menu=self.runmacromenu) self.reportmenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="View", menu=self.reportmenu) self.cbShowPrevious = BooleanVar() self.cbShowPrevious.set(self.settings.showprevious) self.reportmenu.add_checkbutton( label="Show Previous Layer", command=self.toggleShowPrevious, onvalue=True, offvalue=False, variable=self.cbShowPrevious, ) self.cbShowMoves = BooleanVar() self.cbShowMoves.set(self.settings.showmoves) self.reportmenu.add_checkbutton( label="Show Non-extrusion Moves", command=self.toggleShowMoves, onvalue=True, offvalue=False, variable=self.cbShowMoves, ) self.reportmenu.add_separator() self.reportmenu.add_command(label="Show Hours of Usage", command=self.doDataLogReport) self.reportmenu.add_command(label="Reset Hours of Usage", command=self.doDataLogReset) self.reportmenu.add_separator() self.reportmenu.add_command(label="Layer by Layer Timing", command=self.doTimingReport) self.reportmenu.add_command(label="Layer by Layer Filament Usage", command=self.doFilamentReport) self.reportmenu.add_command(label="GCode Measurements", command=self.doMeasurementsReport) self.toolsmenu = Menu(self.menubar, tearoff=0) n = 0 if self.settings.platercmd is not None: n += 1 self.toolsmenu.add_command(label="Plater", command=self.doPlater) if self.settings.gcodeviewcmd is not None: n += 1 self.toolsmenu.add_command(label="GCode Viewer", command=self.doGCodeView) if self.settings.stlviewcmd is not None: n += 1 self.toolsmenu.add_command(label="STL Viewer", command=self.doSTLView) if self.settings.openscadcmd is not None: n += 1 self.toolsmenu.add_command(label="OpenSCAD", command=self.doOpenSCAD) if n > 0: self.menubar.add_cascade(label="Tools", menu=self.toolsmenu) try: self.master.config(menu=self.menubar) except AttributeError: self.master.tk.call(master, "config", "-menu", self.menubar) self.toolbar = ToolBar(self, self.printer, self.settings, self.logger) self.toolbar.grid(row=1, column=1, columnspan=4, sticky=W) self.ctl = MoveControl(self, self.printer, self.settings, self.logger) self.ctl.grid(row=2, column=1, rowspan=3, sticky=N) self.extr = Extruder(self, self.printer, self.settings, self.logger) self.extr.grid(row=2, column=2, rowspan=1, sticky=N + E + W) self.temps = Temperatures(self, self.printer, self.settings, self.logger) self.temps.grid(row=3, column=2, rowspan=2, sticky=N + E + W) self.gc = GcFrame(self, None, [], self.settings, self.logger) self.gc.grid(row=2, column=3, rowspan=3, sticky=N) self.statline = Status(self, self.printer, self.settings, self.logger) self.statline.grid(row=5, column=1, columnspan=4, sticky=E + W) self.logger.grid(row=2, column=4, rowspan=2, sticky=N + E + W) self.sendgcode = SendGCode(self, self.printer, self.settings, self.logger) self.sendgcode.grid(row=4, column=4, sticky=N + E + W) self.printer.errorcb = self.errorcb self.printer.sendcb = self.sendcb self.printer.recvcb = self.recvcb self.sd = SDCard(self, self.printer, self.settings, self.logger) self.firmware = FirmwareParms(self, self.printer, self.settings, self.logger) self.bind(MWM_FIRMWARECOMPLETE, self.firmwareReportComplete) self.bind(MWM_SLICERCOMPLETE, self.sliceComplete) self.bind(MWM_GCODELOADCOMPLETE, self.loadgcodeFinished) self.bind(MWM_GEDITMEASURECOMPLETE, self.geditMeasureComplete) self.bind(MWM_REQUESTPOSITIONREPORT, self.requestPosition) self.doShowButtons() def doStopAll(self): self.toolbar.doPause() self.temps.doOffBed() self.temps.doOffExt() def requestPosition(self, *arg): self.m114count += 1 self.printer.send_now("M400") # finish all moves self.printer.send_now("M114") def doShowButtons(self): self.settings.showmacrobuttons = self.cbShowMacroButtons.get() == 1 self.settings.setModified() if self.settings.showmacrobuttons: self.macroButtons = MacroButtons(self, self.printer, self.settings, self.logger) else: if self.macroButtons: self.macroButtons.close() self.macroButtons = None def toggleShowPrevious(self): self.settings.showprevious = self.cbShowPrevious.get() == 1 self.settings.setModified() self.gc.drawCanvas() def toggleShowMoves(self): self.settings.showmoves = self.cbShowMoves.get() == 1 self.settings.setModified() self.gc.drawCanvas() def selSlicer(self): self.settings.slicer = self.rbSlicer.get() self.settings.setModified() self.toolbar.setSliceText() def macroButtonClose(self): self.settings.showmacrobuttons = False self.settings.setModified() self.cbShowMacroButtons.set(False) def firmwareReportComplete(self, *arg): p = self.firmware.reportComplete() if p is not None: self.acceleration = p["m204_s"].getFlash() print "Retrieved acc value of ", self.acceleration def openSTLFile(self): if self.printing: self.logger.logMsg("Cannot open a new file while printing") return if self.StlFile is None: fn = askopenfilename( filetypes=[("STL files", "*.stl"), ("G Code files", "*.gcode")], initialdir=self.settings.lastdirectory ) else: fn = askopenfilename( filetypes=[("STL files", "*.stl"), ("G Code files", "*.gcode")], initialdir=self.settings.lastdirectory, initialfile=os.path.basename(self.StlFile), ) if fn: self.settings.lastdirectory = os.path.dirname(os.path.abspath(fn)) self.settings.setModified() if fn.lower().endswith(".gcode"): self.StlFile = None self.loadgcode(fn) elif fn.lower().endswith(".stl"): self.StlFile = fn self.doSlice(fn) else: self.logger.logMsg("Invalid file type") def openGCodeFile(self): if self.printing: self.logger.logMsg("Cannot open a new file while printing") return fn = askopenfilename(filetypes=[("G Code files", "*.gcode")], initialdir=self.settings.lastdirectory) if fn: self.settings.lastdirectory = os.path.dirname(os.path.abspath(fn)) self.settings.setModified() if fn.lower().endswith(".gcode"): self.StlFile = None self.loadgcode(fn) else: self.logger.logMsg("Invalid file type") else: self.toolbar.clearCancelMode() def loadgcode(self, fn): self.GCodeFile = fn self.gcodeloadSuccess = True self.toolbar.setLoading(True) self.loader = threading.Thread(target=self.loadgcodeThread) self.loader.daemon = True self.loader.start() def loadgcodeFinished(self, *arg): self.toolbar.setLoading(False) if self.gcodeloadSuccess: self.showMetrics() def loadgcodeThread(self): try: self.gcode = [] l = list(open(self.GCodeFile)) for s in l: self.gcode.append(s.rstrip()) self.logger.logMsg("read %d lines from %s" % (len(self.gcode), os.path.basename(self.GCodeFile))) except: self.logger.logMsg("Problem reading gcode from %s" % self.GCodeFile) self.gcode = [] self.GCodeFile = None if len(self.gcode) != 0: self.logger.logMsg("Processing...") self.gc.loadFile(self.GCodeFile, self.gcode) self.printStartLine = self.gc.getPrintStartLine() self.gcodeInfo = GCode(self.gcode) self.logger.logMsg("Measuring...") self.gcodeInfo.measure(self.acceleration) self.estEta = self.gcodeInfo.totalduration self.timeLayers = self.gcodeInfo.layerdurations else: self.gcodeloadSuccess = False self.event_generate(MWM_GCODELOADCOMPLETE) def replace(self, s, slicer): if slicer == SLIC3R: d = os.path.expandvars(os.path.expanduser(self.settings.s3profiledir)) profile = os.path.join(d, self.slic3r.getProfile() + ".ini") else: profile = self.skeinforge.getProfile() d = {} d["%starttime%"] = time.strftime("%H:%M:%S", time.localtime(self.startTime)) d["%endtime%"] = time.strftime("%H:%M:%S", time.localtime(self.endTime)) d["%elapsed%"] = formatElapsed(self.elapsedTime) d["%profile%"] = profile d["%slicer%"] = self.settings.slicer if self.StlFile is not None: d["%stlbase%"] = os.path.basename(self.StlFile) d["%stl%"] = self.StlFile else: d["%stlbase%"] = "" d["%stl%"] = "" if self.GCodeFile is not None: d["%gcodebase%"] = os.path.basename(self.GCodeFile) d["%gcode%"] = self.GCodeFile else: d["%gcodebase%"] = "" d["%gcode%"] = "" for t in d.keys(): if d[t] is not None: s = s.replace(t, d[t]) s = s.replace('""', "") return s def showMetrics(self): if len(self.gcode) != 0: self.paused = False self.toolbar.initializeToolbar() self.toolbar.checkAllowPrint() self.allowGEdit() self.logger.logMsg( "Width: %f mm (%f -> %f)" % (self.gcodeInfo.width, self.gcodeInfo.xmin, self.gcodeInfo.xmax) ) self.logger.logMsg( "Depth: %f mm (%f -> %f)" % (self.gcodeInfo.depth, self.gcodeInfo.ymin, self.gcodeInfo.ymax) ) self.logger.logMsg( "Height: is %f mm (%f -> %f)" % (self.gcodeInfo.height, self.gcodeInfo.zmin, self.gcodeInfo.zmax) ) self.logger.logMsg("Total extrusion length: %f mm" % self.gcodeInfo.filament_length()) self.logger.logMsg("Estimated print time: %s" % formatElapsed(self.estEta)) def calcEta(self, line, timeThusFar): foundLayer = False for i in range(len(self.timeLayers)): if self.timeLayers[i][0] > line: foundLayer = True break if not foundLayer: return 0 currentLayer = i - 1 if currentLayer < 0: return 0 totalInLayer = self.timeLayers[i][0] - self.timeLayers[currentLayer][0] printedInLayer = line - self.timeLayers[currentLayer][0] pct = printedInLayer / float(totalInLayer) thisLayerTime = (self.timeLayers[currentLayer][1]) * pct ratio = (self.timeLayers[currentLayer][2] - self.timeLayers[currentLayer][1] + thisLayerTime) / float( timeThusFar ) ne = self.estEta / float(ratio) return ne - timeThusFar def doTimingReport(self): if not self.printing: self.logger.logMsg("Only available while printing") return self.timingReport = TimingReport(self, self.printer, self.settings, self.logger) def closeTimingReport(self): if self.timingReport is not None: self.timingReport.cleanup() self.timingReport.destroy() self.timingReport = None def doMeasurementsReport(self): if not self.gcodeInfo: self.logger.logMsg("Only available when GCode loaded") return self.measurementsReport = MeasurementsReport(self, self.printer, self.settings, self.logger) def closeMeasurementsReport(self): if self.measurementsReport is not None: self.measurementsReport.destroy() self.measurementsReport = None def doFilamentReport(self): if not self.gcodeInfo: self.logger.logMsg("Only available when GCode loaded") return if len(self.gcodeInfo.filLayers) == 0: self.logger.logMsg("No filament usage in this gcode") return self.filamentReport = FilamentReport(self, self.printer, self.settings, self.logger) def closeFilamentReport(self): if self.filamentReport is not None: self.filamentReport.destroy() self.filamentReport = None def closeAllReports(self): self.closeTimingReport() self.closeFilamentReport() self.closeMeasurementsReport() def doPlater(self): s = self.replace(self.settings.platercmd, self.settings.slicer) args = shlex.split(os.path.expandvars(os.path.expanduser(s))) subprocess.Popen(args, close_fds=True) def doGCodeView(self): s = self.replace(self.settings.gcodeviewcmd, self.settings.slicer) args = shlex.split(os.path.expandvars(os.path.expanduser(s))) subprocess.Popen(args, close_fds=True) def doSTLView(self): s = self.replace(self.settings.stlviewcmd, self.settings.slicer) self.logger.logMsg(s) args = shlex.split(os.path.expandvars(os.path.expanduser(s))) subprocess.Popen(args, close_fds=True) def doOpenSCAD(self): s = self.replace(self.settings.openscadcmd, self.settings.slicer) args = shlex.split(os.path.expandvars(os.path.expanduser(s))) subprocess.Popen(args, close_fds=True) def doSlice(self, fn): self.paused = False self.toolbar.initializeToolbar() self.slicerfn = fn self.slicing = True self.slicerCancel = False self.toolbar.setCancelMode() if self.settings.slicer == SLIC3R: self.GCodeFile = fn.replace(".stl", ".gcode") cmd = self.replace(os.path.expandvars(os.path.expanduser(self.settings.s3cmd)), SLIC3R) else: self.GCodeFile = fn.replace(".stl", "_export.gcode") cmd = self.replace(os.path.expandvars(os.path.expanduser(self.settings.sfcmd)), SKEINFORGE) self.slicer = threading.Thread(target=self.slicerThread, args=(cmd,)) self.slicer.daemon = True self.slicer.start() def slicerThread(self, cmd): args = shlex.split(cmd) p = subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) obuf = "" while not self.slicerCancel: o = p.stdout.read(1) if o == "": break if o == "\r" or o == "\n": self.logger.logMsg(obuf) obuf = "" elif ord(o) < 32: pass else: obuf += o if self.slicerCancel: p.kill() p.wait() self.event_generate(MWM_SLICERCOMPLETE) def sliceComplete(self, *arg): self.slicing = False self.toolbar.clearCancelMode() if self.slicerCancel: self.slicerCancel = False self.logger.logMsg("Slicing was cancelled") return self.logger.logMsg("Slicing has completed successfully") if os.path.exists(self.GCodeFile): self.loadgcode(self.GCodeFile) else: self.logger.logMsg("Unable to find slicer output file: %s" % self.GCodeFile) def allowGEdit(self): self.editmenu.entryconfig(self.editmenu.index(GCODE_MENU_TEXT), state=NORMAL) def allowSliceMenu(self, flag=True): s = NORMAL if not flag: s = DISABLED self.filemenu.entryconfig(self.slicemenuindex, state=s) def allowLoadGCodeMenu(self, flag=True): s = NORMAL if not flag: s = DISABLED self.filemenu.entryconfig(self.loadgcodemenuindex, state=s) def doGEdit(self): GEditor(self, self.gcode, None) def geditMeasureComplete(self, *arg): self.showMetrics() def gEditSave(self, newgcode, fn, editwindow): if fn == None: self.gcode = newgcode self.meas = threading.Thread(target=self.geditMeasureThread) self.meas.daemon = True self.meas.start() return False else: try: f = open(fn, "w") for l in newgcode: f.write(l + "\n") f.close() self.logger.logMsg("Alterations %s successfully saved" % fn) return True except: self.logger.logMsg("Unable to open %s for output" % fn) return False def geditMeasureThread(self): self.logger.logMsg("Processing...") self.gcodeInfo = GCode(self.gcode) self.logger.logMsg("Measuring...") self.gcodeInfo.measure(self.acceleration) self.estEta = self.gcodeInfo.totalduration self.timeLayers = self.gcodeInfo.layerdurations self.event_generate(MWM_GEDITMEASURECOMPLETE) def doSD(self): if not self.sd.isActive(): self.sd.start() def setToolbarSDPrint(self): self.toolbar.setSDPrint() def startUpload(self): self.sduploading = True self.toolbar.doPrint() def printerAvailable(self, silent=False, cmd="xx"): if not self.connected: if not silent: self.logger.logMsg("Unable to comply - printer not on-line") return False if (self.printing or self.sdprinting) and cmd.upper() not in allow_while_printing: if not silent: self.logger.logMsg("Unable to comply - currently printing") return False return True def printerConnected(self, flag): self.sendgcode.activate(flag) self.connected = flag if flag: self.firmware.start(True) def updateScreen(self): if self.printing: self.gc.updatePrintProgress(self.printer.queueindex) def errorcb(self, s): self.logger.logMsg(s.rstrip()) def sendcb(self, s): # self.logger.logMsg("Sent: %s" % s) pass def recvcb(self, s): if self.readingFirmware: if "M92" in s: X = self.parseG(s, "X") Y = self.parseG(s, "Y") Z = self.parseG(s, "Z") E = self.parseG(s, "E") self.firmware.m92(X, Y, Z, E) return elif "M201" in s: X = self.parseG(s, "X") Y = self.parseG(s, "Y") Z = self.parseG(s, "Z") E = self.parseG(s, "E") self.firmware.m201(X, Y, Z, E) return elif "M203" in s: X = self.parseG(s, "X") Y = self.parseG(s, "Y") Z = self.parseG(s, "Z") E = self.parseG(s, "E") self.firmware.m203(X, Y, Z, E) return elif "M204" in s: S = self.parseG(s, "S") T = self.parseG(s, "T") self.firmware.m204(S, T) return elif "M205" in s: S = self.parseG(s, "S") T = self.parseG(s, "T") B = self.parseG(s, "B") X = self.parseG(s, "X") Z = self.parseG(s, "Z") E = self.parseG(s, "E") self.firmware.m205(S, T, B, X, Z, E) return elif "M206" in s: X = self.parseG(s, "X") Y = self.parseG(s, "Y") Z = self.parseG(s, "Z") self.firmware.m206(X, Y, Z) return elif "M301" in s: P = self.parseG(s, "P") I = self.parseG(s, "I") D = self.parseG(s, "D") self.firmware.m301(P, I, D) return elif ( ("Steps per unit" in s) or ("Acceleration:" in s) or ("Maximum Acceleration" in s) or ("Maximum feedrates" in s) or ("Advanced variables" in s) or ("Home offset" in s) or ("PID settings" in s) or ("Stored settings retreived" in s) ): return if self.sdchecking: if "SD card ok" in s: self.sdchecking = False self.sdpresent = True self.sd.sdCheckComplete(True) return elif "SD init fail" in s: self.sdchecking = False self.sdpresent = False self.sd.sdCheckComplete(False) return if self.sdlisting: if "Begin file list" in s: self.insidelisting = True self.sdfiles = [] return elif "End file list" in s: self.sdlisting = False self.insidelisting = False self.sd.sdListComplete(self.sdfiles) return else: if self.insidelisting: self.sdfiles.append(s.strip()) return if "SD printing byte" in s: m = self.sdre.search(s) t = m.groups() if len(t) != 2: return self.sdbytes = int(t[0]) self.sdmaxbytes = int(t[1]) return elif "Done printing file" in s: if self.sdprinting: self.sdprinting = False self.toolbar.clearSDPrint() m = self.speedrptre.search(s) if m: t = m.groups() if len(t) >= 3: if self.settings.forcefanspeed: ns = int(t[0]) if ns != self.FanSpeed: self.logger.logMsg("Asserting fan speed of %d" % self.FanSpeed) self.toolbar.forceFanSpeed(self.FanSpeed) else: self.FanSpeed = int(t[0]) self.FeedMultiply = int(t[1]) self.ExtrudeMultiply = int(t[2]) self.toolbar.syncSpeeds() if self.speedcount > 0: self.speedcount -= 1 return m = self.locrptre.search(s) if m: t = m.groups() if len(t) >= 4: self.location[XAxis] = float(t[0]) self.location[YAxis] = float(t[1]) self.location[ZAxis] = float(t[2]) self.location[EAxis] = float(t[3]) if self.m114count != 0: self.m114count -= 1 if self.m114count < 0: self.m114count = 0 return if s.startswith("ok"): return if s.startswith("echo:"): s = s[5:] m = self.rpt1re.search(s) if m: t = m.groups() if len(t) >= 1: self.exttemp = float(t[0]) if len(t) >= 2: self.bedtemp = float(t[1]) self.temps.updateTempDisplay(self.bedtemp, self.exttemp) m = self.rpt2re.search(s) if m: t = m.groups() if len(t) >= 1: self.exttemp = float(t[0]) self.temps.updateTempDisplay(self.bedtemp, self.exttemp) self.logger.logMsg(s.rstrip()) def parseG(self, s, v): l = s.split() for p in l: if p.startswith(v): try: return float(p[1:]) except: return None return None def editSettings(self): # TO DO pass def slic3rSettings(self): s = self.replace(self.settings.s3config, SLIC3R) args = shlex.split(os.path.expandvars(os.path.expanduser(s))) subprocess.Popen(args, close_fds=True) def skeinforgeSettings(self): s = self.replace(self.settings.sfconfig, SKEINFORGE) args = shlex.split(os.path.expandvars(os.path.expanduser(s))) subprocess.Popen(args, close_fds=True) def chooseS3Profile(self): pl = self.slic3r.getProfileOptions() if len(pl) > 0: l = ListBoxChoice( clist=pl.keys(), master=self, title="Choose Slic3r Profile", message="Choose Slic3r profile" ) pn = l.returnValue() if pn: self.slic3r.setProfile(pn) self.setS3ProfileMenuText() self.toolbar.setSliceText() else: self.logger.logMsg("Unable to retrieve available slic3r profiles") def chooseSFProfile(self): pl = self.skeinforge.getProfileOptions() if len(pl) > 0: l = ListBoxChoice( clist=pl.keys(), master=self, title="Choose Skeinforge Profile", message="Choose Skeinforge profile" ) pn = l.returnValue() if pn: self.skeinforge.setProfile(pn) self.setSFProfileMenuText() self.toolbar.setSliceText() else: self.logger.logMsg("Unable to retrieve available skeinforge profiles") def setS3ProfileMenuText(self): self.slicermenu.entryconfig(self.S3profileindex, label="Choose Profile (%s)" % self.slic3r.getProfile()) def setSFProfileMenuText(self): self.slicermenu.entryconfig(self.SFprofileindex, label="Choose Profile (%s)" % self.skeinforge.getProfile()) def quitApp(self): self.cleanUp() self.master.quit() def cleanUp(self): if self.connected: self.printer.disconnect() if self.slicing: self.slicerCancel = True self.httpServer.close() self.statline.cleanUp() self.settings.cleanUp() def doEditMacro(self): idir = os.path.join(self.settings.cmdFolder, "macros") try: l = os.listdir(idir) except: self.logger.logMsg("Unable to get listing from macros directory: " + idir) return r = [] for f in sorted(l): if f.endswith(".macro"): r.append(f) l = ListBoxChoice(master=self, title="Macro Files", message="Choose a macro to edit", clist=r) fn = l.returnValue() if fn: try: fn = os.path.join(idir, fn) with open(fn) as f: text = f.read() self.macroEdit = MacroEdit(self, self.printer, self.settings, self.logger, fn, text) except: self.logger.logMsg("Unable to open %s for input" % fn) def doEditAlterations(self): idir = os.path.expandvars(os.path.expanduser(self.settings.sfalterationsdir)) try: l = os.listdir(idir) except: self.logger.logMsg("Unable to get listing from alterations directory: " + idir) return r = [] for f in sorted(l): if f.endswith(".gcode"): r.append(f) l = ListBoxChoice(master=self, title="Alteration Files", message="Choose an alteration file to edit", clist=r) fn = l.returnValue() if fn: try: fn = os.path.join(idir, fn) text = [line.strip() for line in open(fn)] GEditor(self, text, fn) except: self.logger.logMsg("Unable to open %s for input" % fn) def doNewMacro(self): self.macroEdit = MacroEdit(self, self.printer, self.settings, self.logger, None, "") def doDelMacro(self): idir = os.path.join(self.settings.cmdFolder, "macros") try: l = os.listdir(idir) except: self.logger.logMsg("Unable to get listing from macros directory: " + idir) return r = [] for f in sorted(l): if f.endswith(".macro"): r.append(f) l = ListBoxChoice(master=self, title="Macro Files", message="Choose a macro to delete", clist=r) fn = l.returnValue() if fn: if askyesno("Delete?", "Are you sure you want to delete this macro?", parent=self): try: os.unlink(os.path.join(idir, fn)) self.adjustMacroMenu(fn, True) if self.settings.getMacroList().delMacroByName(fn): self.settings.setModified() if self.settings.showmacrobuttons: self.macroButtons.close() self.macroButtons = MacroButtons(self, self.printer, self.settings, self.logger) except: self.logger.logMsg("Unable to delete %s" % fn) def macroEditSave(self, fn, text, btn, editwindow): if fn == None: idir = os.path.join(self.settings.cmdFolder, "macros") try: l = os.listdir(idir) except: self.logger.logMsg("Unable to get listing from macros directory: " + idir) return r = [] for f in sorted(l): if f.endswith(".macro"): r.append(f) l = ListBoxChoice( master=self, title="Macro Files", message="Choose a macro to overwrite", clist=r, newmessage="or enter new file name:", ) fn = l.returnValue() if fn: fn = os.path.join(idir, fn) if not fn.endswith(".macro"): fn += ".macro" if fn is None: return False try: f = open(fn, "w") f.write(text) f.close() self.settings.setModified() if btn != None: if not self.settings.getMacroList().addMacro(btn[0], btn[1], os.path.basename(fn), btn[2]): self.settings.getMacroList().setMacroByName(btn[0], btn[1], os.path.basename(fn), btn[2]) self.settings.setModified() if self.settings.showmacrobuttons: self.macroButtons.close() self.macroButtons = MacroButtons(self, self.printer, self.settings, self.logger) self.adjustMacroMenu(fn) self.logger.logMsg("Macro %s successfully saved" % fn) return True except: self.logger.logMsg("Unable to open %s for output" % fn) return False def macroEditExit(self, fn): pass def loadMacros(self): p = os.path.join(".", "macros") if not os.path.exists(p): os.makedirs(p) self.macroList = {} for filename in sorted(os.listdir(p)): if filename.endswith(".macro"): n = os.path.splitext(filename)[0] self.macroList[n] = 1 self.runmacromenu.add_command(label=n, command=lambda m=n: self.doMacro(m)) def adjustMacroMenu(self, fn, delete=False): mn = os.path.splitext(os.path.basename(fn))[0] if not delete: if mn in self.macroList: # nothing to be done here pass else: self.macroList[mn] = 1 self.runmacromenu.add_command(label=mn, command=lambda m=mn: self.doMacro(name=mn)) else: # delete the menu entry if mn in self.macroList: self.runmacromenu.delete(self.runmacromenu.index(mn)) del self.macroList[mn] else: # huh?? pass def doMacro(self, name=None, fname=None, silent=False): if name: if not silent: self.logger.logMsg("Invoking macro: %s" % name) n = os.path.join(self.settings.cmdFolder, "macros", name + ".macro") elif fname: if not silent: self.logger.logMsg("Invoking macro file: %s" % fname) n = os.path.join(self.settings.cmdFolder, "macros", fname) else: self.logger.logMsg("Error - must provide a macro name or filename") return try: l = list(open(n)) for s in l: sl = s.lower() if sl.startswith("@log "): self.logger.logMsg(self.replace(s[5:].strip(), self.settings.slicer)) elif sl.startswith("@sh "): s = self.replace(sl[4:], self.settings.slicer) args = shlex.split(os.path.expandvars(os.path.expanduser(s))) subprocess.Popen(args, close_fds=True) else: verb = s.split()[0] if self.printerAvailable(cmd=verb): self.printer.send_now(s) else: self.logger.logMsg("Printer not available for %s command" % verb) if not silent: self.logger.logMsg("End of macro") except: self.logger.logMsg("Error attempting to invoke macro file %s" % n) def FirmwareSettings(self): if self.connected: if not self.firmware.isActive(): self.firmware.start() else: self.logger.logMsg("Unable to comply - printer not on-line") def doDataLogReport(self): for d in DLLIST: self.logger.logMsg("%s Usage: %s" % (DLNAMES[d], self.dataLoggers[d].getToNowStr())) def doDataLogReset(self): DataLogReset(self)
def __init__(self, master): # Master Window self.master = master NUMLINES = 32 BOXWIDTH = 42 BUTTONWIDTH = 24 CHECKWIDTH = 24 BUTTONPAD = 12 BG_COLOR1 = 'black' # Input Box BG_COLOR2 = '#301313' # Output Box BG_COLOR3 = '#131313' BG_COLOR4 = '#333333' BG_COLOR5 = '#433333' # Text FG_COLOR1 = 'white' FG_COLOR1 = 'grey' BD_COLOR1 = '#120000' FIELD_WIDTH = 9 # Delimiter Options # Display, characterString global MODES DELIMITERS = list(MODES.keys()) # Date String options DATEFORMATS = { 'YMDhm', 'YMD_hm', 'D/M/Y', 'D/M/Y h:m:s', 'D/M/Y h:m', 'Y-M-D', 'Y-M-D h:m:s', 'Y-M-D h:m' } # Initialize the source text. source_text_on_load = StringVar() source_text_on_load.set(self.getClipboard()) source_text = StringVar() source_text.set(source_text_on_load.get()) output_text = StringVar() output_text.set('') src_delimiter = StringVar() src_delimiter.set('\n') out_delimiter = StringVar() out_delimiter.set(',') out_quote = StringVar() out_quote.set('') prefix = StringVar() prefix.set('') suffix = StringVar() suffix.set('') find_text = StringVar() find_text.set('') replace_text = StringVar() replace_text.set('') capitalize = BooleanVar() remove_empty = BooleanVar() order_alpha = BooleanVar() unique_only = BooleanVar() skip_header = BooleanVar() capitalize.set(0) remove_empty.set(0) order_alpha.set(0) unique_only.set(0) skip_header.set(0) date_format = StringVar() date_format.set('YMDhm') ################## # NOTEBOOK 1 ################ ################# # TOP ################ top_frame = Frame(root, bg='', width=36, height=260, pady=3, padx=3) top_frame.pack() line_numbers = StringVar() for i in range(0, NUMLINES): line_numbers.set(line_numbers.get() + str(i + 1) + '\n') # Source Text Box source_text_frame = LabelFrame(top_frame, text='Source', fg=FG_COLOR1, bg=BD_COLOR1, width=20, height=400, pady=3, padx=3) source_text_frame.grid(row=0, column=1, sticky="nw") src_txt_line_numbers = Label(source_text_frame, textvar=line_numbers, fg=FG_COLOR1, bg=BG_COLOR4, anchor='ne', justify='right', width=2, height=NUMLINES, relief='raised') src_txt_line_numbers.grid(row=0, column=0) src_txt_box = Label(source_text_frame, textvar=source_text, fg=FG_COLOR1, bg=BG_COLOR3, anchor='nw', justify='left', wraplength=320, width=BOXWIDTH, height=NUMLINES, relief='raised') src_txt_box.grid(row=0, column=1) # Output Text Box output_text_frame = LabelFrame(top_frame, text='Output', fg=FG_COLOR1, bg=BD_COLOR1, width=20, height=400, pady=3, padx=3) output_text_frame.grid(row=0, column=3, sticky="ne") out_txt_box = Label(output_text_frame, textvar=line_numbers, fg=FG_COLOR1, bg=BG_COLOR5, anchor='ne', justify='right', width=2, height=NUMLINES, relief='raised') out_txt_box.grid(row=0, column=0) out_txt_box = Label(output_text_frame, textvar=output_text, fg=FG_COLOR1, bg=BG_COLOR2, anchor='nw', justify='left', wraplength=320, width=BOXWIDTH, height=NUMLINES, relief='raised') out_txt_box.grid(row=0, column=1) ################# # MIDDLE ################ # delimiter_frame = LabelFrame(master, fg=FG_COLOR1, bg=BG_COLOR1, pady=10, text='Delimiter Settings') # delimiter_frame.pack() delimiter_frame = LabelFrame(master, fg=FG_COLOR1, bg=BG_COLOR1, pady=10, text='Delmiter (From -> To)') delimiter_frame.pack() # MIDDLE LEFT src_delimiter_container = Frame(delimiter_frame, bg=BG_COLOR1, padx=5) src_delimiter_container.grid(sticky=('n', 'w', 's', 'e'), row=0, column=0, columnspan=3) # src_delimiter_label = Label(src_delimiter_container, text="Src", justify='left', height=1, width=3, anchor='e', relief='groove') # src_delimiter_label.grid(row=0, column=0, sticky=('n','w','s','e')) # src_delimiter_radio = Frame(src_delimiter_container, relief='groove') # src_delimiter_radio.grid(row=0, column=1, sticky=('n','w','s','e')) # # i = 0 # for text, mode in MODES: # b = Radiobutton(src_delimiter_radio, text=text, width=8, # variable=src_delimiter, value=mode, indicatoron=0) # b.grid(row=0, column=i) # i = i+1 src_delimiter_option = OptionMenu( delimiter_frame, src_delimiter, *DELIMITERS) # Pointer to option array src_delimiter_option.grid(row=0, column=0) # MIDDLE MIDDLE - Delimiter out_delimiter_container = Frame(delimiter_frame, bg=BG_COLOR1, padx=5) out_delimiter_container.grid(sticky=('n', 'w', 's', 'e'), row=1, column=0, columnspan=3) # out_delimiter_label = Label(out_delimiter_container, text="Out", justify='center', height=1, width=3, anchor='e', relief='groove') # out_delimiter_label.grid(sticky=('n','w','s','e'),row=0, column=0) # # out_delimiter_radio = Frame(out_delimiter_container, width=240, height=120, relief='groove') # out_delimiter_radio.grid(sticky=('n','w','s','e'),row=0, column=1) # # i = 1 # for text, mode in MODES: # if mode != 'none': # b = Radiobutton(out_delimiter_radio, text=text, width=8, # variable=out_delimiter, value=mode, indicatoron=0) # b.grid(row=0, column=i) # i = i+1 out_delimiter_option = OptionMenu( delimiter_frame, out_delimiter, *DELIMITERS) # Pointer to option array out_delimiter_option.grid(row=0, column=1) mid_container = Frame(master, bg=BG_COLOR1) mid_container.pack() textvar_container = LabelFrame(mid_container, fg=FG_COLOR1, bg=BG_COLOR1, pady=10, text='Text Operations') textvar_container.grid(row=0, column=0, columnspan=5) # MIDDLE BOTTOM - Quote out_quote_container = Frame(textvar_container, bg=BG_COLOR1, width=100, height=160, pady=8) out_quote_container.grid(row=0, column=0) out_quote_label = Label(out_quote_container, text="Quote", justify='center', width=FIELD_WIDTH, height=1, relief='groove') out_quote_label.grid(row=0, column=0) out_quote_entry = Entry(out_quote_container, textvar=out_quote, justify='center', width=FIELD_WIDTH, relief='groove', bg=FG_COLOR1, fg=BG_COLOR1) out_quote_entry.grid(row=1, column=0) # MIDDLE BOTTOM - Prefix prefix_container = Frame(textvar_container, bg=BG_COLOR1, width=100, height=160, pady=8) prefix_container.grid(row=0, column=1) prefix_label = Label(prefix_container, text="Prefix", justify='center', width=FIELD_WIDTH, height=1, relief='groove') prefix_label.grid(row=0, column=0) prefix_entry = Entry(prefix_container, textvar=prefix, justify='center', width=FIELD_WIDTH, relief='groove', bg=FG_COLOR1, fg=BG_COLOR1) prefix_entry.grid(row=1, column=0) # MIDDLE BOTTOM - Suffix suffix_container = Frame(textvar_container, bg=BG_COLOR1, width=100, height=160, pady=8) suffix_container.grid(row=0, column=2) suffix_label = Label(suffix_container, text="Suffix", justify='center', width=FIELD_WIDTH, height=1, relief='groove') suffix_label.grid(row=0, column=0) suffix_entry = Entry(suffix_container, textvar=suffix, justify='center', width=FIELD_WIDTH, relief='groove', bg=FG_COLOR1, fg=BG_COLOR1) suffix_entry.grid(row=1, column=0) ###################### # FIND REPLACE PANEL # ###################### find_container = Frame(textvar_container, bg=BG_COLOR1, width=100, height=160, pady=8) find_container.grid(row=0, column=3) find_label = Label(find_container, text="Replace", justify='left', width=FIELD_WIDTH, height=1, relief='groove') find_label.grid(row=0, column=0) find_entry = Entry(find_container, textvar=find_text, justify='left', width=FIELD_WIDTH * 2, relief='groove', bg=FG_COLOR1, fg=BG_COLOR1) find_entry.grid(row=1, column=0) replace_container = Frame(textvar_container, bg=BG_COLOR1, width=100, height=160, pady=8) replace_container.grid(row=0, column=4) replace_label = Label(replace_container, text="With", justify='left', width=FIELD_WIDTH, height=1, relief='groove') replace_label.grid(row=0, column=0) replace_entry = Entry(replace_container, textvar=replace_text, justify='left', width=FIELD_WIDTH * 2, relief='groove', bg=FG_COLOR1, fg=BG_COLOR1) replace_entry.grid(row=1, column=0) # DATE MENU date_frame = LabelFrame(mid_container, bg=BG_COLOR1, fg=FG_COLOR1, text='Date', width=650, height=280, pady=3, padx=3, relief='groove') date_frame.grid(row=0, column=6) date_option = OptionMenu(date_frame, date_format, *DATEFORMATS) # Pointer to option array date_option.grid(row=0, column=0) date_button = Button( date_frame, text="Copy", command=lambda: self.setClipboard(self.printDate(date_format.get()) ), width=BUTTONWIDTH / 2, highlightbackground=BG_COLOR1, ) date_button.grid(row=1, column=0) ################# # BOTTOM ################ control_frame = Frame(root, bg='', width=650, height=140, pady=3, padx=3, relief='groove') control_frame.pack() # # # BOTTOM LEFT src_control_container = Frame(control_frame, bg=BG_COLOR1, width=200, height=280, padx=BUTTONPAD) src_control_container.grid(sticky='w', row=0, column=0) # Refresh State to Load refresh_button = Button( src_control_container, text="Refresh To Load State", command=lambda: source_text.set(source_text_on_load.get()), width=BUTTONWIDTH, highlightbackground=BG_COLOR1) refresh_button.grid(row=0, column=0) clipboard_button = Button( src_control_container, text="Copy from Clipboard", command=lambda: source_text.set(self.getClipboard()), width=BUTTONWIDTH, highlightbackground=BG_COLOR1) clipboard_button.grid(row=1, column=0) pushback_button = Button( src_control_container, text="Output to Input", command=lambda: source_text.set(output_text.get()), width=BUTTONWIDTH, highlightbackground=BG_COLOR1) pushback_button.grid(row=2, column=0) # BOTTOM MIDDLE settings_container = Frame(control_frame, bg='grey', width=200, height=280, pady=3, padx=3) settings_container.grid(row=0, column=1) order_check = Checkbutton(settings_container, text="Alphabeticalize", variable=order_alpha, anchor='w', width=CHECKWIDTH) order_check.pack(anchor='w') cap_check = Checkbutton(settings_container, text="Capitalize", variable=capitalize, anchor='w', width=CHECKWIDTH) cap_check.pack(anchor='w') header_check = Checkbutton(settings_container, text="Skip Header", variable=skip_header, anchor='w', width=CHECKWIDTH) header_check.pack(anchor='w') rem_check = Checkbutton(settings_container, text="Strip Blanks", variable=remove_empty, anchor='w', width=CHECKWIDTH) rem_check.pack(anchor='w') unique_check = Checkbutton(settings_container, text="Unique Values", variable=unique_only, anchor='w', width=CHECKWIDTH) unique_check.pack(anchor='w') # BOTTOM RIGHT out_control_container = Frame(control_frame, bg=BG_COLOR1, width=200, height=280, padx=BUTTONPAD) out_control_container.grid(row=0, column=2) fr_button = Button( out_control_container, text="Find/Replace", command=lambda: output_text.set( self.findReplace(source_text.get(), find_text.get(), replace_text.get())), width=BUTTONWIDTH, highlightbackground=BG_COLOR1, ) fr_button.pack() go_button = Button( out_control_container, text="Process", command=lambda: output_text.set( self.process(source_text.get(), src_delimiter.get( ), out_delimiter.get(), out_quote.get(), order_alpha.get( ), skip_header.get(), remove_empty.get(), unique_only.get(), capitalize.get(), prefix.get(), suffix.get(), find_text.get(), replace_text.get())), width=BUTTONWIDTH, highlightbackground=BG_COLOR1, ) go_button.pack() copy_button = Button( out_control_container, text="Copy to Clipboard", command=lambda: self.setClipboard(output_text.get()), width=BUTTONWIDTH, highlightbackground=BG_COLOR1) copy_button.pack() close_button = Button(out_control_container, text="Quit", command=master.quit, width=BUTTONWIDTH, highlightbackground=BG_COLOR1) close_button.pack()
class GrepDialog(SearchDialogBase): title = "Find in Files Dialog" icon = "Grep" needwrapbutton = 0 bottom_btns = [("Search Files", 'default_command', 1)] def __init__(self, root, engine, flist): SearchDialogBase.__init__(self, root, engine) self.flist = flist self.globvar = StringVar(root) self.recvar = BooleanVar(root) def open(self, text, searchphrase, io=None): SearchDialogBase.open(self, text, searchphrase) if io: path = io.filename or "" else: path = "" dir, base = os.path.split(path) head, tail = os.path.splitext(base) if not tail: tail = ".py" self.globvar.set(os.path.join(dir, "*" + tail)) def create_entries(self): SearchDialogBase.create_entries(self) self.globent = self.make_entry("In files", self.globvar) def create_other_buttons(self): f = self.make_frame() btn = Checkbutton(f, variable=self.recvar, text="Recurse down subdirectories") btn.pack(side="top", fill="both") btn.invoke() def create_command_buttons(self): SearchDialogBase.create_command_buttons(self) def default_command(self, event=None): prog = self.engine.getprog() if not prog: return path = self.globvar.get() if not path: self.top.bell() return from OutputWindow import OutputWindow save = sys.stdout try: sys.stdout = OutputWindow(self.flist) self.grep_it(prog, path) finally: sys.stdout = save def grep_it(self, prog, path): dir, base = os.path.split(path) list = self.findfiles(dir, base, self.recvar.get()) list.sort() self.close() pat = self.engine.getpat() print "Searching %r in %s ..." % (pat, path) hits = 0 for fn in list: try: f = open(fn) except IOError, msg: print msg continue lineno = 0 while 1: block = f.readlines(100000) if not block: break for line in block: lineno = lineno + 1 if line[-1:] == '\n': line = line[:-1] if prog.search(line): sys.stdout.write("%s: %s: %s\n" % (fn, lineno, line)) hits = hits + 1 if hits: if hits == 1: s = "" else: s = "s" print "Found", hits, "hit%s." % s print "(Hint: right-click to open locations.)" else: print "No hits."
class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.grid() #ENTRY CELL self.entryVariable = StringVar() self.entry = Tkinter.Entry(self,textvariable=self.entryVariable) self.entry.grid(column=0,row=0,sticky='EW') self.entry.bind("<Return>", self.OnPressEnter) self.entryVariable.set(u"Enter text here.") #CLICK BUTTON button = Tkinter.Button(self,text=u"Click me !",command=self.OnButtonClick) button.grid(column=1,row=0) #CHECK BOX self.var = BooleanVar() cb = Tkinter.Checkbutton(self, text="Show title",variable=self.var, command=self.onClick) cb.select() cb.grid(column=0,row=5,sticky='W') ## #COMBO BOX ## self.combo = StringVar() ## self.box = ttk.Combobox(self.parent, textvariable=self.box) ## self.box['values'] = ('X', 'Y', 'Z') ## self.box.current(0) ## self.box.grid(column=0, row=4,sticky='W') #LABEL self.labelVariable = Tkinter.StringVar() label = Tkinter.Label(self,textvariable=self.labelVariable,anchor="w",fg="white",bg="blue") label.grid(column=0,row=1,columnspan=2,sticky='EW') self.labelVariable.set(u"Hello !") # MENU menubar = Tkinter.Menu(self.parent) # level0: -- menubar-- self.config(menu=menubar) fileMenu = Tkinter.Menu(menubar) #level1: filemenu menubar.add_cascade(label="File", menu=fileMenu) # add to menubar submenu = Tkinter.Menu(menubar) #level2: submenu fileMenu.add_cascade(label='Import', menu=submenu) # add to filemenu submenu.add_command(label="test1",command=self.test1)# level3: add under submenu submenu.add_command(label="test2",command=self.test2) fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self.destroy)# level2: under filemenu self.grid_columnconfigure(0,weight=1) # just formatting self.resizable(True,False) self.update() self.geometry(self.geometry()) self.entry.focus_set() self.entry.selection_range(0, Tkinter.END) #QUIT quitButton = Tkinter.Button(self, text="Quit",command=self.destroy) quitButton.grid(column=1,row=5,sticky='E') def OnButtonClick(self): self.labelVariable.set(self.entryVariable.get()+" (TEST)" ) self.entry.focus_set() self.entry.selection_range(0, Tkinter.END) def OnPressEnter(self,event): self.labelVariable.set(self.entryVariable.get()+" (TEST)") self.entry.focus_set() self.entry.selection_range(0, Tkinter.END) def onClick(self): if self.var.get() == True: a=1 else: a=1 def test1(self): ftypes = [('Python files', '*.py'), ('All files', '*')] dlg = tkFileDialog.Open(self, filetypes = ftypes) fl = dlg.show() if fl != '': text = self.readFile(fl) # get "text" self.labelVariable.set(text) # display in label def test2(self): a=1 def readFile(self, filename): f = open(filename, "r") text = f.read() return text
class FontChooser( tkSimpleDialog.Dialog ): BASIC = 1 ALL = 2 def __init__( self, parent, defaultfont=None, showstyles=None ): self._family = StringVar( value='Century Schoolbook L') self._sizeString = StringVar( value='20' ) self._weight = StringVar( value=tkFont.NORMAL ) self._slant = StringVar( value=tkFont.ROMAN ) self._isUnderline = BooleanVar( value=False ) self._isOverstrike = BooleanVar( value=False ) if defaultfont: self._initialize( defaultfont ) self._currentFont = tkFont.Font( font=self.getFontTuple() ) self._showStyles = showstyles self.sampleText = None tkSimpleDialog.Dialog.__init__( self, parent, 'Font Chooser' ) def _initialize( self, aFont ): if not isinstance( aFont, tkFont.Font ): aFont = tkFont.Font( font=aFont ) fontOpts = aFont.actual( ) self._family.set( fontOpts[ 'family' ] ) self._sizeString.set( fontOpts[ 'size' ] ) self._weight.set( fontOpts[ 'weight' ] ) self._slant.set( fontOpts[ 'slant' ] ) self._isUnderline.set( fontOpts[ 'underline' ] ) self._isOverstrike.set( fontOpts[ 'overstrike' ] ) def body( self, master ): theRow = 0 Label( master, text="Font Family" ).grid( row=theRow, column=0 ) Label( master, text="Font Size" ).grid( row=theRow, column=2 ) theRow += 1 # Font Families fontList = ttk.Combobox( master, height=10, textvariable=self._family ) fontList.grid( row=theRow, column=0, columnspan=2, sticky=N+S+E+W, padx=10 ) rawfamilyList = list(tkFont.families( )) rawfamilyList.sort() # print rawfamilyList familyList=[] for family in rawfamilyList: if family[0] == '@': continue familyList.append(family) fontList.configure( values=familyList ) fontList.bind('<<ComboboxSelected>>', self.selectionChanged) # Font Sizes sizeList = ttk.Combobox( master, height=10, width=5, textvariable=self._sizeString ) sizeList.grid( row=theRow, column=2, columnspan=2, sticky=N+S+E+W, padx=10 ) sizes=[] for size in xrange( 10,50 ): sizes.append( str(size) ) sizeList.configure( values=sizes) sizeList.bind('<<ComboboxSelected>>', self.selectionChanged) # Styles if self._showStyles is not None: theRow += 1 if self._showStyles in ( FontChooser.ALL, FontChooser.BASIC ): Label( master, text='Styles', anchor=W ).grid( row=theRow, column=0, pady=10, sticky=W ) theRow += 1 Checkbutton( master, text="bold", command=self.selectionChanged, offvalue='normal', onvalue='bold', variable=self._weight ).grid(row=theRow, column=0) Checkbutton( master, text="italic", command=self.selectionChanged, offvalue='roman', onvalue='italic', variable=self._slant ).grid(row=theRow, column=1) if self._showStyles == FontChooser.ALL: Checkbutton( master, text="underline", command=self.selectionChanged, offvalue=False, onvalue=True, variable=self._isUnderline ).grid(row=theRow, column=2) Checkbutton( master, text="overstrike", command=self.selectionChanged, offvalue=False, onvalue=True, variable=self._isOverstrike ).grid(row=theRow, column=3) # Sample Text theRow += 1 Label( master, text='Sample Text', anchor=W ).grid( row=theRow, column=0, pady=10, sticky=W ) theRow += 1 self.sampleText = Text( master, height=11, width=70 ) self.sampleText.insert( INSERT,'ABC...XYZ\nabc....xyz', 'fontStyle' ) self.sampleText.config( state=DISABLED ) self.sampleText.tag_config( 'fontStyle', font=self._currentFont ) self.sampleText.grid( row=theRow, column=0, columnspan=4, padx=10 ) def apply( self ): self.result = self.getFontTuple( ) def selectionChanged( self, something=None ): self._currentFont.configure( family=self._family.get(), size=self._sizeString.get(), weight=self._weight.get(), slant=self._slant.get(), underline=self._isUnderline.get(), overstrike=self._isOverstrike.get() ) if self.sampleText: self.sampleText.tag_config( 'fontStyle', font=self._currentFont ) def getFontString( self ): family = self._family.get() size = int(self._sizeString.get()) styleList = [ ] if self._weight.get() == tkFont.BOLD: styleList.append( 'bold' ) if self._slant.get() == tkFont.ITALIC: styleList.append( 'italic' ) if self._isUnderline.get(): styleList.append( 'underline' ) if self._isOverstrike.get(): styleList.append( 'overstrike' ) if len(styleList) == 0: return family+ ' ' + str(size) else: xx='' for x in styleList: xx=xx+' '+ x return family + ' ' +str(size) +' '+xx def getFontTuple( self ): family = self._family.get() size = int(self._sizeString.get()) styleList = [ ] if self._weight.get() == tkFont.BOLD: styleList.append( 'bold' ) if self._slant.get() == tkFont.ITALIC: styleList.append( 'italic' ) if self._isUnderline.get(): styleList.append( 'underline' ) if self._isOverstrike.get(): styleList.append( 'overstrike' ) if len(styleList) == 0: return family, size else: return family, size, ' '.join( styleList )
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.centerUI(w=570,h=240) def initUI(self): self.parent.title("DBLR for Dummies") self.pack(fill=BOTH, expand=True) #self.columnconfigure(0, weight=1) #self.rowconfigure(0, weight=1) # weight attibute is used to make them growable self.meas = IntVar() self.base_path = StringVar() self.coef = DoubleVar() self.noise = DoubleVar() self.n_sigma = DoubleVar() self.thr1 = DoubleVar() self.thr2 = DoubleVar() self.thr3 = DoubleVar() self.graph_sw = BooleanVar() #Image factor=0.65 search = Image.open("NEXT_official_logo.jpg") width_org, height_org = search.size search_temp = search.resize((int(width_org*factor), int(height_org*factor)), Image.ANTIALIAS) search_aux = ImageTk.PhotoImage(search_temp) label1 = Label(self, image=search_aux) label1.image = search_aux label1.grid(row=0, column=4, columnspan=2, rowspan=3, padx=5) self.base_path.set("F:/DATOS_DAC/2052/pmt_0_trace_evt_") e1 = Entry(self, textvariable=self.base_path, width=40) e1.grid(row=0,column=1, sticky=W, columnspan=3, pady=5, padx=5) e1_label = Label(self, text="Path & Name") e1_label.grid(row=0,column=0, columnspan=1, sticky=E, pady=5, padx=5) self.meas.set("1") sb1 = Spinbox(self, from_=1, to=100, width=4, textvariable=self.meas) sb1.grid(row=2,column=1, sticky=W, pady=5, padx=5) sb1_label = Label(self, text="File") sb1_label.grid(row=2,column=0, padx=5, sticky=E) #Check buttons cb1 = Checkbutton(self, text="New Graph", variable=self.graph_sw) cb1.select() cb1.grid(row=2,column=2, sticky=W) #PARAMETERS Integration_label = Label(self, text="PARAMETERS", font = "Verdana 12 bold") Integration_label.grid(row=3,column=1, padx=5, columnspan = 2, pady=10, sticky=E) self.coef.set("1.625E-3") e2 = Entry(self, width=12, textvariable=self.coef) e2.grid(row=4,column=1, sticky=W, pady=5, padx=5) e2_label = Label(self, text="DBLR Coef") e2_label.grid(row=4,column=0, sticky=E, pady=5, padx=5) self.noise.set("0.75") e3 = Entry(self, width=12, textvariable=self.noise) e3.grid(row=4,column=3, sticky=W, pady=5, padx=5) e3_label = Label(self, text="Noise (LSB)") e3_label.grid(row=4,column=2, sticky=E, pady=5, padx=5) self.n_sigma.set("4") e4 = Entry(self, width=12, textvariable=self.n_sigma) e4.grid(row=4,column=5, sticky=W, pady=5, padx=5) e4_label = Label(self, text="Noise Threshold") e4_label.grid(row=4,column=4, sticky=E, pady=5, padx=5) self.thr1.set("3") e5 = Entry(self, width=12, textvariable=self.thr1) e5.grid(row=5,column=1, sticky=W, pady=5, padx=5) e5_label = Label(self, text="Threshold 1") e5_label.grid(row=5,column=0, sticky=E, pady=5, padx=5) self.thr2.set("5") e6 = Entry(self, width=12, textvariable=self.thr2) e6.grid(row=5,column=3, sticky=W, pady=5, padx=5) e6_label = Label(self, text="Threshold 2") e6_label.grid(row=5,column=2, sticky=E, pady=5, padx=5) self.thr3.set("1") e7 = Entry(self, width=12, textvariable=self.thr3) e7.grid(row=5,column=5, sticky=W, pady=5, padx=5) e7_label = Label(self, text="Threshold 3") e7_label.grid(row=5,column=4, sticky=E, pady=5, padx=5) # Main buttons obtn = Button(self, text="GO!!", command=self.DBLR_f) obtn.grid(row=6, column=4, sticky=E, pady=10) cbtn = Button(self, text="Quit", command=self.quit) cbtn.grid(row=6, column=5, sticky=E, pady=10) hbtn = Button(self, text="Help", command=self.help_f) hbtn.grid(row=6, column=0, sticky=W, pady=10) def help_f(self): top = Toplevel() top.title("HELP") msg = Message(top, width= 500, text="Noise Threshold (NT) - Noise Based Main Threshold \ (Sigmas)\n Threshold 1 - Main Threshold (LSBs) \n Threshold 2 - End of Pulse Error \n \ Threshold 3 - End of Tail Error \n When Thr1 = Thr3 = 0 their values are defined as: \n \ (THR1 = NT (LSBs) / THR3 = NT*NOISE_ADC / 5)") msg.pack() button = Button(top, text="Close", command=top.destroy) button.pack() # tkMessageBox.showinfo("HELP", "Noise Threshold (NT) - Noise Based Main Threshold (Sigmas)\ #Threshold 1 - Main Threshold (LSBs)\ #Threshold 2 - End of Pulse Error\ #Threshold 3 - End of Tail Error\ #When Thr1 = Thr3 = 0 their values are defined as:\ #(THR1 = NT (LSBs) / THR3 = NT*NOISE_ADC/5)") def DBLR_f(self): global a if (self.graph_sw.get()==True): b=a a=a+1 else: b=0 aux=self.base_path.get() path=''.join([aux,str(self.meas.get()),'.txt']) g=pd.read_csv(path) f=4096-g.values recons,energia = DB.BLR( signal_daq=f.flatten().astype(float), coef=self.coef.get(), n_sigma=self.n_sigma.get(), NOISE_ADC=self.noise.get(), thr1=self.thr1.get(), thr2=self.thr2.get(), thr3=self.thr3.get(), plot=False) plt.figure(a) plt.plot(recons) plt.figtext(0.2,0.75, ('ENERGY = %0.2f ' % (energia))) plt.show(block=False) 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 ScalePanel(PluginPanel): name = 'ScaleAndMirror' title = _("Scale and Mirror") def init(self, master): PluginPanel.init(self, master) self.width_priority = 1 root = self.mw.root self.var_width = DoubleVar(root) self.var_height = DoubleVar(root) unit = '%' jump = 5 self.var_proportional = IntVar(root) self.var_proportional.set(0) self.var_basepoint = StringVar(root) self.var_basepoint.set('C') #--------------------------------------------------------- top = TFrame(self.panel, style='FlatFrame') top.pack(side=TOP, fill=BOTH) #--------------------------------------------------------- # Horisontal size size_frameH = TFrame(top, style='FlatFrame', borderwidth=3) size_frameH.pack(side=TOP, fill=BOTH) label = TLabel(size_frameH, style='FlatLabel', image='size_h') label.pack(side=LEFT, padx=5) self.entry_width = TSpinbox(size_frameH, var=100, vartype=1, textvariable=self.var_width, min=-30000, max=30000, step=jump, width=6, command=self.apply_scale) self.entry_width.pack(side=LEFT) self.entry_width.down_button.bind('<ButtonRelease>', self.entry_width_chang) self.entry_width.down_button.bind('<KeyRelease>', self.entry_width_chang) self.entry_width.up_button.bind('<ButtonRelease>', self.entry_width_chang) self.entry_width.up_button.bind('<KeyRelease>', self.entry_width_chang) self.entry_width.entry.bind('<ButtonRelease>', self.entry_width_chang) self.entry_width.entry.bind('<KeyRelease>', self.entry_width_chang) self.entry_width.entry.bind('<FocusOut>', self.entry_width_chang) self.entry_width.entry.bind('<FocusIn>', self.entry_width_FocusIn) self.labelwunit = TLabel(size_frameH, style='FlatLabel', text=unit) self.labelwunit.pack(side=LEFT, padx=5) self.hflip = BooleanVar(root) self.hflip.set(0) button = TCheckbutton(size_frameH, image="pstrip_hflip", style='ToolBarCheckButton', variable=self.hflip, command=None) button.pack(side=LEFT) #--------------------------------------------------------- # Vertical size_frameV = TFrame(top, style='FlatFrame', borderwidth=3) size_frameV.pack(side=TOP, fill=BOTH) label = TLabel(size_frameV, style='FlatLabel', image='size_v') label.pack(side=LEFT, padx=5) self.entry_height = TSpinbox(size_frameV, var=100, vartype=1, textvariable=self.var_height, min=-30000, max=30000, step=jump, width=6, command=self.apply_scale) self.entry_height.pack(side=LEFT) self.entry_height.down_button.bind('<ButtonRelease>', self.entry_height_chang) self.entry_height.down_button.bind('<KeyRelease>', self.entry_height_chang) self.entry_height.up_button.bind('<ButtonRelease>', self.entry_height_chang) self.entry_height.up_button.bind('<KeyRelease>', self.entry_height_chang) self.entry_height.entry.bind('<ButtonRelease>', self.entry_height_chang) self.entry_height.entry.bind('<KeyRelease>', self.entry_height_chang) self.entry_height.entry.bind('<FocusOut>', self.entry_height_chang) self.entry_height.entry.bind('<FocusIn>', self.entry_height_FocusIn) self.labelhunit = TLabel(size_frameV, style='FlatLabel', text=unit) self.labelhunit.pack(side=LEFT, padx=5) self.vflip = BooleanVar(root) self.vflip.set(0) button = TCheckbutton(size_frameV, image="pstrip_vflip", style='ToolBarCheckButton', variable=self.vflip, command=None) button.pack(side=LEFT) #--------------------------------------------------------- # Proportional chek self.proportional_check = TCheckbutton(top, text=_("Proportional"), variable=self.var_proportional, command=self.proportional) self.proportional_check.pack(side=TOP, anchor=W, padx=5, pady=5) #--------------------------------------------------------- # Basepoint check label = TLabel(top, style='FlatLabel', text=_("Basepoint:")) label.pack(side=TOP, fill=BOTH, padx=5) basepoint_frame = TLabelframe(top, labelwidget=label, style='Labelframe', borderwidth=4) basepoint_frame.pack(side=TOP, fill=X, padx=5, pady=2) self.Basepoint = BasePointSelector(basepoint_frame, anchor=self.var_basepoint) self.Basepoint.pack(side=LEFT, fill=BOTH, padx=5) label = TLabel(basepoint_frame, style='FlatLabel', image='coordinate_sys') label.pack(side=LEFT, fill=BOTH, padx=10) #--------------------------------------------------------- # Button frame button_frame = TFrame(top, style='FlatFrame', borderwidth=5) button_frame.pack(side=BOTTOM, fill=BOTH) self.update_buttons = [] self.button = UpdatedButton(top, text=_("Apply"), command=self.apply_scale) self.button.pack(in_=button_frame, side=BOTTOM, expand=1, fill=X, pady=3) self.button_copy = UpdatedButton(top, text=_("Apply to Copy"), command=self.apply_to_copy) self.button_copy.pack(in_=button_frame, side=BOTTOM, expand=1, fill=X) self.init_from_doc() self.subscribe_receivers() ############################################################################### def subscribe_receivers(self): self.document.Subscribe(SELECTION, self.Update) def unsubscribe_receivers(self): self.document.Unsubscribe(SELECTION, self.Update) def init_from_doc(self, *arg): self.Update() def Update(self, *arg): if self.is_selection(): self.entry_width.set_state(NORMAL) self.entry_height.set_state(NORMAL) self.proportional_check['state'] = NORMAL self.button['state'] = NORMAL self.button_copy['state'] = NORMAL else: self.entry_width.set_state(DISABLED) self.entry_height.set_state(DISABLED) self.proportional_check['state'] = DISABLED self.button['state'] = DISABLED self.button_copy['state'] = DISABLED def entry_width_FocusIn(self, *arg): self.width_priority = 1 def entry_height_FocusIn(self, *arg): self.width_priority = 0 def ScaleSelected(self, h, v, cnt_x=None, cnt_y=None): text = _("Scale") if self.document.selection: self.document.begin_transaction(text) try: try: br = self.document.selection.coord_rect hor_sel = br.right - br.left ver_sel = br.top - br.bottom if cnt_x is None: cnt_x = hor_sel / 2 + br.left if cnt_y is None: cnt_y = ver_sel / 2 + br.bottom trafo = Trafo(h, 0, 0, v, cnt_x - cnt_x * h, cnt_y - cnt_y * v) self.document.TransformSelected(trafo, text) except: self.document.abort_transaction() finally: self.document.end_transaction() def ScaleAndCopy(self, h, v, cnt_x=None, cnt_y=None): text = _("Scale&Copy") if self.document.selection: self.document.begin_transaction(text) try: try: br = self.document.selection.coord_rect hor_sel = br.right - br.left ver_sel = br.top - br.bottom if cnt_x is None: cnt_x = hor_sel / 2 + br.left if cnt_y is None: cnt_y = ver_sel / 2 + br.bottom trafo = Trafo(h, 0, 0, v, cnt_x - cnt_x * h, cnt_y - cnt_y * v) self.document.ApplyToDuplicate() self.document.TransformSelected(trafo, text) except: self.document.abort_transaction() finally: self.document.end_transaction() def entry_height_chang(self, *arg): if self.var_proportional.get(): self.var_width.set(self.var_height.get()) def entry_width_chang(self, *arg): if self.var_proportional.get(): self.var_height.set(self.var_width.get()) def proportional(self): if self.width_priority: self.entry_width_chang() else: self.entry_height_chang() def apply_scale(self, *arg): if self.button["state"] == DISABLED: return self.proportional() width = self.var_width.get() height = self.var_height.get() br = self.document.selection.coord_rect hor_sel = br.right - br.left ver_sel = br.top - br.bottom cnt_x, cnt_y = self.Basepoint.get_basepoint(hor_sel, ver_sel, br.left, br.bottom) h = width / 100 if h == 0: h = 1 if self.hflip.get(): h = -1 * h v = height / 100 if v == 0: v = 1 if self.vflip.get(): v = -1 * v if arg and arg[0] == 'Duplicate': self.ScaleAndCopy(h, v, cnt_x, cnt_y) else: self.ScaleSelected(h, v, cnt_x, cnt_y) def apply_to_copy(self): self.apply_scale('Duplicate') def is_selection(self): return (len(self.document.selection) > 0)
class MainUI(Frame): """ Main UI window for draft """ def __init__(self, parent, draftgame): self.current_opponent_id = 0 self.user_pick_made = BooleanVar() self.user_pick_made.set(False) self.game = draftgame self.parent = parent Frame.__init__(self, parent) self.grid() self.__MainUI() self.draft_logic() def draft_logic(self): if self.game.draft_style == "Linear": self.linear_draft() elif self.game.draft_style == "Snake": self.snake_draft() FinalUI(self.parent, self.game) def linear_draft(self): while self.game.current_round <= self.game.number_of_rounds: if self.game.draft_position != self.game.current_position: self.opponent_pick_logic(self.current_opponent_id) self.current_opponent_id += 1 self.increment_position() else: self.user_pick_logic() self.increment_position() def snake_draft(self): while self.game.current_round <= self.game.number_of_rounds: if self.game.current_round % 2 != 0: if self.game.draft_position != self.game.current_position: self.opponent_pick_logic(self.current_opponent_id) self.current_opponent_id += 1 self.increment_position() else: self.user_pick_logic() self.increment_position() else: if self.game.draft_position != \ self.game.number_of_opponents \ - self.game.current_position + 2: self.opponent_pick_logic( self.game.number_of_opponents - self.current_opponent_id - 1 ) self.current_opponent_id += 1 self.increment_position() else: self.user_pick_logic() self.increment_position() def increment_position(self): self.game.current_position += 1 if self.game.current_position > self.game.number_of_opponents + 1: self.game.current_round += 1 self.game.current_position = 1 self.current_opponent_id = 0 self.__MainUI() def user_pick_logic(self): self.user_pick_made.set(False) while not self.user_pick_made.get(): self.wait_variable(name=self.user_pick_made) def opponent_pick_logic(self, opponent_id): pick_made = False pick = tkSimpleDialog.askstring( "Opponent's pick", "Who did your opponent pick?\nCurrent Pick: Round {0}: Pick {1}" .format(self.game.current_round, self.game.current_position)) while not pick_made: try: if utils.get_player_position(pick, self.game.cursor) is not None: position = utils.get_player_position(pick, self.game.cursor).rstrip('0123456789 ').upper() if utils.get_player_from_table(pick, position, self.game.cursor) is not None: utils.remove_player_from_possible_players(pick, self.game.connection, self.game.cursor) opponent = [opponent for opponent in self.game.opponents if opponent_id == opponent.id][0] opponent.team.append(pick) pick_made = True else: pick = tkSimpleDialog.askstring( "Opponent's pick", "NOT A VALID PICK: please select again\nCurrent Pick: Round {0}: Pick {1}" .format(self.game.current_round, self.game.current_position)) else: pick = tkSimpleDialog.askstring( "Opponent's pick", "NOT A VALID PICK: please select again\nCurrent Pick: Round {0}: Pick {1}" .format(self.game.current_round, self.game.current_position)) except AttributeError: tkMessageBox.showinfo("Error", "Opponent must pick a valid player") pick = tkSimpleDialog.askstring( "Opponent's pick", "NOT A VALID PICK: please select again\nCurrent Pick: Round {0}: Pick {1}" .format(self.game.current_round, self.game.current_position)) def __MainUI(self): self.parent.title("Fantasy Football Helper") for widget in self.parent.winfo_children(): widget.destroy() self.__draw_round_label(self.parent) self.__draw_recommended_list(self.parent) self.__draw_valuable_list(self.parent) self.__draw_current_team(self.parent) self.__draw_team_requirements(self.parent) self.__draw_current_choice(self.parent) self.__draw_opponent_teams(self.parent) def __draw_round_label(self, parent): Label(parent, text="Round{0}: Pick{1}".format(self.game.current_round, self.game.current_position)).grid(row=0) def __draw_current_choice(self, parent): choice = IntVar() other_player = StringVar() recommended = self.game.most_recommended_player_remaining() valuable = self.game.get_best_player_remaining() recommended_button = Radiobutton(parent, text=recommended, variable=choice, value=1) valuable_button = Radiobutton(parent, text=valuable, variable=choice, value=2) other_button = Radiobutton(parent, text="", variable=choice, takefocus=0, value=3) other_text = Entry(parent, textvariable=other_player) def text_focus(event): other_button.select() other_text.bind("<Button-1>", text_focus) def pick_player(): decision = choice.get() if decision == 1: player = self.game.most_recommended_player_remaining() self.game.add_player_to_team(player) utils.remove_player_from_possible_players( player, self.game.connection, self.game.cursor) self.user_pick_made.set(True) elif decision == 2: player = self.game.get_best_player_remaining() self.game.add_player_to_team(player) utils.remove_player_from_possible_players( player, self.game.connection, self.game.cursor) self.user_pick_made.set(True) elif decision == 3: player = other_player.get() try: self.game.add_player_to_team(player) utils.remove_player_from_possible_players( player, self.game.connection, self.game.cursor) self.user_pick_made.set(True) except: tkMessageBox.showinfo("Error", "Can't add that player to team, try again.") self.user_pick_logic() else: tkMessageBox.showinfo("No Selection", "Please make a selection") self.user_pick_logic() def pick_player_button(event): pick_player() Label(parent, text="Recommended Player").grid(sticky="w", row=1) recommended_button.grid(sticky="w", row=1, column=1, columnspan=2) Label(parent, text="Most Valuable Player").grid(sticky="w", row=2) valuable_button.grid(sticky="w", row=2, column=1, columnspan=2) Label(parent, text="Choose other Player").grid(sticky="w", row=3) other_button.grid(sticky="w", row=3, column=1) other_text.grid(row=3, column=2, sticky="w", padx=5) pick_button = Button(parent, text="Pick", command=pick_player).grid( row=4, columnspan=3, sticky="ne", padx=5) self.parent.bind("<Return>", pick_player_button) def __draw_recommended_list(self, parent): recommended_list = self.game.get_list_recommended_players("10") recommended_listbox = Text(parent, height=10, width=35) Label(parent, text="List of Recommended Players").grid(row=1, column=3) recommended_listbox.grid(row=2, column=3, rowspan=4, sticky="n") for player in recommended_list: index = str(recommended_list.index(player) + 1) recommended_listbox.insert("end", "{0:>2}:{1:<20} {2} {3}\n".format(index, player[0], player[2], format(player[1], '.0f')) ) recommended_listbox.config(state="disabled") def __draw_valuable_list(self, parent): valuable_list = self.game.get_list_of_best_players("10") valuable_listbox = Text(parent, height=10, width=35) Label(parent, text="List of Most Valuable Players").grid(row=1, column=4) valuable_listbox.grid(row=2, column=4, rowspan=4, sticky="n", padx=10) for player in valuable_list: index = str(valuable_list.index(player) + 1) valuable_listbox.insert("end", "{0:>2}:{1:<20} {2} {3}\n".format(index, player[0], player[2], format(player[1], '.0f')) ) valuable_listbox.config(state="disabled") def __draw_team_requirements(self, parent): requirements = self.game.check_current_team_needs() requirement_list = [] for key in requirements.keys(): # key_string = "%d%s" % (requirements[key], key) requirement_list.append("{0}{1}".format(requirements[key], key)) Label(parent, text="Still Need: " + ", ".join(requirement_list)).grid( row=5, columnspan=3, sticky="w") def __draw_current_team(self, parent): current_team = self.game.current_team team_list = [] for key in current_team.keys(): # player_string = "%s %s" % (key, current_team[key]) team_list.append("{0}: {1}".format(key, current_team[key])) current_team_string = (", ".join(team_list[0:len(team_list) / 2 + 1]) + "\n" + ", ".join(team_list[len(team_list) / 2 + 1:])) Label(parent, text="Current Team: ").grid( row=6) Label(parent, text=current_team_string).grid( row=6, column=1, columnspan=4, pady=10) def __draw_opponent_teams(self, parent): opponents = self.game.opponents for opponent in opponents: Label(parent, text="Opponent{0}'s Team: ".format(opponent.id + 1)).grid( row=7 + opponent.id) Label(parent, text=str(opponent.team)).grid( row=7 + opponent.id, column=1, columnspan=4)
class vco_model_win(Toplevel): def __init__(self, parent): Toplevel.__init__(self) img = ImageTk.PhotoImage(file=os.path.join(os.path.dirname(__file__), 'Icons/LMS8001_PLLSim.png')) self.tk.call('wm', 'iconphoto', self._w, img) self.resizable(0, 0) self.parent = parent self.pll = self.parent.pll self.initUI() center_Window(self) self.protocol("WM_DELETE_WINDOW", self.on_Quit) def initUI(self): self.title("LMS8001-PLL-VCO Model Definition") self.style = Style() self.style.theme_use("default") self.columnconfigure(0, pad=1) self.columnconfigure(1, pad=1) self.columnconfigure(2, pad=1) #self.columnconfigure(3, pad=1, weight=1) self.rowconfigure(0, pad=10) self.rowconfigure(1, pad=1, weight=1) self.rowconfigure(2, pad=1, weight=1) self.rowconfigure(3, pad=15, weight=1) self.rowconfigure(4, pad=1, weight=1) self.VCO_EM = BooleanVar() self.VCO_EM.set(self.parent.VCO_EM.get()) self.cbox_vco_em = Checkbutton(self, text='Use EM (RLCK) VCO Model', onvalue=1, offvalue=0, variable=self.VCO_EM, command=self.on_VCO_EM) self.cbox_vco_em.grid(row=0, column=0, columnspan=3, sticky=W) self.radio_fvco = IntVar() self.radio_fvco.set(int(self.parent.VCO_MEAS_FREQ.get())) self.radio_fvco_meas = Radiobutton( self, text='Use Measured VCO Frequency Values in Analysis', variable=self.radio_fvco, value=1) self.radio_fvco_meas.grid(row=1, column=0, columnspan=2, padx=15, sticky=W + N) self.radio_fvco_sim = Radiobutton( self, text='Use Simulated VCO Frequency Values in Analysis', variable=self.radio_fvco, value=0) self.radio_fvco_sim.grid(row=2, column=0, columnspan=2, padx=15, sticky=W + N) buttonFreq = Button(self, text='Plot Freq', command=self.on_FREQ, width=10) buttonFreq.grid(row=3, column=0, sticky=W + E) buttonKVCO = Button(self, text='Plot KVCO', command=self.on_KVCO, width=10) buttonKVCO.grid(row=3, column=1, sticky=W + E) buttonFSTEP = Button(self, text='Plot FSTEP', command=self.on_FSTEP, width=17) buttonFSTEP.grid(row=3, column=2, sticky=W + E) buttonOK = Button(self, text='OK', command=self.on_OK, width=10) buttonOK.grid(row=4, column=0, sticky=W + E) buttonQuit = Button(self, text='Quit', command=self.on_Quit, width=17) buttonQuit.grid(row=4, column=2, sticky=W + E) buttonApply = Button(self, text='Apply', command=self.on_Apply, width=10) buttonApply.grid(row=4, column=1, sticky=W + E) self.on_VCO_EM() #self.pack(fill=BOTH, expand=True) def get_vals(self): if (self.VCO_EM.get()): EM_MODEL = True if (self.radio_fvco.get()): MEAS_FREQ = True else: MEAS_FREQ = False else: EM_MODEL = False MEAS_FREQ = False return (EM_MODEL, MEAS_FREQ) def on_FREQ(self): (EM_MODEL, MEAS_FREQ) = self.get_vals() vco = lms8001_vco(EM_MODEL=EM_MODEL, MEAS_FREQ=MEAS_FREQ) fvco = np.array(np.empty([3, 256])) for sel in range(1, 4): for freq in range(0, 256): fvco[sel - 1, freq] = vco.calcF(sel, freq, 0.6) figure(15) plt1, = plotsig(range(0, 256), fvco[0, :] / 1.0e9, 15, xlabel='$Cap. Bank Code$', ylabel='$F_{VCO} [GHz]$', title='VCO Frequency vs. Cap Bank Code', line_color='black', font_name=self.parent.font_name) plt2, = plotsig(range(0, 256), fvco[1, :] / 1.0e9, 15, xlabel='$Cap. Bank Code$', ylabel='$F_{VCO} [GHz]$', title='VCO Frequency vs. Cap Bank Code', line_color='blue', font_name=self.parent.font_name) plt3, = plotsig(range(0, 256), fvco[2, :] / 1.0e9, 15, xlabel='$Cap. Bank Code$', ylabel='$F_{VCO} [GHz]$', title='VCO Frequency vs. Cap Bank Code', line_color='red', font_name=self.parent.font_name) setlegend(15, [plt1, plt2, plt3], ['VCO_SEL=1', 'VCO_SEL=2', 'VCO_SEL=3'], font_name=self.parent.font_name) show_plots() def on_KVCO(self): (EM_MODEL, MEAS_FREQ) = self.get_vals() vco = lms8001_vco(EM_MODEL=EM_MODEL, MEAS_FREQ=MEAS_FREQ) fvco = np.array(np.empty([3, 256])) NDIV = np.array(np.empty([3, 256])) kvco = np.array(np.empty([3, 256])) for sel in range(1, 4): for freq in range(0, 256): fvco[sel - 1, freq] = vco.calcF(sel, freq, 0.6) kvco[sel - 1, freq] = vco.calcKVCO(sel, freq, 0.6) NDIV[sel - 1, freq] = 1.0 * fvco[sel - 1, freq] / self.pll.Fref for sel in range(1, 4): kvco_avg = 1.0 kvco_over_NDIV_avg = 1.0 for freq in range(0, 256): kvco_avg = kvco_avg * (kvco[sel - 1, freq] / 1.0e6)**(1.0 / 256) kvco_over_NDIV_avg = kvco_over_NDIV_avg * ( (kvco[sel - 1, freq] / 1.0e6) / NDIV[sel - 1, freq])**(1.0 / 256.0) print 'VCO_SEL=%d, KVCO_AVG=%.3f MHz/V, KVCO_over_NDIV_AVG=%.3f MHz/V' % ( sel, kvco_avg, kvco_over_NDIV_avg) print '' figure(16) plt1, = plotsig(fvco[0, :] / 1.0e9, kvco[0, :] / 1.0e6, 16, xlabel='$F_{VCO} [GHz]$', ylabel='$K_{VCO} [MHz/V]$', title='VCO Sensitivity vs. Frequency', line_color='black', font_name=self.parent.font_name) plt2, = plotsig(fvco[1, :] / 1.0e9, kvco[1, :] / 1.0e6, 16, xlabel='$F_{VCO} [GHz]$', ylabel='$K_{VCO} [MHz/V]$', title='VCO Sensitivity vs. Frequency', line_color='blue', font_name=self.parent.font_name) plt3, = plotsig(fvco[2, :] / 1.0e9, kvco[2, :] / 1.0e6, 16, xlabel='$F_{VCO} [GHz]$', ylabel='$K_{VCO} [MHz/V]$', title='VCO Sensitivity vs. Frequency', line_color='red', font_name=self.parent.font_name) setlegend(16, [plt1, plt2, plt3], ['VCO_SEL=1', 'VCO_SEL=2', 'VCO_SEL=3'], font_name=self.parent.font_name) show_plots() def on_FSTEP(self): (EM_MODEL, MEAS_FREQ) = self.get_vals() vco = lms8001_vco(EM_MODEL=EM_MODEL, MEAS_FREQ=MEAS_FREQ) fstep = np.array(np.empty([3, 255])) for sel in range(1, 4): for freq in range(0, 255): fstep[sel - 1, freq] = vco.calcF(sel, freq + 1, 0.6) - vco.calcF( sel, freq, 0.6) figure(17) plt1, = plotsig( range(0, 255), fstep[0, :] / 1.0e6, 17, xlabel='$Cap. Bank Code$', ylabel='$F_{STEP} [MHz/V]$', title='VCO Frequency Step Between Adjacent Tuning Bands', line_color='black', font_name=self.parent.font_name) plt2, = plotsig( range(0, 255), fstep[1, :] / 1.0e6, 17, xlabel='$Cap. Bank Code$', ylabel='$F_{STEP} [MHz/V]$', title='VCO Frequency Step Between Adjacent Tuning Bands', line_color='blue', font_name=self.parent.font_name) plt3, = plotsig( range(0, 255), fstep[2, :] / 1.0e6, 17, xlabel='$Cap. Bank Code$', ylabel='$F_{STEP} [MHz/V]$', title='VCO Frequency Step Between Adjacent Tuning Bands', line_color='red', font_name=self.parent.font_name) setlegend(17, [plt1, plt2, plt3], ['VCO_SEL=1', 'VCO_SEL=2', 'VCO_SEL=3'], font_name=self.parent.font_name) show_plots() def on_VCO_EM(self): if (self.VCO_EM.get()): self.radio_fvco_meas.config(state='enabled') self.radio_fvco_sim.config(state='enabled') else: self.radio_fvco_meas.config(state='disabled') self.radio_fvco_sim.config(state='disabled') def on_OK(self): self.on_Apply() self.on_Quit() def on_Quit(self): self.parent.vco_model_win = None self.destroy() def on_Apply(self): (EM_MODEL, MEAS_FREQ) = self.get_vals() self.parent.VCO_EM.set(EM_MODEL) self.parent.VCO_MEAS_FREQ.set(MEAS_FREQ) self.pll.vco = lms8001_vco(SEL=2, FREQ=128, EM_MODEL=EM_MODEL, MEAS_FREQ=MEAS_FREQ)
def test_get(self): v = BooleanVar(self.root, True, "name") self.assertAlmostEqual(True, v.get()) self.root.globalsetvar("name", "0") self.assertAlmostEqual(False, v.get())
class CreateMask(Frame): def __init__(self, parent, filename=None, dirname=None, mask4d=False, obj_return_value=None): Frame.__init__(self, parent) self.parent = parent self.obj_return_value = obj_return_value if dirname is None: self.dirname = '' else: self.dirname = dirname if filename is None or not os.path.isfile(filename): if dirname is not None: filename = tkFileDialog.askopenfilename(initialdir=dirname) else: filename = tkFileDialog.askopenfilename() if not os.path.isfile(filename): parent.destroy() return self.readImage(filename) _, _, filename_mask = create_mask.set_filenames(filename) self.filename_mask = filename_mask + '.nii.gz' if mask4d: if len(self.shape) > 3: self.mask_base = np.zeros(self.shape, dtype=np.int8) self.mask = self.mask_base[:, :, :, 0] self.mask4d = True else: self.mask = np.zeros(self.shape[:3], dtype=np.int8) self.mask4d = False self.volume = 0 self.initUI() self.modifyUI() self.drawSlice() def initUI(self): self.frame_bottom = Frame(self) self.frame_main = Frame(self) def modifyUI(self): frame_bottom = self.frame_bottom frame_main = self.frame_main self.sliceView = [ ImshowMplCanvas(frame_main) for k in range(self.shape[2]) ] self.sliceSpin = [ MySpinBox(frame_main, k) for k in range(self.shape[2]) ] #Layout self.parent.title('CreateMask') max_spin = 0 if self.mask4d: max_spin = self.shape[3] - 1 self.spin_volume = Spinbox(frame_bottom, from_=0, to=max_spin, increment=1, command=self.change_volume, width=8) self.reset_box(self.spin_volume, 0) buttonMask = Button(frame_bottom, text='B0 from Bval...', command=self.createBaseImage) buttonMaskCreate = Button(frame_bottom, text='Create', command=self.createMaskAll) buttonSave = Button(frame_bottom, text='Save', command=self.saveMask) self.drawmask = BooleanVar() buttonDrawMask = Checkbutton(frame_bottom, text='Draw Mask', variable=self.drawmask, command=self.drawSlice) num_col = 3 num_row = 6 for col in range(self.shape[2] / num_row): for k in range(num_row): ind = col * num_row + k if ind >= self.shape[2]: break self.sliceView[ind].get_tk_widget().grid(row=k, column=col * num_col, sticky=NSEW) self.sliceSpin[ind].grid(row=k, column=col * num_col + 1) self.frame_main.grid_columnconfigure(col * num_col, weight=1) for k in range(num_row): self.frame_main.grid_rowconfigure(k, weight=1) self.spin_volume.grid(row=0, column=0) buttonMask.grid(row=0, column=1) buttonMaskCreate.grid(row=0, column=2) buttonSave.grid(row=0, column=3) buttonDrawMask.grid(row=0, column=5) frame_bottom.pack(side=BOTTOM) frame_main.pack(fill=BOTH, expand=TRUE) self.pack(fill=BOTH, expand=True) def change_volume(self): if not self.mask4d: return self.volume = int(self.spin_volume.get()) self.data = self.data_base[:, :, :, self.volume] self.mask = self.mask_base[:, :, :, self.volume] self.drawSlice() def saveMask(self): print 'save mask to %s' % self.filename_mask if self.mask4d: img_out = nib.Nifti1Image(self.mask_base, self.img.get_affine(), self.img.get_header()) else: img_out = nib.Nifti1Image(self.mask, self.img.get_affine(), self.img.get_header()) nib.save(img_out, os.path.join(self.dirname, self.filename_mask)) if self.obj_return_value is not None: self.obj_return_value.delete(0, len(self.obj_return_value.get())) self.obj_return_value.insert(0, os.path.basename(self.filename_mask)) def readImage(self, filename): self.filename = filename self.img = nib.load(filename) self.shape = self.img.shape self.data_base = self.img.get_data() if len(self.data_base.shape) > 3: for f in range(self.data_base.shape[3]): for z in range(self.data_base.shape[2]): self.data_base[:, :, z, f] = ndimage.gaussian_filter( self.data_base[:, :, z, f], sigma=0.5) self.data = self.data_base[:, :, :, 0] else: for z in range(self.data_base.shape[2]): self.data_base[:, :, z] = ndimage.gaussian_filter( self.data_base[:, :, z], sigma=0.5) self.data = self.data_base def createBaseImage(self): bvalFilename = tkFileDialog.askopenfilename() if bvalFilename: b0frames = parameter.get_b0_from_bval(bvalFilename) print self.filename, b0frames filename, filename_fltd, filename_mask = create_mask.set_filenames( self.filename) create_mask.make_base_image(filename, filename_fltd + '.nii.gz', b0frames) self.filename_mask = filename_mask + '.nii.gz' self.readImage(filename_fltd + '.nii.gz') self.drawSlice() def setSpinBoxConnect(self): for k in range(self.shape[2]): #self.sliceSpin[k].valueChanged.connect(lambda: self.createMaskSlice(k)) #self.sliceSpin[k].configure(command=lambda:self.createMaskSlice(k, self.sliceSpin[k])) self.sliceSpin[k].configure(command=functools.partial( self.createMaskSlice, k, self.sliceSpin[k])) def drawSlice(self): for k in range(self.shape[2]): self.sliceView[k].drawData(self.data[:, :, k], self.mask[:, :, k], self.drawmask.get()) def reset_box(self, box, text): box.delete(0, len(box.get())) box.insert(0, text) def createMaskSlice(self, k, value=None): self.mask[:, :, k] = 0 if value is None: value_i = int(self.sliceSpin[k].get()) else: value_i = int(value.get()) #create_mask.mask_from_threshold(self.com_x[k], self.com_y[k], self.sliceSpin[k].value(), self.data, self.mask, k) create_mask.mask_from_threshold(self.com_x[k], self.com_y[k], value_i, self.data, self.mask, k) self.sliceView[k].drawData(self.data[:, :, k], self.mask[:, :, k], self.drawmask.get()) def createMaskAll(self): self.drawmask.set(True) hdr = self.img.get_header() zooms = hdr.get_zooms() shape = self.shape self.com_x, self.com_y, roi_x, roi_y = create_mask.calculate_com( self.data, zooms) for k in range(shape[2]): dat_subflt = self.data[roi_x[k][0]:roi_x[k][1], roi_y[k][0]:roi_y[k][1], k].flatten() #threshold = np.mean(dat_subflt) threshold = np.mean(dat_subflt) + np.std(dat_subflt) self.reset_box(self.sliceSpin[k], int(threshold)) self.createMaskSlice(k) #create_mask.mask_from_threshold(self.com_x[k], self.com_y[k], threshold, self.data, self.mask, k) #self.drawSlice() self.setSpinBoxConnect()
class Cap(Frame): def __init__(self): ' set defaults, create widgets, bind callbacks, start live view ' self.root = Tk() # menu: self.menu = Menu(self.root) self.root.config(menu=self.menu) # bind global keypresses: self.root.bind('q', lambda e: self.root.quit()) self.root.bind('x', lambda e: self.root.quit()) self.root.bind('<Destroy>', self.do_stop_video) self.root.bind('<space>', self.do_single_shot) self.root.bind('<Return>', self.do_single_shot) self.root.bind('<Button-3>', self.do_single_shot) self.root.bind('<Left>', lambda e: self.degree.set(-90)) self.root.bind('<Right>', lambda e: self.degree.set(90)) self.root.bind('<Up>', lambda e: self.degree.set(0)) self.root.bind('a', lambda e: self.autocontrast.set(not self.autocontrast.get())) self.root.bind('e', lambda e: self.equalize.set(not self.equalize.get())) self.root.bind('g', lambda e: self.grayscale.set(not self.grayscale.get())) self.root.bind('i', lambda e: self.invert.set(not self.invert.get())) self.root.bind('s', lambda e: self.solarize.set(not self.solarize.get())) # config: self.config = RawConfigParser() self.config.read('filmroller.conf') if not self.config.has_section('global'): self.config.add_section('global') self.video = None self.invert = BooleanVar(name='invert') self.invert.set(self.config_get('invert', True)) self.invert.trace('w', self.do_configure) self.grayscale = BooleanVar(name='grayscale') self.grayscale.set(self.config_get('grayscale', False)) self.grayscale.trace('w', self.do_configure) self.autocontrast = BooleanVar(name='autocontrast') self.autocontrast.set(self.config_get('autocontrast', True)) self.autocontrast.trace('w', self.do_configure) self.equalize = BooleanVar(name='equalize') self.equalize.set(self.config_get('equalize', False)) self.equalize.trace('w', self.do_configure) self.solarize = BooleanVar(name='solarize') self.solarize.set(self.config_get('solarize', False)) self.solarize.trace('w', self.do_configure) self.degree = IntVar(name='degree') self.degree.set(0) self.filename = StringVar(name='filename') self.videodevice = StringVar(name='videodevice') dev_names = sorted(['/dev/{}'.format(x) for x in listdir('/dev') if x.startswith('video')]) d = self.config_get('videodevice', dev_names[-1]) if not d in dev_names: d = dev_names[-1] self.videodevice.set(d) self.videodevice.trace('w', self.do_configure) # self.path = 'filmroller' if not exists(self.path): makedirs(self.path) # create gui: Frame.__init__(self, self.root) self.grid() self.x_canvas = Canvas(self, width=640, height=640, ) self.x_canvas.pack(side='top') self.x_canvas.bind('<Button-1>', self.do_change_rotation) Checkbutton(self, text='Invert', variable=self.invert).pack(side='left') Checkbutton(self, text='Gray', variable=self.grayscale).pack(side='left') Checkbutton(self, text='Auto', variable=self.autocontrast).pack(side='left') OptionMenu(self, self.videodevice, *dev_names, command=self.restart_video).pack(side='left') Button(self, text='First role', command=self.do_first_role).pack(side='left') Label(self, textvariable=self.filename).pack(side='left') Button(self, text='Next role', command=self.do_inc_role).pack(side='left') Button(self, text='Take!', command=self.do_single_shot).pack(side='right') #filemenu = Menu(self.menu) #self.menu.add_cascade(label=self.videodevice.get(), menu=filemenu, ) #for n in dev_names: # filemenu.add_command(label=n, ) #filemenu.add_separator() # start operation: self.do_first_role() self.do_start_video() def do_change_rotation(self, event): ' determine where the image was clicked and turn that to the top ' if event.x < 200: self.degree.set(-90) elif event.x > 640 - 200: self.degree.set(90) else: self.degree.set(0) def config_get(self, name, default): ' read a configuration entry, fallback to default if not already stored ' if not self.config.has_option('global', name): return default if isinstance(default, bool): return self.config.getboolean('global', name) else: return self.config.get('global', name) def do_configure(self, name, mode, cbname): ' change a configuration entry ' if cbname == 'w': value = getattr(self, name).get() self.config.set('global', name, str(value)) self.config.write(open('filmroller.conf', 'w')) def do_first_role(self, *args): ' jump back to first role ' self.role = 'aa' self.serial = 0 self.inc_picture() def inc_picture(self): ' increment the picture number, jump over existing files ' self.filename.set('{}/scanned.{}-{:04}.jpg'.format(self.path, self.role, self.serial, )) while exists(self.filename.get()): self.serial += 1 self.filename.set('{}/scanned.{}-{:04}.jpg'.format(self.path, self.role, self.serial, )) self.root.title('filmroller - ' + self.filename.get()) def do_inc_role(self, *args): ' increment to next role ' self.serial = 0 self.role = ascii_increment(self.role) self.inc_picture() def set_pauseimage(self): ' show pause image (during shot) ' self.image = fromfile('filmroller.pause.png') self.image.thumbnail((self.previewsize['size_x'], self.previewsize['size_y'], ), ) self.photo = PhotoImage(self.image) self.x_canvas.create_image(640/2, 640/2, image=self.photo) def do_stop_video(self, *args): ' stop video and release device ' if self.video is not None: self.video.stop() self.video.close() self.video = None def restart_video(self, *args): ' restart video (if device changes or hangs) ' self.do_stop_video() self.root.after(1, self.do_start_video) def do_start_video(self, *args): ' init video and start live view ' if self.video is None: self.video = Video_device(self.videodevice.get()) _, _, self.fourcc = self.video.get_format() caps = sorted(self.video.get_framesizes(self.fourcc), cmp=lambda a, b: cmp(a['size_x']*a['size_y'], b['size_x']*b['size_y'])) self.previewsize, self.highressize = caps[0], caps[-1] self.previewsize['size_x'], self.previewsize['size_y'] = self.video.set_format( self.previewsize['size_x'], self.previewsize['size_y'], 0, 'MJPEG') try: self.video.set_auto_white_balance(True) except: pass try: self.video.set_exposure_auto(True) except: pass try: self.video.set_focus_auto(True) except: pass self.video.create_buffers(30) self.video.queue_all_buffers() self.video.start() self.root.after(1, self.do_live_view) #self.x_canvas.config(width=640, height=480) #self.x_canvas.pack(side='top') self.degree.set(0) def do_live_view(self, *args): ' show single pic live view and ask tk to call us again later ' if self.video is not None: select((self.video, ), (), ()) data = self.video.read_and_queue() self.image = frombytes('RGB', (self.previewsize['size_x'], self.previewsize['size_y']), data) if self.invert.get(): self.image = invert(self.image) if self.grayscale.get(): self.image = grayscale(self.image) if self.autocontrast.get(): self.image = autocontrast(self.image) if self.equalize.get(): self.image = equalize(self.image) if self.solarize.get(): self.image = solarize(self.image) if self.degree.get(): self.image = self.image.rotate(self.degree.get()) self.photo = PhotoImage(self.image) self.x_canvas.create_image(640/2, 640/2, image=self.photo) self.root.after(3, self.do_live_view) def do_single_shot(self, *args): ' do a high res single shot and store it ' def _go(): self.video = Video_device(self.videodevice.get()) try: self.highressize['size_x'], self.highressize['size_y'] = self.video.set_format( self.highressize['size_x'], self.highressize['size_y'], 0, 'MJPEG') try: self.video.set_auto_white_balance(True) except: pass try: self.video.set_exposure_auto(True) except: pass try: self.video.set_focus_auto(True) except: pass self.video.create_buffers(7) self.video.queue_all_buffers() self.video.start() stop_time = time() + 3.0 # wait for auto while stop_time >= time(): select((self.video, ), (), ()) self.update_idletasks() data = self.video.read_and_queue() image = frombytes('RGB', (self.highressize['size_x'], self.highressize['size_y'], ), data) if self.invert.get(): image = invert(image) if self.grayscale.get(): image = grayscale(image) if self.autocontrast.get(): image = autocontrast(image) if self.equalize.get(): self.image = equalize(self.image) if self.solarize.get(): self.image = solarize(self.image) if self.degree.get(): image = image.rotate(self.degree.get()) image.save(self.filename.get()) self.inc_picture() self.root.bell() self.video.stop() finally: self.video.close() self.video = None self.root.after(1, self.do_start_video) self.do_stop_video() self.set_pauseimage() self.update_idletasks() self.root.after(1, _go)
class MyQuestion(object): def __init__(self, parent, question_text, ans1_text, ans2_text, ans3_text, ans4_text, exp1_text, exp2_text, exp3_text, exp4_text, correct_ans): # assigning parameters to attributes self.parent = parent self.qtext = str(question_text) self.text1 = str(ans1_text) self.text2 = str(ans2_text) self.text3 = str(ans3_text) self.text4 = str(ans4_text) self.exp1 = str(exp1_text) self.exp2 = str(exp2_text) self.exp3 = str(exp3_text) self.exp4 = str(exp4_text) self.ans = int(correct_ans) # creating Tkinter variables self.ans_input = IntVar() self.is_correct = BooleanVar() self.efbg = StringVar() self.is_correct_text = StringVar() self.exp_text = StringVar() # developer mode if dev: self.ans_input.set(self.ans) # questionwide bgcolor, fgcolor self.bgcolor = GrayScale(80) self.fgcolor = GrayScale(20) # creating parent frame self.parent_frame() self.question_frame() def parent_frame(self): # creating parent frame self.pf = Frame(self.parent) self.pf.configure(bg=self.bgcolor) self.pf.place(relx=0, rely=0, relwidth=1, relheight=1) def question_frame(self): # creating question frame within parent frame self.qf = Frame(self.pf) self.qf.configure(bg=self.bgcolor) self.qf.place(relx=0, rely=0, relwidth=1, relheight=1) # creating objects within question frame self.title_label() self.radiobutton1() self.radiobutton2() self.radiobutton3() self.radiobutton4() self.check_ans_button() def explanation_frame(self): # creating explanation frame within parent frame self.ef = Frame(self.pf) self.ef.configure(bg=self.efbg.get()) self.ef.place(relx=0, rely=0, relwidth=1, relheight=1) # creating objects within explanation frame self.is_correct_label() self.exp_label() self.next_ques_button() # creating display answer button if answer is wrong if not self.is_correct.get(): self.disp_ans_button() def title_label(self): # creating title label for question frame self.tl = Label(self.qf) self.tl.configure(text=self.qtext) self.tl.configure(font=MyFonts['ExtraLarge']) self.tl.configure(bg=self.bgcolor, fg=self.fgcolor) self.tl.configure(relief=FLAT) self.tl.configure(padx=2, pady=2, anchor=N) self.tl.place(relx=0.05, rely=0.05, relwidth=0.90, relheight=0.10) def radiobutton1(self): # creating radiobuttion1 for question frame self.q1 = Radiobutton(self.qf) self.q1.configure(text='A. ' + self.text1) self.q1.configure(font=MyFonts['Large']) self.q1.configure(bg=self.bgcolor, activebackground=self.bgcolor) self.q1.configure(variable=self.ans_input, value=1) self.q1.place(relx=0.10, rely=0.20) def radiobutton2(self): # creating radiobutton2 for question frame self.q2 = Radiobutton(self.qf) self.q2.configure(text='B. ' + self.text2) self.q2.configure(font=MyFonts['Large']) self.q2.configure(bg=self.bgcolor, activebackground=self.bgcolor) self.q2.configure(variable=self.ans_input, value=2) self.q2.place(relx=0.10, rely=0.35) def radiobutton3(self): # creating radiobutton3 for question frame self.q3 = Radiobutton(self.qf) self.q3.configure(text='C. ' + self.text3) self.q3.configure(font=MyFonts['Large']) self.q3.configure(bg=self.bgcolor, activebackground=self.bgcolor) self.q3.configure(variable=self.ans_input, value=3) self.q3.place(relx=0.10, rely=0.50) def radiobutton4(self): # creating radiobutton4 for question frame self.q4 = Radiobutton(self.qf) self.q4.configure(text='D. ' + self.text4) self.q4.configure(font=MyFonts['Large']) self.q4.configure(bg=self.bgcolor, activebackground=self.bgcolor) self.q4.configure(variable=self.ans_input, value=4) self.q4.place(relx=0.10, rely=0.65) def check_ans_button(self): # creating check answer button for question frame self.cb = MyButton(self.qf, 'Check Answer', self.check_ans, 0.80, 0.85) def is_correct_label(self): # creating is_correct_label for explanation frame self.cl = Label(self.ef) self.cl.configure(text=self.is_correct_text.get()) self.cl.configure(font=MyFonts['ExtraLargeBold']) self.cl.configure(bg=self.efbg.get(), fg=GrayScale(20)) self.cl.configure(relief=FLAT) self.cl.configure(padx=2, pady=2, anchor=N) self.cl.place(relx=0.05, rely=0.05, relwidth=0.90, relheight=0.05) def exp_label(self): # creating exp_label for explanation frame self.el = Label(self.ef) self.el.configure(text=self.exp_text.get()) self.el.configure(font=MyFonts['LargeBold']) self.el.configure(bg=self.efbg.get(), fg=GrayScale(20)) self.el.configure(relief=FLAT) self.el.configure(padx=2, pady=2, anchor=N) self.el.place(relx=0.05, rely=0.10, relwidth=0.90, relheight=0.85) def next_ques_button(self): # creating next question button for explanation frame self.nq = MyButton(self.ef, 'Next Question', self.next_ques, 0.80, 0.85) def disp_ans_button(self): # creating display answer button for explanation frame self.da = MyButton(self.ef, 'Show Answer', self.disp_ans, 0.65, 0.85) def assign_all(self): # assigning correct answer text (ans_text) and explanation attributes (ans_exp) if self.ans == 1: self.ans_text = 'A. ' + self.text1 self.ans_exp = self.exp1 elif self.ans == 2: self.ans_text = 'B. ' + self.text2 self.ans_exp = self.exp2 elif self.ans == 3: self.ans_text = 'C. ' + self.text3 self.ans_exp = self.exp3 elif self.ans == 4: self.ans_text = 'D. ' + self.text4 self.ans_exp = self.exp4 else: self.ans_text = 'invalid correct_ans parameter' self.ans_exp = 'invalid correct_ans parameter' print 'invalid correct_ans parameter, please input between 1 and 4' def check_ans(self): # defining check answer function # is_correct (Boolean conditional) if self.ans_input.get() == self.ans: self.efbg.set(color_green) self.is_correct.set(True) self.is_correct_text.set('Correct Answer! :)') else: self.efbg.set(color_red) self.is_correct.set(False) self.is_correct_text.set('Wrong Answer :(') # only assign values for show answer if user answer is wrong self.assign_all() # appropriate response to selected answer if self.ans_input.get() == 1: self.exp_text.set(self.exp1) self.explanation_frame() self.qf.destroy() elif self.ans_input.get() == 2: self.exp_text.set(self.exp2) self.explanation_frame() self.qf.destroy() elif self.ans_input.get() == 3: self.exp_text.set(self.exp3) self.explanation_frame() self.qf.destroy() elif self.ans_input.get() == 4: self.exp_text.set(self.exp4) self.explanation_frame() self.qf.destroy() else: # no selected answer condition showerror('Error', 'Please select an answer to continue') def disp_ans(self): # defining display answer function tmp_str = self.ans_exp[0].lower() + self.ans_exp[1:] disp_ans_text = 'The correct answer is "' + str( self.ans_text) + '" because ' + str(tmp_str) showinfo('Correct Answer', disp_ans_text) def next_ques(self): # defininf next_question function self.pf.destroy() self.ef.destroy()
class FindReplacePanel(PluginPanel): name='Text Find & Replace' title = _("Text Find & Replace") def init(self, master): PluginPanel.init(self, master) top = self.panel top = TFrame(top, borderwidth=2, style='FlatFrame') top.pack(side = TOP, expand = 1, fill = X) button_frame = TFrame(top, borderwidth=2, style='FlatFrame') button_frame.pack(side = BOTTOM, fill = BOTH, expand = 1) button=TButton(button_frame,text=_('Apply'), command=self.replace) button.pack(side = TOP) #---------------------------------------------------------- main_frame = TFrame(top, style='FlatFrame', borderwidth=3) main_frame.pack(side = TOP, fill=X) self.find_var = StringVar(top); self.find_var.set('') findField = TEntryExt(main_frame, textvariable=self.find_var) findField.pack(side = RIGHT) label = TLabel(main_frame, style='FlatLabel', text = _("Find:")+" ") label.pack(side = RIGHT, anchor = E) #--------------------------------------------------------- main_frame = TFrame(top, style='FlatFrame', borderwidth=3) main_frame.pack(side = TOP, fill=X) self.replace_var = StringVar(top); self.replace_var.set('') replaceField = TEntryExt(main_frame, textvariable=self.replace_var) replaceField.pack(side = RIGHT) label = TLabel(main_frame, style='FlatLabel', text = _("Replace to:")+" ") label.pack(side = RIGHT, anchor = E) main_frame = TFrame(top, style='FlatFrame', borderwidth=3) main_frame.pack(side = TOP) #--------------------------------------------------------- label=TLabel(top, text=" "+_("Parameters")+" ", style="FlatLabel") label.pack() parametersFrameLabel=TLabelframe(top, labelwidget=label, style='Labelframe', borderwidth=4) parametersFrameLabel.pack(side = TOP, fill=X, pady=4, padx=4) parametersFrame = TFrame(parametersFrameLabel, style='FlatFrame') self.var_case_sensitive = BooleanVar(top) self.var_case_sensitive.set(False) self.case_sensitive_check = TCheckbutton(parametersFrame, text = _("Case sensitive"), variable = self.var_case_sensitive) self.case_sensitive_check.pack(side = TOP, anchor=W, padx=5) self.var_whole_word = BooleanVar(top) self.var_whole_word.set(False) self.whole_word_check = TCheckbutton(parametersFrame, text = _("Whole word"), variable = self.var_whole_word) self.whole_word_check.pack(side = TOP, anchor=W, padx=5) self.var_regexp = BooleanVar(top) self.var_regexp.set(False) self.regexpCheck = TCheckbutton(parametersFrame, text = _("RegExp search"), variable = self.var_regexp, command=self.disable_enable_action) self.regexpCheck.pack(side = TOP, anchor=W, padx=5) parametersFrame.pack(side=TOP, fill=X, pady=2) ################################################################ def replace_text(self,objects, toReplace, replaceTo): for object in objects: if object.is_Text: if self.var_regexp.get(): if self.var_case_sensitive.get(): p=re.compile(toReplace) else: p=re.compile(toReplace, re.I) text=p.sub(replaceTo, object.text) app.mw.document.SelectObject(object) app.mw.document.CallObjectMethod(object.__class__,_('Text Replace'),'SetText',text) continue if self.var_whole_word.get(): if not self.var_case_sensitive.get(): if object.text.lower()==toReplace.lower(): text=replaceTo app.mw.document.SelectObject(object) app.mw.document.CallObjectMethod(object.__class__,_('Text Replace'),'SetText',text) else: if object.text==toReplace: text=replaceTo app.mw.document.SelectObject(object) app.mw.document.CallObjectMethod(object.__class__,_('Text Replace'),'SetText',text) else: if object.text.lower().find(toReplace.lower(), 0, len(object.text)) != -1: if not self.var_case_sensitive.get(): text=object.text.lower().replace(toReplace.lower(), replaceTo) else: text=object.text.replace(toReplace, replaceTo) app.mw.document.SelectObject(object) app.mw.document.CallObjectMethod(object.__class__,_('Text Replace'),'SetText',text) if object.is_Group: self.replace_text(object.objects) ################################################################ def replace(self): textObjects=[] textToReplace=self.find_var.get().decode('utf-8') replaceTo=self.replace_var.get().decode('utf-8') for layer in app.mw.document.layers: self.replace_text(layer.objects, textToReplace, replaceTo) app.mw.canvas.ForceRedraw() ################################################################ def disable_enable_action(self): if self.var_regexp.get(): self.whole_word_check['state'] = DISABLED else: self.whole_word_check['state'] = NORMAL ################################################################ def whole_word_action(self): pass
def test_get(self): v = BooleanVar(self.root, True, 'name') self.assertAlmostEqual(True, v.get()) self.root.globalsetvar('name', '0') self.assertAlmostEqual(False, v.get())
class GrepDialog(SearchDialogBase): title = "Find in Files Dialog" icon = "Grep" needwrapbutton = 0 def __init__(self, root, engine, flist): SearchDialogBase.__init__(self, root, engine) self.flist = flist self.globvar = StringVar(root) self.recvar = BooleanVar(root) def open(self, text, searchphrase, io=None): SearchDialogBase.open(self, text, searchphrase) if io: path = io.filename or "" else: path = "" dir, base = os.path.split(path) head, tail = os.path.splitext(base) if not tail: tail = ".py" self.globvar.set(os.path.join(dir, "*" + tail)) def create_entries(self): SearchDialogBase.create_entries(self) self.globent = self.make_entry("In files:", self.globvar)[0] def create_other_buttons(self): f = self.make_frame()[0] btn = Checkbutton(f, anchor="w", variable=self.recvar, text="Recurse down subdirectories") btn.pack(side="top", fill="both") btn.select() def create_command_buttons(self): SearchDialogBase.create_command_buttons(self) self.make_button("Search Files", self.default_command, 1) def default_command(self, event=None): prog = self.engine.getprog() if not prog: return path = self.globvar.get() if not path: self.top.bell() return from idlelib.OutputWindow import OutputWindow # leave here! save = sys.stdout try: sys.stdout = OutputWindow(self.flist) self.grep_it(prog, path) finally: sys.stdout = save def grep_it(self, prog, path): dir, base = os.path.split(path) list = self.findfiles(dir, base, self.recvar.get()) list.sort() self.close() pat = self.engine.getpat() print("Searching %r in %s ..." % (pat, path)) hits = 0 try: for fn in list: try: with open(fn) as f: for lineno, line in enumerate(f, 1): if line[-1:] == '\n': line = line[:-1] if prog.search(line): sys.stdout.write("%s: %s: %s\n" % (fn, lineno, line)) hits += 1 except IOError as msg: print(msg) print(("Hits found: %s\n" "(Hint: right-click to open locations.)" % hits) if hits else "No hits.") except AttributeError: # Tk window has been closed, OutputWindow.text = None, # so in OW.write, OW.text.insert fails. pass def findfiles(self, dir, base, rec): try: names = os.listdir(dir or os.curdir) except os.error as msg: print(msg) return [] list = [] subdirs = [] for name in names: fn = os.path.join(dir, name) if os.path.isdir(fn): subdirs.append(fn) else: if fnmatch.fnmatch(name, base): list.append(fn) if rec: for subdir in subdirs: list.extend(self.findfiles(subdir, base, rec)) return list def close(self, event=None): if self.top: self.top.grab_release() self.top.withdraw()
class A_DWI: def __init__(self, container, frame, label='', text='', row=0, column=0): self.container = container self.is_b0 = BooleanVar(container.parent) self.is_dw = BooleanVar(container.parent) self.column = column self.direction = StringVar(container.parent) self.label_from = Label(frame, text='from') self.text_from = Entry(frame) self.text_from.insert(0, text) self.button_file_from = Button(frame, text='...', command=lambda:filenameDialog_text(self.text_from)) self.button_rm = Button(frame, text='remove', command=self.click_remove) self.radio_ap = Radiobutton(frame, text='AP', variable=self.direction, value='AP', command=self.set_direction) self.radio_pa = Radiobutton(frame, text='PA', variable=self.direction, value='PA', command=self.set_direction) self.label_to = Label(frame, text='to') self.text_to = Entry(frame) #self.text_to.insert(0, text) self.button_file_to = Button(frame, text='Gen', command=self.set_filename_to) self.check_b0 = Checkbutton(frame, text='B0', variable=self.is_b0) self.check_dw = Checkbutton(frame, text='DWI', variable=self.is_dw) self.button_up = Button(frame, text='up', width=3, command=self.click_up) self.button_dn = Button(frame, text='down', width=3, command=self.click_dn) self.row = -1 self.change_row(row) if text != '': self.set_appa() self.set_filename_to() def prefix(self): return self.container.parent.prefix() def set_direction(self): pass def get_dwi_filenames(self): ''' :return: [('from', 'to'), ('from', 'to')] ''' filename_from = self.text_from.get() filename_to = self.text_to.get() if self.is_dw.get(): rtn = [ [filename_from, filename_to] ] filename_b_from = filename_wo_ext(filename_from) filename_b_to = filename_wo_ext(filename_to) rtn.append( [filename_b_from+'.bval', filename_b_to+'.bval'] ) rtn.append( [filename_b_from+'.bvec', filename_b_to+'.bvec'] ) return rtn return [] def get_b0_filename(self): ''' :return: [('from', 'to')] ''' filename_from = self.text_from.get() filename_to = self.text_to.get() ext = extname(filename_to) if self.is_b0.get(): if self.is_dw.get(): filename_to = '%s_B0%s' % (filename_wo_ext(filename_to), ext) return [ [filename_from, filename_to] ] return [] def set_appa(self): filename_from = self.text_from.get() basename_from = os.path.basename(filename_from) basename_b_from = filename_wo_ext(basename_from) if 'pa' in basename_b_from.lower(): self.direction.set('PA') elif 'ap' in basename_b_from.lower(): self.direction.set('AP') else: pass def set_filename_to(self, middle=None): filename_from = self.text_from.get() basename_from = os.path.basename(filename_from) number = os.path.dirname(filename_from).split('/')[-1].split('_')[0] if number == '': number = str(self.row) else: try: int(number) except: number = str(self.row) ext = extname(basename_from) intermediate = self.direction.get() if intermediate == '': intermediate = 'DWI' if self.is_b0.get() and not self.is_dw.get(): intermediate += '_B0' self.text_to.delete(0, len(self.text_to.get())) self.text_to.insert(0, '%s%s_%s%s' % (self.prefix(), number, intermediate, ext)) def change_row(self, row): if self.row == row: return self.row = row i = 2*row j = self.column j += 0; self.button_up.grid(row=i, column=j) j += 1; self.label_from.grid(row=i, column=j) j += 1; self.text_from.grid(row=i, column=j, sticky=EW) j += 1; self.button_file_from.grid(row=i, column=j) j += 1; self.button_rm.grid(row=i, column=j) j += 1; self.radio_ap.grid(row=i, column=j) j += 1; self.radio_pa.grid(row=i, column=j) i += 1 j = 0 j += 0; self.button_dn.grid(row=i, column=j) j += 1; self.label_to.grid(row=i, column=j) j += 1; self.text_to.grid(row=i, column=j, sticky=EW) j += 1; self.button_file_to.grid(row=i, column=j) j += 1 j += 1; self.check_b0.grid(row=i, column=j) j += 1; self.check_dw.grid(row=i, column=j) def click_remove(self): self.container.remove(self.row) self.button_up.destroy() self.label_from.destroy() self.text_from.destroy() self.button_file_from.destroy() self.button_rm.destroy() self.radio_ap.destroy() self.radio_pa.destroy() self.button_dn.destroy() self.label_to.destroy() self.text_to.destroy() self.button_file_to.destroy() self.check_b0.destroy() self.check_dw.destroy() def click_up(self): self.container.up(self.row) def click_dn(self): self.container.dn(self.row)
class SearchEngine: def __init__(self, root): self.root = root self.patvar = StringVar(root, '') self.revar = BooleanVar(root, False) self.casevar = BooleanVar(root, False) self.wordvar = BooleanVar(root, False) self.wrapvar = BooleanVar(root, True) self.backvar = BooleanVar(root, False) def getpat(self): return self.patvar.get() def setpat(self, pat): self.patvar.set(pat) def isre(self): return self.revar.get() def iscase(self): return self.casevar.get() def isword(self): return self.wordvar.get() def iswrap(self): return self.wrapvar.get() def isback(self): return self.backvar.get() def setcookedpat(self, pat): if self.isre(): pat = re.escape(pat) self.setpat(pat) def getcookedpat(self): pat = self.getpat() if not self.isre(): pat = re.escape(pat) if self.isword(): pat = '\\b%s\\b' % pat return pat def getprog(self): pat = self.getpat() if not pat: self.report_error(pat, 'Empty regular expression') return None else: pat = self.getcookedpat() flags = 0 if not self.iscase(): flags = flags | re.IGNORECASE try: prog = re.compile(pat, flags) except re.error as what: args = what.args msg = args[0] col = arg[1] if len(args) >= 2 else -1 self.report_error(pat, msg, col) return None return prog def report_error(self, pat, msg, col=-1): msg = 'Error: ' + str(msg) if pat: msg = msg + '\nPattern: ' + str(pat) if col >= 0: msg = msg + '\nOffset: ' + str(col) tkMessageBox.showerror('Regular expression error', msg, master=self.root) def search_text(self, text, prog=None, ok=0): if not prog: prog = self.getprog() if not prog: return None wrap = self.wrapvar.get() first, last = get_selection(text) if self.isback(): if ok: start = last else: start = first line, col = get_line_col(start) res = self.search_backward(text, prog, line, col, wrap, ok) else: if ok: start = first else: start = last line, col = get_line_col(start) res = self.search_forward(text, prog, line, col, wrap, ok) return res def search_forward(self, text, prog, line, col, wrap, ok=0): wrapped = 0 startline = line chars = text.get('%d.0' % line, '%d.0' % (line + 1)) while chars: m = prog.search(chars[:-1], col) if m and (ok or m.end() > col): return (line, m) line = line + 1 if wrapped and line > startline: break col = 0 ok = 1 chars = text.get('%d.0' % line, '%d.0' % (line + 1)) if not chars and wrap: wrapped = 1 wrap = 0 line = 1 chars = text.get('1.0', '2.0') return None def search_backward(self, text, prog, line, col, wrap, ok=0): wrapped = 0 startline = line chars = text.get('%d.0' % line, '%d.0' % (line + 1)) while 1: m = search_reverse(prog, chars[:-1], col) if m and (ok or m.start() < col): return (line, m) line = line - 1 if wrapped and line < startline: break ok = 1 if line <= 0: if not wrap: break wrapped = 1 wrap = 0 pos = text.index('end-1c') line, col = map(int, pos.split('.')) chars = text.get('%d.0' % line, '%d.0' % (line + 1)) col = len(chars) - 1 return None
def test_default(self): v = BooleanVar(self.root) self.assertIs(v.get(), False)
class wm_seg: """ Simple GUI application If the application inside a container, automatic updates are removed. The application uses two frames (tabs): - training - testing """ def __init__(self, master, container): self.master = master master.title("nicMSlesions") # running on a container self.container = container # gui attributes self.path = os.getcwd() self.default_config = None self.user_config = None self.current_folder = os.getcwd() self.list_train_pretrained_nets = [] self.list_test_nets = [] self.version = __version__ if self.container is False: # version_number self.commit_version = subprocess.check_output( ['git', 'rev-parse', 'HEAD']) # queue and thread parameters. All processes are embedded # inside threads to avoid freezing the application self.train_task = None self.test_task = None self.test_queue = Queue.Queue() self.train_queue = Queue.Queue() # -------------------------------------------------- # parameters. Mostly from the config/*.cfg files # -------------------------------------------------- # data parameters self.param_training_folder = StringVar() self.param_test_folder = StringVar() self.param_FLAIR_tag = StringVar() self.param_T1_tag = StringVar() self.param_MOD3_tag = StringVar() self.param_MOD4_tag = StringVar() self.param_mask_tag = StringVar() self.param_model_tag = StringVar() self.param_register_modalities = BooleanVar() self.param_skull_stripping = BooleanVar() self.param_denoise = BooleanVar() self.param_denoise_iter = IntVar() self.param_save_tmp = BooleanVar() self.param_debug = BooleanVar() # train parameters self.param_net_folder = os.path.join(self.current_folder, 'nets') self.param_use_pretrained_model = BooleanVar() self.param_pretrained_model = StringVar() self.param_inference_model = StringVar() self.param_num_layers = IntVar() self.param_net_name = StringVar() self.param_net_name.set('None') self.param_balanced_dataset = StringVar() self.param_fract_negatives = DoubleVar() # model parameters self.param_pretrained = None self.param_min_th = DoubleVar() self.param_patch_size = IntVar() self.param_weight_paths = StringVar() self.param_load_weights = BooleanVar() self.param_train_split = DoubleVar() self.param_max_epochs = IntVar() self.param_patience = IntVar() self.param_batch_size = IntVar() self.param_net_verbose = IntVar() self.param_t_bin = DoubleVar() self.param_l_min = IntVar() self.param_min_error = DoubleVar() self.param_mode = BooleanVar() self.param_gpu_number = IntVar() # load the default configuration from the conf file self.load_default_configuration() # self frame (tabbed notebook) self.note = Notebook(self.master) self.note.pack() os.system('cls' if platform.system() == 'Windows' else 'clear') print "##################################################" print "# ------------ #" print "# nicMSlesions #" print "# ------------ #" print "# MS WM lesion segmentation #" print "# #" print "# ------------------------------- #" print "# (c) Sergi Valverde 2018 #" print "# Neuroimage Computing Group #" print "# ------------------------------- #" print "##################################################\n" print "Please select options for training or inference in the menu..." # -------------------------------------------------- # training tab # -------------------------------------------------- self.train_frame = Frame() self.note.add(self.train_frame, text="Training") self.test_frame = Frame() self.note.add(self.test_frame, text="Inference") # label frames cl_s = 5 self.tr_frame = LabelFrame(self.train_frame, text="Training images:") self.tr_frame.grid(row=0, columnspan=cl_s, sticky='WE', padx=5, pady=5, ipadx=5, ipady=5) self.model_frame = LabelFrame(self.train_frame, text="CNN model:") self.model_frame.grid(row=5, columnspan=cl_s, sticky='WE', padx=5, pady=5, ipadx=5, ipady=5) # training options self.inFolderLbl = Label(self.tr_frame, text="Training folder:") self.inFolderLbl.grid(row=0, column=0, sticky='E', padx=5, pady=2) self.inFolderTxt = Entry(self.tr_frame) self.inFolderTxt.grid(row=0, column=1, columnspan=5, sticky="W", pady=3) self.inFileBtn = Button(self.tr_frame, text="Browse ...", command=self.load_training_path) self.inFileBtn.grid(row=0, column=5, columnspan=1, sticky='W', padx=5, pady=1) self.optionsBtn = Button(self.tr_frame, text="Other options", command=self.parameter_window) self.optionsBtn.grid(row=0, column=10, columnspan=1, sticky="W", padx=(100, 1), pady=1) # setting input modalities: FLAIR + T1 are mandatory # Mod 3 / 4 are optional self.flairTagLbl = Label(self.tr_frame, text="FLAIR tag:") self.flairTagLbl.grid(row=1, column=0, sticky='E', padx=5, pady=2) self.flairTxt = Entry(self.tr_frame, textvariable=self.param_FLAIR_tag) self.flairTxt.grid(row=1, column=1, columnspan=1, sticky="W", pady=1) self.t1TagLbl = Label(self.tr_frame, text="T1 tag:") self.t1TagLbl.grid(row=2, column=0, sticky='E', padx=5, pady=2) self.t1Txt = Entry(self.tr_frame, textvariable=self.param_T1_tag) self.t1Txt.grid(row=2, column=1, columnspan=1, sticky="W", pady=1) self.mod3TagLbl = Label(self.tr_frame, text="mod 3 tag:") self.mod3TagLbl.grid(row=3, column=0, sticky='E', padx=5, pady=2) self.mod3Txt = Entry(self.tr_frame, textvariable=self.param_MOD3_tag) self.mod3Txt.grid(row=3, column=1, columnspan=1, sticky="W", pady=1) self.mod4TagLbl = Label(self.tr_frame, text="mod 4 tag:") self.mod4TagLbl.grid(row=4, column=0, sticky='E', padx=5, pady=2) self.mod4Txt = Entry(self.tr_frame, textvariable=self.param_MOD4_tag) self.mod4Txt.grid(row=4, column=1, columnspan=1, sticky="W", pady=1) self.maskTagLbl = Label(self.tr_frame, text="MASK tag:") self.maskTagLbl.grid(row=5, column=0, sticky='E', padx=5, pady=2) self.maskTxt = Entry(self.tr_frame, textvariable=self.param_mask_tag) self.maskTxt.grid(row=5, column=1, columnspan=1, sticky="W", pady=1) # model options self.modelTagLbl = Label(self.model_frame, text="Model name:") self.modelTagLbl.grid(row=6, column=0, sticky='E', padx=5, pady=2) self.modelTxt = Entry(self.model_frame, textvariable=self.param_net_name) self.modelTxt.grid(row=6, column=1, columnspan=1, sticky="W", pady=1) self.checkPretrain = Checkbutton(self.model_frame, text="use pretrained", var=self.param_use_pretrained_model) self.checkPretrain.grid(row=6, column=3, padx=5, pady=5) self.update_pretrained_nets() self.pretrainTxt = OptionMenu(self.model_frame, self.param_pretrained_model, *self.list_train_pretrained_nets) self.pretrainTxt.grid(row=6, column=5, sticky='E', padx=5, pady=5) # START button links self.trainingBtn = Button(self.train_frame, state='disabled', text="Start training", command=self.train_net) self.trainingBtn.grid(row=7, column=0, sticky='W', padx=1, pady=1) # -------------------------------------------------- # inference tab # -------------------------------------------------- self.tt_frame = LabelFrame(self.test_frame, text="Inference images:") self.tt_frame.grid(row=0, columnspan=cl_s, sticky='WE', padx=5, pady=5, ipadx=5, ipady=5) self.test_model_frame = LabelFrame(self.test_frame, text="CNN model:") self.test_model_frame.grid(row=5, columnspan=cl_s, sticky='WE', padx=5, pady=5, ipadx=5, ipady=5) # testing options self.test_inFolderLbl = Label(self.tt_frame, text="Testing folder:") self.test_inFolderLbl.grid(row=0, column=0, sticky='E', padx=5, pady=2) self.test_inFolderTxt = Entry(self.tt_frame) self.test_inFolderTxt.grid(row=0, column=1, columnspan=5, sticky="W", pady=3) self.test_inFileBtn = Button(self.tt_frame, text="Browse ...", command=self.load_testing_path) self.test_inFileBtn.grid(row=0, column=5, columnspan=1, sticky='W', padx=5, pady=1) self.test_optionsBtn = Button(self.tt_frame, text="Other options", command=self.parameter_window) self.test_optionsBtn.grid(row=0, column=10, columnspan=1, sticky="W", padx=(100, 1), pady=1) self.test_flairTagLbl = Label(self.tt_frame, text="FLAIR tag:") self.test_flairTagLbl.grid(row=1, column=0, sticky='E', padx=5, pady=2) self.test_flairTxt = Entry(self.tt_frame, textvariable=self.param_FLAIR_tag) self.test_flairTxt.grid(row=1, column=1, columnspan=1, sticky="W", pady=1) self.test_t1TagLbl = Label(self.tt_frame, text="T1 tag:") self.test_t1TagLbl.grid(row=2, column=0, sticky='E', padx=5, pady=2) self.test_t1Txt = Entry(self.tt_frame, textvariable=self.param_T1_tag) self.test_t1Txt.grid(row=2, column=1, columnspan=1, sticky="W", pady=1) self.test_mod3TagLbl = Label(self.tt_frame, text="mod 3 tag:") self.test_mod3TagLbl.grid(row=3, column=0, sticky='E', padx=5, pady=2) self.test_mod3Txt = Entry(self.tt_frame, textvariable=self.param_MOD3_tag) self.test_mod3Txt.grid(row=3, column=1, columnspan=1, sticky="W", pady=1) self.test_mod4TagLbl = Label(self.tt_frame, text="mod 4 tag:") self.test_mod4TagLbl.grid(row=4, column=0, sticky='E', padx=5, pady=2) self.test_mod4Txt = Entry(self.tt_frame, textvariable=self.param_MOD4_tag) self.test_mod4Txt.grid(row=4, column=1, columnspan=1, sticky="W", pady=1) self.test_pretrainTxt = OptionMenu(self.test_model_frame, self.param_inference_model, *self.list_test_nets) self.param_inference_model.set('None') self.test_pretrainTxt.grid(row=5, column=0, sticky='E', padx=5, pady=5) # START button links cto docker task self.inferenceBtn = Button(self.test_frame, state='disabled', text="Start inference", command=self.infer_segmentation) self.inferenceBtn.grid(row=7, column=0, sticky='W', padx=1, pady=1) # train / test ABOUT button self.train_aboutBtn = Button(self.train_frame, text="about", command=self.about_window) self.train_aboutBtn.grid(row=7, column=4, sticky='E', padx=(1, 1), pady=1) self.test_aboutBtn = Button(self.test_frame, text="about", command=self.about_window) self.test_aboutBtn.grid(row=7, column=4, sticky='E', padx=(1, 1), pady=1) # Processing state self.process_indicator = StringVar() self.process_indicator.set(' ') self.label_indicator = Label(master, textvariable=self.process_indicator) self.label_indicator.pack(side="left") # Closing processing events is implemented via # a master protocol self.master.protocol("WM_DELETE_WINDOW", self.close_event) def parameter_window(self): """ Setting other parameters using an emerging window CNN parameters, CUDA device, post-processing.... """ t = Toplevel(self.master) t.wm_title("Other parameters") # data parameters t_data = LabelFrame(t, text="data options:") t_data.grid(row=0, sticky="WE") checkPretrain = Checkbutton(t_data, text="Register modalities", var=self.param_register_modalities) checkPretrain.grid(row=0, sticky='W') checkSkull = Checkbutton(t_data, text="Skull-strip modalities", var=self.param_skull_stripping) checkSkull.grid(row=1, sticky="W") checkDenoise = Checkbutton(t_data, text="Denoise masks", var=self.param_denoise) checkDenoise.grid(row=2, sticky="W") denoise_iter_label = Label(t_data, text=" Denoise iter: ") denoise_iter_label.grid(row=3, sticky="W") denoise_iter_entry = Entry(t_data, textvariable=self.param_denoise_iter) denoise_iter_entry.grid(row=3, column=1, sticky="E") check_tmp = Checkbutton(t_data, text="Save tmp files", var=self.param_save_tmp) check_tmp.grid(row=4, sticky="W") checkdebug = Checkbutton(t_data, text="Debug mode", var=self.param_debug) checkdebug.grid(row=5, sticky="W") # model parameters t_model = LabelFrame(t, text="Model:") t_model.grid(row=5, sticky="EW") maxepochs_label = Label(t_model, text="Max epochs: ") maxepochs_label.grid(row=6, sticky="W") maxepochs_entry = Entry(t_model, textvariable=self.param_max_epochs) maxepochs_entry.grid(row=6, column=1, sticky="E") trainsplit_label = Label(t_model, text="Validation %: ") trainsplit_label.grid(row=7, sticky="W") trainsplit_entry = Entry(t_model, textvariable=self.param_train_split) trainsplit_entry.grid(row=7, column=1, sticky="E") batchsize_label = Label(t_model, text="Test batch size:") batchsize_label.grid(row=8, sticky="W") batchsize_entry = Entry(t_model, textvariable=self.param_batch_size) batchsize_entry.grid(row=8, column=1, sticky="E") mode_label = Label(t_model, text="Verbosity:") mode_label.grid(row=9, sticky="W") mode_entry = Entry(t_model, textvariable=self.param_net_verbose) mode_entry.grid(row=9, column=1, sticky="E") #gpu_mode = Checkbutton(t_model, # text="GPU:", # var=self.param_mode) #gpu_mode.grid(row=10, sticky="W") gpu_number = Label(t_model, text="GPU number:") gpu_number.grid(row=10, sticky="W") gpu_entry = Entry(t_model, textvariable=self.param_gpu_number) gpu_entry.grid(row=10, column=1, sticky="W") # training parameters tr_model = LabelFrame(t, text="Training:") tr_model.grid(row=12, sticky="EW") balanced_label = Label(tr_model, text="Balanced dataset: ") balanced_label.grid(row=13, sticky="W") balanced_entry = Entry(tr_model, textvariable=self.param_balanced_dataset) balanced_entry.grid(row=13, column=1, sticky="E") fraction_label = Label(tr_model, text="Fraction negative/positives: ") fraction_label.grid(row=14, sticky="W") fraction_entry = Entry(tr_model, textvariable=self.param_fract_negatives) fraction_entry.grid(row=14, column=1, sticky="E") # postprocessing parameters t_post = LabelFrame(t, text="Post-processing: ") t_post.grid(row=15, sticky="EW") t_bin_label = Label(t_post, text="Out probability th: ") t_bin_label.grid(row=16, sticky="W") t_bin_entry = Entry(t_post, textvariable=self.param_t_bin) t_bin_entry.grid(row=16, column=1, sticky="E") l_min_label = Label(t_post, text="Min out region size: ") l_min_label.grid(row=17, sticky="W") l_min_entry = Entry(t_post, textvariable=self.param_l_min) l_min_entry.grid(row=17, column=1, sticky="E") vol_min_label = Label(t_post, text="Min vol error (ml): ") vol_min_label.grid(row=18, sticky="W") vol_min_entry = Entry(t_post, textvariable=self.param_min_error) vol_min_entry.grid(row=18, column=1, sticky="E") def load_default_configuration(self): """ load the default configuration from /config/default.cfg This method assign each of the configuration parameters to class attributes """ default_config = ConfigParser.SafeConfigParser() default_config.read(os.path.join(self.path, 'config', 'default.cfg')) # dastaset parameters self.param_training_folder.set( default_config.get('database', 'train_folder')) self.param_test_folder.set( default_config.get('database', 'inference_folder')) self.param_FLAIR_tag.set(default_config.get('database', 'flair_tags')) self.param_T1_tag.set(default_config.get('database', 't1_tags')) self.param_MOD3_tag.set(default_config.get('database', 'mod3_tags')) self.param_MOD4_tag.set(default_config.get('database', 'mod4_tags')) self.param_mask_tag.set(default_config.get('database', 'roi_tags')) self.param_register_modalities.set( default_config.get('database', 'register_modalities')) self.param_denoise.set(default_config.get('database', 'denoise')) self.param_denoise_iter.set( default_config.getint('database', 'denoise_iter')) self.param_skull_stripping.set( default_config.get('database', 'skull_stripping')) self.param_save_tmp.set(default_config.get('database', 'save_tmp')) self.param_debug.set(default_config.get('database', 'debug')) # train parameters self.param_use_pretrained_model.set( default_config.get('train', 'full_train')) self.param_pretrained_model.set( default_config.get('train', 'pretrained_model')) self.param_inference_model.set(" ") self.param_balanced_dataset.set( default_config.get('train', 'balanced_training')) self.param_fract_negatives.set( default_config.getfloat('train', 'fraction_negatives')) # model parameters self.param_net_folder = os.path.join(self.current_folder, 'nets') self.param_net_name.set(default_config.get('model', 'name')) self.param_train_split.set( default_config.getfloat('model', 'train_split')) self.param_max_epochs.set(default_config.getint('model', 'max_epochs')) self.param_patience.set(default_config.getint('model', 'patience')) self.param_batch_size.set(default_config.getint('model', 'batch_size')) self.param_net_verbose.set(default_config.get('model', 'net_verbose')) self.param_gpu_number.set(default_config.getint('model', 'gpu_number')) # self.param_mode.set(default_config.get('model', 'gpu_mode')) # post-processing self.param_l_min.set(default_config.getint('postprocessing', 'l_min')) self.param_t_bin.set(default_config.getfloat('postprocessing', 't_bin')) self.param_min_error.set( default_config.getfloat('postprocessing', 'min_error')) def write_user_configuration(self): """ write the configuration into config/configuration.cfg """ user_config = ConfigParser.RawConfigParser() # dataset parameters user_config.add_section('database') user_config.set('database', 'train_folder', self.param_training_folder.get()) user_config.set('database', 'inference_folder', self.param_test_folder.get()) user_config.set('database', 'flair_tags', self.param_FLAIR_tag.get()) user_config.set('database', 't1_tags', self.param_T1_tag.get()) user_config.set('database', 'mod3_tags', self.param_MOD3_tag.get()) user_config.set('database', 'mod4_tags', self.param_MOD4_tag.get()) user_config.set('database', 'roi_tags', self.param_mask_tag.get()) user_config.set('database', 'register_modalities', self.param_register_modalities.get()) user_config.set('database', 'denoise', self.param_denoise.get()) user_config.set('database', 'denoise_iter', self.param_denoise_iter.get()) user_config.set('database', 'skull_stripping', self.param_skull_stripping.get()) user_config.set('database', 'save_tmp', self.param_save_tmp.get()) user_config.set('database', 'debug', self.param_debug.get()) # train parameters user_config.add_section('train') user_config.set('train', 'full_train', not (self.param_use_pretrained_model.get())) user_config.set('train', 'pretrained_model', self.param_pretrained_model.get()) user_config.set('train', 'balanced_training', self.param_balanced_dataset.get()) user_config.set('train', 'fraction_negatives', self.param_fract_negatives.get()) # model parameters user_config.add_section('model') user_config.set('model', 'name', self.param_net_name.get()) user_config.set('model', 'pretrained', self.param_pretrained) user_config.set('model', 'train_split', self.param_train_split.get()) user_config.set('model', 'max_epochs', self.param_max_epochs.get()) user_config.set('model', 'patience', self.param_patience.get()) user_config.set('model', 'batch_size', self.param_batch_size.get()) user_config.set('model', 'net_verbose', self.param_net_verbose.get()) # user_config.set('model', 'gpu_mode', self.param_mode.get()) user_config.set('model', 'gpu_number', self.param_gpu_number.get()) # postprocessing parameters user_config.add_section('postprocessing') user_config.set('postprocessing', 't_bin', self.param_t_bin.get()) user_config.set('postprocessing', 'l_min', self.param_l_min.get()) user_config.set('postprocessing', 'min_error', self.param_min_error.get()) # Writing our configuration file to 'example.cfg' with open(os.path.join(self.path, 'config', 'configuration.cfg'), 'wb') as configfile: user_config.write(configfile) def load_training_path(self): """ Select training path from disk and write it. If the app is run inside a container, link the iniitaldir with /data """ initialdir = '/data' if self.container else os.getcwd() fname = askdirectory(initialdir=initialdir) if fname: try: self.param_training_folder.set(fname) self.inFolderTxt.delete(0, END) self.inFolderTxt.insert(0, self.param_training_folder.get()) self.trainingBtn['state'] = 'normal' except: pass def load_testing_path(self): """ Selecet the inference path from disk and write it If the app is run inside a container, link the iniitaldir with /data """ initialdir = '/data' if self.container else os.getcwd() fname = askdirectory(initialdir=initialdir) if fname: try: self.param_test_folder.set(fname) self.test_inFolderTxt.delete(0, END) self.test_inFolderTxt.insert(0, self.param_test_folder.get()) self.inferenceBtn['state'] = 'normal' except: pass def update_pretrained_nets(self): """ get a list of the different net configuration present in the system. Each model configuration is represented by a folder containing the network weights for each of the networks. The baseline net config is always included by default """ folders = os.listdir(self.param_net_folder) self.list_train_pretrained_nets = folders self.list_test_nets = folders def write_to_console(self, txt): """ to doc: important method """ self.command_out.insert(END, str(txt)) def write_to_test_console(self, txt): """ to doc: important method """ self.test_command_out.insert(END, str(txt)) def infer_segmentation(self): """ Method implementing the inference process: - Check network selection - write the configuration to disk - Run the process on a new thread """ if self.param_inference_model.get() == 'None': print "ERROR: Please, select a network model before starting...\n" return if self.test_task is None: self.inferenceBtn.config(state='disabled') self.param_net_name.set(self.param_inference_model.get()) self.param_use_pretrained_model.set(False) self.write_user_configuration() print "\n-----------------------" print "Running configuration:" print "-----------------------" print "Inference model:", self.param_model_tag.get() print "Inference folder:", self.param_test_folder.get(), "\n" print "Method info:" print "------------" self.test_task = ThreadedTask(self.write_to_test_console, self.test_queue, mode='testing') self.test_task.start() self.master.after(100, self.process_container_queue) def train_net(self): """ Method implementing the training process: - write the configuration to disk - Run the process on a new thread """ if self.param_net_name.get() == 'None': print "ERROR: Please, define network name before starting...\n" return self.trainingBtn['state'] = 'disable' if self.train_task is None: self.trainingBtn.update() self.write_user_configuration() print "\n-----------------------" print "Running configuration:" print "-----------------------" print "Train model:", self.param_net_name.get() print "Training folder:", self.param_training_folder.get(), "\n" print "Method info:" print "------------" self.train_task = ThreadedTask(self.write_to_console, self.test_queue, mode='training') self.train_task.start() self.master.after(100, self.process_container_queue) def check_update(self): """ check update version and propose to download it if differnt So far, a rudimentary mode is used to check the last version. """ # I have to discard possible local changes :( print "---------------------------------------" print "Updating software" print "current version:", self.commit_version remote_commit = subprocess.check_output(['git', 'stash']) remote_commit = subprocess.check_output(['git', 'fetch']) remote_commit = subprocess.check_output( ['git', 'rev-parse', 'origin/master']) if remote_commit != self.commit_version: proc = subprocess.check_output(['git', 'pull', 'origin', 'master']) self.check_link.config(text="Updated") self.commit_version = remote_commit print "updated version:", self.commit_version else: print "This software is already in the latest version" print "---------------------------------------" def about_window(self): """ Window showing information about the software and version number, including auto-update. If the application is run from a container, then auto-update is disabled """ def callback(event): """ open webbrowser when clicking links """ webbrowser.open_new(event.widget.cget("text")) # main window t = Toplevel(self.master, width=500, height=500) t.wm_title("About") # NIC logo + name title = Label(t, text="nicMSlesions v" + self.version + "\n" "Multiple Sclerosis White Matter Lesion Segmentation") title.grid(row=2, column=1, padx=20, pady=10) img = ImageTk.PhotoImage(Image.open('./logonic.png')) imglabel = Label(t, image=img) imglabel.image = img imglabel.grid(row=1, column=1, padx=10, pady=10) group_name = Label(t, text="Copyright Sergi Valverde (2018-) \n " + "NeuroImage Computing Group") group_name.grid(row=3, column=1) group_link = Label(t, text=r"http://atc.udg.edu/nic", fg="blue", cursor="hand2") group_link.grid(row=4, column=1) group_link.bind("<Button-1>", callback) license_content = "Licensed under the BSD 2-Clause license. \n" + \ "A copy of the license is present in the root directory." license_label = Label(t, text=license_content) license_label.grid(row=5, column=1, padx=20, pady=20) # if self.container is False: # # check version and updates # version_number = Label(t, text="commit: " + self.commit_version) # version_number.grid(row=6, column=1, padx=20, pady=(1, 1)) # # self.check_link = Button(t, # text="Check for updates", # command=self.check_update) # self.check_link.grid(row=7, column=1) def process_container_queue(self): """ Process the threading queue. When the threaded processes are finished, buttons are reset and a message is shown in the app. """ self.process_indicator.set('Running... please wait') try: msg = self.test_queue.get(0) self.process_indicator.set('Done. See log for more details.') self.inferenceBtn['state'] = 'normal' self.trainingBtn['state'] = 'normal' except Queue.Empty: self.master.after(100, self.process_container_queue) def close_event(self): """ Stop the thread processes using OS related calls. """ if self.train_task is not None: self.train_task.stop_process() if self.test_task is not None: self.test_task.stop_process() os.system('cls' if platform.system == "Windows" else 'clear') root.destroy()
class Example(Frame): ####################################################################### def __init__(self, parent): Frame.__init__(self, width=1000, height=1000, background="green") self.parent = parent self.pack(fill=BOTH, expand=True) self.initUI() def initUI(self): self.parent.title("Cravis_ver1") self.pack(fill=BOTH, expand=1) frame = Frame(self, width=1500, height=200, relief=RAISED, borderwidth=1) frame.pack(expand=False) #frame.config(bg="blue") self.pack(expand=False) ##### ##### frame2 = Frame(self, width=1500, height=300, relief=RAISED, borderwidth=1) frame2.pack(expand=False) self.pack(expand=False) self.var0 = BooleanVar() self.var1 = BooleanVar() self.var2 = BooleanVar() self.var3 = BooleanVar() self.var4 = BooleanVar() self.var5 = BooleanVar() self.content = IntVar() reset_Area_Button = Button(self, width=10, text="reset_Area", command=self.reset_Area) reset_Area_Button.place(x=610, y=400) set_Area_Button = Button(self, width=10, text="set_Area", command=self.set_Area) set_Area_Button.place(x=610, y=430) show_Area_Button = Button(self, width=10, text="show_Area", command=self.show_Area) show_Area_Button.place(x=610, y=460) quitButton = Button(self, text="Quit", command=self.off_video) quitButton.place(x=50, y=20) startButton = Button(self, text="Video", command=self.on_start) startButton.place(x=100, y=20) TakePicButton = Button(self, text="TakePic", command=self.Takepic) TakePicButton.place(x=150, y=20) LoadDataButton = Button(self, text="Load_Data", bg="green", command=self.confirm_LoadData) LoadDataButton.place(x=550, y=90) SaveDataButton = Button(self, text="Save_Data", bg="green", command=self.confirm_SaveData) SaveDataButton.place(x=550, y=120) ###### cb1 = Checkbutton(self, text="Binary", variable=self.var1, command=self.on_Binary) cb1.place(x=80, y=50) cb2 = Checkbutton(self, text="Partical", variable=self.var2, command=self.on_Partical) cb2.place(x=80, y=80) cb3 = Checkbutton(self, text="Sobel", variable=self.var3, command=self.on_Sobel) cb3.place(x=80, y=110) cb4 = Checkbutton(self, text="Median", variable=self.var4, command=self.on_Median) cb4.place(x=80, y=140) cb5 = Checkbutton(self, text="Level_Adjust", variable=self.var5, command=self.on_LevelAdjust) cb5.place(x=80, y=170) cb5 = Checkbutton(self, text="SaveImage", variable=self.var0) cb5.place(x=550, y=20) ##### ################################### AdjustBinaryButton = Button(self, text="Adjust_Binary", command=self.AdjustBinary) AdjustBinaryButton.place(x=340, y=50) AdjustExtractButton = Button(self, text="Adjust_Extract", command=self.AdjustExtract) AdjustExtractButton.place(x=340, y=80) AdjustBinaryButton = Button(self, text="Adjust_3", command=self.AdjustBinary) AdjustBinaryButton.place(x=340, y=110) AdjustExtractButton = Button(self, text="Adjust_4", command=self.AdjustExtract) AdjustExtractButton.place(x=340, y=140) AdjustExtractButton = Button(self, text="Adjust_5", command=self.AdjustExtract) AdjustExtractButton.place(x=340, y=170) ######## self.infor_Alg1 = Text(self, width=40, height=1) #self.infor_Alg1.pack(side=LEFT) self.infor_Alg1.place(x=130, y=250) #thongtin_Alg1="Binary : " #self.infor_Alg1.insert(END,thongtin_Alg1) self.label_Alg1 = Label(self, text="Binary: ") self.label_Alg1.place(x=50, y=250) ## self.infor_Alg2 = Text(self, width=40, height=1) #self.infor_Alg2.pack(side=LEFT) self.infor_Alg2.place(x=130, y=270) #thongtin_Alg2="Extract : " #self.infor_Alg2.insert(END,thongtin_Alg2) self.label_Alg2 = Label(self, text="Extract: ") self.label_Alg2.place(x=50, y=270) ## self.infor_Alg3 = Text(self, width=40, height=1) #self.infor_Alg3.pack() self.infor_Alg3.place(x=130, y=290) #thongtin_Alg3="Alg_3 : " #self.infor_Alg3.insert(END,thongtin_Alg3) self.label_Alg3 = Label(self, text="Alg3: ") self.label_Alg3.place(x=50, y=290) ## self.infor_Alg4 = Text(self, width=40, height=1) #self.infor_Alg4.pack(side=LEFT) self.infor_Alg4.place(x=130, y=310) #thongtin_Alg4="Alg_4 : " #self.infor_Alg4.insert(END,thongtin_Alg4) self.label_Alg4 = Label(self, text="Alg4: ") self.label_Alg4.place(x=50, y=310) ## self.infor_Alg5 = Text(self, width=40, height=1) #self.infor_Alg5.pack() self.infor_Alg5.place(x=130, y=330) #thongtin_Alg5="Alg_5 : " #self.infor_Alg5.insert(END,thongtin_Alg5) self.label_Alg5 = Label(self, text="Alg5: ") self.label_Alg5.place(x=50, y=330) ## self.infor_Area1 = Text(self, width=20, height=1) self.infor_Area1.place(x=100, y=400) #thongtin_Area1="Area1:" #self.infor_Area1.insert(END,thongtin_Area1) self.label_Area1 = Label(self, text="Area1: ") self.label_Area1.place(x=50, y=400) ## self.infor_Area2 = Text(self, width=20, height=1) self.infor_Area2.place(x=350, y=400) #thongtin_Area2="Area2:" #self.infor_Area2.insert(END,thongtin_Area2) self.label_Area2 = Label(self, text="Area2: ") self.label_Area2.place(x=300, y=400) ## self.infor_Area3 = Text(self, width=20, height=1) self.infor_Area3.place(x=100, y=450) #thongtin_Area3="Area3:" #self.infor_Area3.insert(END,thongtin_Area3) self.label_Area3 = Label(self, text="Area3: ") self.label_Area3.place(x=50, y=450) ## self.infor_Area4 = Text(self, width=20, height=1) self.infor_Area4.place(x=350, y=450) #thongtin_Area4="Area4:" #self.infor_Area4.insert(END,thongtin_Area4) self.label_Area4 = Label(self, text="Area4: ") self.label_Area4.place(x=300, y=450) ##### ################################ self.infor = Text(self, width=50, height=2) self.infor.pack() thongtin = "CHAO MUNG DEN VOI CHUONG TRINH CRAVIS_V1 \n DESIGN BY VISUAL GROUP" self.infor.insert(END, thongtin) ################################### menuBar = Menu(self.parent) self.parent.config(menu=menuBar) fileMenu1 = Menu(menuBar) fileMenu2 = Menu(menuBar) fileMenu3 = Menu(menuBar) fileMenu1.add_command(label="zoom", command=self.zoom) fileMenu1.add_command(label="password", command=self.zoom) fileMenu1.add_command(label="2", command=self.onExit) fileMenu1.add_command(label="3", command=self.onExit) fileMenu2.add_command(label="Exit", command=self.onExit) fileMenu2.add_command(label="1", command=self.onExit) fileMenu2.add_command(label="2", command=self.onExit) fileMenu2.add_command(label="3", command=self.onExit) fileMenu3.add_command(label="help", command=self.file_help) fileMenu3.add_command(label="1", command=self.onExit) fileMenu3.add_command(label="2", command=self.onExit) fileMenu3.add_command(label="3", command=self.onExit) menuBar.add_cascade(label="File", menu=fileMenu1) menuBar.add_cascade(label="Infor", menu=fileMenu2) menuBar.add_cascade(label="Help", menu=fileMenu3) ###### ####### ################################################ function for menu def onScale_H(self, val): v = int(float(val)) self.varHigh.set(v) print(v) #self.varHigh.set(v) def onScale_L(self, val): v = int(float(val)) self.varLow.set(v) print(v) ### def onScale_R_L(self, val): v = int(float(val)) self.varRed_L.set(v) print(v) def onScale_R_H(self, val): v = int(float(val)) self.varRed_H.set(v) print(v) def onScale_G_L(self, val): v = int(float(val)) self.varGreen_L.set(v) print(v) def onScale_G_H(self, val): v = int(float(val)) self.varGreen_H.set(v) print(v) def onScale_B_L(self, val): v = int(float(val)) self.varBlue_L.set(v) print(v) def onScale_B_H(self, val): v = int(float(val)) self.varBlue_H.set(v) print(v) ### def on_Select(self, val): sender = val.widget idx = sender.curselection() value = sender.get(idx) self.varSelect.set(value) def onExit(self): self.quit() def file_help(self): f = open('a.txt', 'w+') #line=f.readline() infor = "1111111111111\n 2222222222222222222\n333333333333333" f.write(infor) line = f.readline() for line in f: print(line) def zoom(self): root.geometry("1500x500") ###################################################### ############ Algorithm def on_Binary(self): if self.var1.get() == True: print("Binary") self.show_Binary() #show window else: print("No_Binary") if hasattr(self, 'ThExtract'): print "dsfsdfds" self.ThBinary.withdraw() else: print "dddddddd" #self.ThBinary.withdraw() def on_Partical(self): if self.var2.get() == True: print("Partical") self.show_Extract() else: print("No_Partical") self.ThExtract.withdraw() def on_Sobel(self): if self.var3.get() == True: print("Sobel") else: print("No_Sobel") def on_Median(self): if self.var4.get() == True: print("Median") else: print("No_Median") def on_LevelAdjust(self): if self.var5.get() == True: print("LevAd") else: print("No_LevAd") def showvideo(self): if camera.resolution == (400, 300): print("ok") cwgt.camera.start_preview() ############################################################################### button to analyse image def Takepic(self): ## take pic button src = Frame(cwgt, width=400, height=300, relief=RAISED, borderwidth=1) src = camera.capture('src.png') analysed = camera.capture('analysed.png') if self.var0.get() == 1: camera.capture("/home/pi/Desktop/New/{0:%Y%m%d-%H%M%S}.png".format( datetime.now())) #'{0:%Y%m%d-%H%M%S}: start.'.format(datetime.now()) #img_abc=PhotoImage(file="src.png") #h=img_abc.width() #w=img_abc.height() #print h,w #cv2.imwrite("src.png",src) #img_abc = cv2.imread("img.png",cv2.IMREAD_COLOR) #cv2.rectangle(img_abc,(50,50),(100,50),(255,0,0),15) #cv2.imwrite("out2.png",img_abc) img_origin = PhotoImage(file="src.png") cwgt2.img = img_origin cwgt2.create_image(200, 200, image=img_origin) h = img_origin.width() w = img_origin.height() #print h,w #px=img[55,55] #img_new=cv2.imread("out2.png") #pix=img_new[2,2] #pix0=img_new[2,2][0] #pix1=img_new[2,2][1] #pix2=img_new[2,2][2] #print pix,pix0,pix1,pix2 #for j in range (0,h): # for i in range (0,w): # if img_new[i,j] #img_new[i,i]=[255,255,255] #pix__=img_new[2,2][0] #print pix__ #cv2.imwrite("out3.png",img_new) #img_x=PhotoImage(file="out3.png") #cwgt2.img=img_x #cwgt2.create_image(200, 200, image=img_x) #if self.var1.get() == True: #src=cv2.imread("src.png") #res=cv2.Canny(src,self.varLow.get(), self.varHigh.get()) #retval,res = cv2.threshold(src, self.varLow.get(), self.varHigh.get(), cv2.THRESH_BINARY) #cv2.imwrite("analysed.png",res) if self.var2.get() == True: min_R = self.varRed_L.get() max_R = self.varRed_H.get() min_G = self.varGreen_L.get() max_G = self.varGreen_H.get() min_B = self.varBlue_L.get() max_B = self.varBlue_H.get() pro_2 = cv2.imread('analysed.png') #hsv = cv2.cvtColor(src,cv2.COLOR_BGR2HSV) lower = np.array([min_B, min_G, min_R], np.uint8) upper = np.array([max_B, max_G, max_R], np.uint8) mask = cv2.inRange(pro_2, lower, upper) analysed = cv2.bitwise_and(pro_2, pro_2, mask=mask) cv2.imwrite("analysed.png", analysed) #cv2.imshow('aaa',src) # #img2=PhotoImage(file="out.png") #cwgt.img2=img2 #cwgt.create_image(200, 200, image=img2) #cv2.imwrite("out3.png",img_new) img_show = PhotoImage(file="analysed.png") cwgt.img = img_show cwgt.create_image(200, 200, image=img_show) if self.var1.get() == True: src = cv2.imread("analysed.png") #analysed=cv2.Canny(src,self.varLow.get(), self.varHigh.get()) retval, res = cv2.threshold(src, self.varLow.get(), self.varHigh.get(), cv2.THRESH_BINARY) cv2.imwrite("analysed.png", res) if self.var5.get() == True: src = cv2.imread("analysed.png") number = 0 for j in range(self.x0_1, self.x1_1): for i in range(self.y0_1, self.y1_1): if src[i, j][0] > 0 and src[i, j][1] > 0 and src[i, j][2] > 0: src[i, j] = [255, 255, 255] number = number + 1 print number if number > 180: tkMessageBox.showinfo(title="OK", message="OK") else: tkMessageBox.showinfo(title="ng", message="ng") cv2.imwrite("analysed.png", src) img_show = PhotoImage(file="analysed.png") cwgt.img = img_show cwgt.create_image(200, 200, image=img_show) #img_show=PhotoImage(file="src.png") #cwgt.img=img_show #cwgt.create_image(200, 200, image=img_show) #retval, after_Binary = cv2.threshold(img, self.varLow.get(), self.varHigh.get(), cv2.THRESH_BINARY) #after_Blurr =cv2.blur(img,(5,5)) #after_MedianBlur=cv2.medianBlur(after_Blurr,5) #cv2.imwrite("out.png",res) #after_Binary=PhotoImage(file="out.png") #cwgt.img=res #cv2.imshow("show",res) #cwgt.create_image(0, 0, image=after_Binary) #cwgt.create_image(0, 0, image=mask) #after_Canny=cv2.Canny(after_MedianBlur,100,200) #findlabel=cv2.findContours(after_Blurr,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #findlabel=cv2.findContours(after_Binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) #im = cv2.imread('new.png') #imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) #ret,thresh = cv2.threshold(imgray,0,255,0) #image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) #img=cv2.drawContours(image,contours,-1,(0,255,0),1) #cv2.imwrite("out.png",after_Binary) #cv2.imwrite("blur.png",after_Blurr) #cv2.imwrite("median blur.png",after_MedianBlur) #cv2.imwrite("Canny.png",after_Canny) #after_Binary=PhotoImage(file="out.png") #cwgt.img=after_Binary #cwgt.create_image(0, 0, image=after_Binary) #else: #cwgt.create_image(0, 0, image=img_origin) #print("xsfd") #print img_origin[100,100][0] #www=img_origin.width() #print www # def on_start(self): print("xsfd") self.showvideo() def off_video(self): #cwgt.frame.destroy() camera.stop_preview() ######## ###################################################################################### show window def show_Binary(self): ## input Thresh_Binary if (hasattr(self, 'ThBinary')): #(self.varHigh.get()> self.varLow.get()) self.ThBinary.deiconify() else: self.ThBinary = Tk() self.ThBinary.geometry("350x100+350+350") self.ThBinary.title("Binary") self.scale_L = Scale(self.ThBinary, from_=255, to=0, command=self.onScale_L) self.scale_L.pack(side=LEFT, padx=10) self.varLow = IntVar() self.label1 = Label(self.ThBinary, text="LOW") self.label1.pack(side=LEFT, padx=0) self.scale_H = Scale(self.ThBinary, from_=255, to=0, command=self.onScale_H) self.scale_H.pack(side=LEFT, padx=20) self.varHigh = IntVar() self.label2 = Label(self.ThBinary, text="HIGH") self.label2.pack(side=LEFT, padx=1) binary = Button(self.ThBinary, text="OK", width=5, background="green", command=self.getdata_Binary) binary.pack(side=LEFT) #binary = Button(self.ThBinary, text="Get_Binary",background="green",command=self.getdata_Binary) #binary.pack() ######## def show_Extract(self): ## input Thresh_Extract if hasattr(self, 'ThExtract'): self.ThExtract.deiconify() else: self.ThExtract = Tk() self.ThExtract.geometry("750x100+350+350") self.ThExtract.title("Extract_Color") ### self.scale_R_L = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_R_L) self.scale_R_L.pack(side=LEFT, padx=10) self.varRed_L = IntVar() self.label_R_L = Label(self.ThExtract, text="Red_L") self.label_R_L.pack(side=LEFT, padx=0) self.scale_R_H = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_R_H) self.scale_R_H.pack(side=LEFT, padx=10) self.varRed_H = IntVar() self.label_R_H = Label(self.ThExtract, text="Red_H") self.label_R_H.pack(side=LEFT, padx=0) ### self.scale_G_L = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_G_L) self.scale_G_L.pack(side=LEFT, padx=10) self.varGreen_L = IntVar() self.label_G_L = Label(self.ThExtract, text="Green_L") self.label_G_L.pack(side=LEFT, padx=0) self.scale_G_H = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_G_H) self.scale_G_H.pack(side=LEFT, padx=10) self.varGreen_H = IntVar() self.label_G_H = Label(self.ThExtract, text="Green_H") self.label_G_H.pack(side=LEFT, padx=0) ### self.scale_B_L = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_B_L) self.scale_B_L.pack(side=LEFT, padx=10) self.varBlue_L = IntVar() self.label_B_L = Label(self.ThExtract, text="Blue_L") self.label_B_L.pack(side=LEFT, padx=0) self.scale_B_H = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_B_H) self.scale_B_H.pack(side=LEFT, padx=10) self.varBlue_H = IntVar() self.label_G_H = Label(self.ThExtract, text="Blue_H") self.label_G_H.pack(side=LEFT, padx=0) ### Extract = Button(self.ThExtract, text="OK", width=5, background="green", command=self.getdata_Extract) Extract.pack(side=LEFT) ########## def show_Partical(self): print("") #self.ThBinary=Tk() #self.ThBinary.geometry("200x70+350+350") #self.ThBinary.title("Binary") #self.scale_L = Scale(self.ThBinary, from_=0, to=255, command=self.onScale_L) #self.scale_L.pack(side=LEFT, padx=10) #self.varLow = IntVar() #self.label1 = Label(self.ThBinary,text="LOW") #self.label1.pack(side=LEFT,padx=0) #self.scale_H = Scale(self.ThBinary, from_=0, to=255, command=self.onScale_H) #self.scale_H.pack(side=LEFT, padx=20) #self.varHigh = IntVar() #self.label2 = Label(self.ThBinary, text="HIGH") #self.label2.pack(side=LEFT,padx=1) ######### def confirm_SaveData(self): ##input password self.master = Tk() self.master.title("pass") self.master.geometry("200x70+350+350") self.content = StringVar() self.entry = Entry(self.master, text="000", textvariable=self.content) self.entry.pack() b = Button(self.master, text="get", width=10, command=self.SaveData) b.pack() text123 = self.content.get() self.content.set(text123) print(self.content.get()) ############ def reset_Area(self): self.infor_Area1.delete('1.0', END) self.infor_Area2.delete('1.0', END) self.infor_Area3.delete('1.0', END) self.infor_Area4.delete('1.0', END) def set_Area(self): self.text1 = self.infor_Area1.get('1.0', END) self.x0_1 = int(self.text1[0] + self.text1[1] + self.text1[2]) self.y0_1 = int(self.text1[4] + self.text1[5] + self.text1[6]) self.x1_1 = int(self.text1[8] + self.text1[9] + self.text1[10]) self.y1_1 = int(self.text1[12] + self.text1[13] + self.text1[14]) ######### def show_Area(self): #text1=self.infor_Area1.get('1.0',END) #x0_1=int(text1[0]+text1[1]) #y0_1=int(text1[3]+text1[4]) #x1_1=int(text1[6]+text1[7]) #y1_1=int(text1[9]+text1[10]) #text2=self.infor_Area2.get('1.0',END) #x0_2=int(text2[0]+text2[1]) #y0_2=int(text2[3]+text2[4]) #x1_2=int(text2[6]+text2[7]) #y1_2=int(text2[9]+text2[10]) #text3=self.infor_Area3.get('1.0',END) #x0_3=int(text3[0]+text3[1]) #y0_3=int(text3[3]+text3[4]) #x1_3=int(text3[6]+text3[7]) #y1_3=int(text3[9]+text3[10]) #text4=self.infor_Area4.get('1.0',END) #x0_4=int(text4[0]+text4[1]) #y0_4=int(text4[3]+text4[4]) #x1_4=int(text4[6]+text4[7]) #y1_4=int(text4[9]+text4[10]) img = cv2.imread("src.png", cv2.IMREAD_COLOR) #print self.x0_1 cv2.rectangle(img, (self.x0_1, self.y0_1), (self.x1_1, self.y1_1), (255, 0, 0), 2) #cv2.rectangle(img,(x0_2,y0_2),(x1_2,y1_2),(0,255,0),2) #cv2.rectangle(img,(x0_3,y0_3),(x1_3,y1_3),(0,0,255),2) #cv2.rectangle(img,(x0_4,y0_4),(x1_4,y1_4),(255,255,0),2) img_show_Area = img #img_show_Area=cv2.rectangle(img,(x0_1,y0_1),(x1_1,y1_1),(255,0,0),2) cv2.imwrite("show_Area.png", img_show_Area) img_show = PhotoImage(file="show_Area.png") cwgt2.img = img_show cwgt2.create_image(200, 200, image=img_show) #cv2.rectangle(img,(50,250),(100,500),(255,0,0),15) def AdjustBinary(self): if self.var1.get() == True: self.ThBinary.withdraw() self.ThBinary.deiconify() def AdjustExtract(self): if self.var2.get() == True: self.ThExtract.withdraw() self.ThExtract.deiconify() ############################################################################################ get data def SaveData(self): ## get password button print(self.entry.get()) self.set_Area() if self.entry.get() == "1111": self.master.destroy() tkMessageBox.showinfo(title="Save", message="SaveData success !!") print "Save" self.inforData_binary = "Binary : (" + self.text_binary + ")" self.inforData_Extract = "Extract : " + self.text_Extract self.inforData_Area1 = "Area1 : " + self.text1 if self.var1.get() == 1: data1 = "1" else: data1 = "0" ## if self.var2.get() == 1: data2 = "1" else: data2 = "0" ## if self.var3.get() == 1: data3 = "1" else: data3 = "0" ## if self.var4.get() == 1: data4 = "1" else: data4 = "0" ## if self.var5.get() == 1: data5 = "1" else: data5 = "0" ## self.SumData = (data1 + data2 + data3 + data4 + data5) print self.SumData self.inforData = self.SumData + "\n" + self.inforData_binary + "\n" + self.inforData_Extract + "\n" + self.inforData_Area1 print self.inforData #if self.var1.get()==1 : f = open('a.txt', 'w+') f.write(self.inforData) else: tkMessageBox.showinfo(title="fail", message="again") #### def getdata_Binary(self): value_low = str(self.varLow.get()) value_high = str(self.varHigh.get()) if self.varLow.get() > 99: min_binary = str(value_low) else: if self.varLow.get() > 9: min_binary = str("0" + value_low) else: min_binary = str("00" + value_low) if self.varHigh.get() > 99: max_binary = str(value_high) else: if self.varHigh.get() > 9: max_binary = str("0" + value_high) else: max_binary = str("00" + value_high) self.text_binary = str(min_binary + "," + max_binary) #if hasattr(self,'infor'): # self.infor.destroy() #if hasattr(self,'infor_Alg1'): # self.infor_Alg1.destroy() if self.varHigh.get() > self.varLow.get(): self.infor_Alg1.delete('1.0', END) self.infor_Alg1.insert(END, self.text_binary) #self.ThBinary.destroy() self.ThBinary.withdraw() else: tkMessageBox.showinfo(title="fail", message="again") #### def getdata_Extract(self): value_R_L = str(self.varRed_L.get()) value_R_H = str(self.varRed_H.get()) value_G_L = str(self.varGreen_L.get()) value_G_H = str(self.varGreen_H.get()) value_B_L = str(self.varBlue_L.get()) value_B_H = str(self.varBlue_H.get()) ## if self.varRed_L.get() > 99: min_R = str(value_R_L) else: if self.varRed_L.get() > 9: min_R = str("0" + value_R_L) else: min_R = str("00" + value_R_L) ## if self.varRed_H.get() > 99: max_R = str(value_R_H) else: if self.varRed_H.get() > 9: max_R = str("0" + value_R_H) else: max_R = str("00" + value_R_H) ### if self.varGreen_L.get() > 99: min_G = str(value_G_L) else: if self.varGreen_L.get() > 9: min_G = str("0" + value_G_L) else: min_G = str("00" + value_G_L) ## if self.varGreen_H.get() > 99: max_G = str(value_G_H) else: if self.varGreen_H.get() > 9: max_G = str("0" + value_G_H) else: max_G = str("00" + value_G_H) ### if self.varBlue_L.get() > 99: min_B = str(value_B_L) else: if self.varBlue_L.get() > 9: min_B = str("0" + value_B_L) else: min_B = str("00" + value_B_L) ## if self.varBlue_H.get() > 99: max_B = str(value_B_H) else: if self.varBlue_H.get() > 9: max_B = str("0" + value_B_H) else: max_B = str("00" + value_B_H) ### self.text_Extract = str("R(" + min_R + "," + max_R + ")" + "G(" + min_G + "," + max_G + ")" + "B(" + min_B + "," + max_B + ")") #if hasattr(self,'infor'): # self.infor.destroy() if ((self.varRed_H.get() > self.varRed_L.get()) and (self.varGreen_H.get() > self.varGreen_L.get()) and (self.varBlue_H.get() > self.varBlue_L.get())): self.infor_Alg2.delete('1.0', END) self.infor_Alg2.insert(END, self.text_Extract) self.ThExtract.withdraw() else: tkMessageBox.showinfo(title="fail", message="again") def confirm_LoadData(self): self.master = Tk() self.master.title("pass") self.master.geometry("200x70+350+350") self.content = StringVar() self.entry = Entry(self.master, text="000", textvariable=self.content) self.entry.pack() b = Button(self.master, text="get", width=10, command=self.getdata_Load) b.pack() text123 = self.content.get() self.content.set(text123) def getdata_Load(self): if self.entry.get() == "1111": self.master.destroy() tkMessageBox.showinfo(title="Load", message="LoadData success !!") self.LoadData() else: tkMessageBox.showinfo(title="fail", message="again") def LoadData(self): print "Load" f = open('a.txt', 'r') self.SumData = f.readline() load_binary = f.readline() load_extract = f.readline() load_area1 = f.readline() #self.ThBinary.deiconify() text_binary = (load_binary[10] + load_binary[11] + load_binary[12] + load_binary[13] + load_binary[14] + load_binary[15] + load_binary[16]) text_extract = ( load_extract[10] + load_extract[11] + load_extract[12] + load_extract[13] + load_extract[14] + load_extract[15] + load_extract[16] + load_extract[17] + load_extract[18] + load_extract[19] + load_extract[20] + load_extract[21] + load_extract[22] + load_extract[23] + load_extract[24] + load_extract[25] + load_extract[26] + load_extract[27] + load_extract[28] + load_extract[29] + load_extract[30] + load_extract[31] + load_extract[32] + load_extract[33] + load_extract[34] + load_extract[35] + load_extract[36] + load_extract[37] + load_extract[38] + load_extract[39]) text_area1 = (load_area1[8] + load_area1[9] + load_area1[10] + load_area1[11] + load_area1[12] + load_area1[13] + load_area1[14] + load_area1[15] + load_area1[16] + load_area1[17] + load_area1[18] + load_area1[19] + load_area1[20] + load_area1[21] + load_area1[22]) value_low_binary = int(load_binary[10] + load_binary[11] + load_binary[12]) value_high_binary = int(load_binary[14] + load_binary[15] + load_binary[16]) #### value_low_red = int(load_extract[12] + load_extract[13] + load_extract[14]) value_high_red = int(load_extract[16] + load_extract[17] + load_extract[18]) value_low_green = int(load_extract[22] + load_extract[23] + load_extract[24]) value_high_green = int(load_extract[26] + load_extract[27] + load_extract[28]) value_low_blue = int(load_extract[32] + load_extract[33] + load_extract[34]) value_high_blue = int(load_extract[36] + load_extract[37] + load_extract[38]) #### value_area1_x0 = int(load_area1[8] + load_area1[9] + load_area1[10]) value_area1_y0 = int(load_area1[12] + load_area1[13] + load_area1[14]) value_area1_x1 = int(load_area1[16] + load_area1[17] + load_area1[18]) value_area1_y1 = int(load_area1[20] + load_area1[21] + load_area1[22]) ####### self.x0_1 = value_area1_x0 self.y0_1 = value_area1_y0 self.x1_1 = value_area1_x1 self.y1_1 = value_area1_y1 ####### self.varHigh = IntVar() self.varLow = IntVar() self.varRed_L = IntVar() self.varRed_H = IntVar() self.varGreen_L = IntVar() self.varGreen_H = IntVar() self.varBlue_L = IntVar() self.varBlue_H = IntVar() self.varLow.set(value_low_binary) self.varHigh.set(value_high_binary) self.varRed_L.set(value_low_red) self.varRed_H.set(value_high_red) self.varGreen_L.set(value_low_green) self.varGreen_H.set(value_high_green) self.varBlue_L.set(value_low_blue) self.varBlue_H.set(value_high_blue) self.text_binary = text_binary self.text_Extract = text_extract self.text_area1 = text_area1 self.infor_Alg1.delete('1.0', END) self.infor_Alg1.insert(END, self.text_binary) self.infor_Alg2.delete('1.0', END) self.infor_Alg2.insert(END, self.text_Extract) self.infor_Area1.delete('1.0', END) self.infor_Area1.insert(END, self.text_area1) if self.SumData[0] == "1": self.var1.set(1) else: self.var1.set(0) if self.SumData[1] == "1": self.var2.set(1) else: self.var2.set(0) if self.SumData[2] == "1": self.var3.set(1) else: self.var3.set(0) if self.SumData[3] == "1": self.var4.set(1) else: self.var4.set(0) if self.SumData[4] == "1": self.var5.set(1) else: self.var5.set(0) self.set_Area() #self.inforData_binary="Binary : (" + self.text_binary + ")" #self.inforData_Extract="Extract : " + self.text_Extract #self.inforData=self.inforData_binary + "\n" + self.inforData_Extract #print self.inforData def Area(self): print "asasas"
class TkAdmin(TkWindow, RPCComponent): """ Development graphical user interface for cape systems. """ unique = True directory_name = "TkAdmin" # TODO: # * Clean up user interface # * Develop interaction elements for all primitives def __init__(self): self.nodelist = {} self.messages = [] self.title = "cape TkAdmin - [%s]" % identity.SystemName super(TkAdmin, self).__init__() self.Configuration['fixsender'] = False self.Configuration['autoclear'] = True self.Configuration['autoscan'] = True self.Configuration['showresponses'] = False self.autoscan.set(self.Configuration['autoscan']) self.fixsender.set(self.Configuration['fixsender']) self.autoclear.set(self.Configuration['autoclear']) self.showresponses.set(self.Configuration['showresponses']) # The invisibleroot is necessary to avoid stopping Tk's eventloop # upon closure of tkWindows. # TODO: Good idea to already activate here? # TODO: Don't we need a central InvisibleWindow thats kept inbetween destruction of tkinterfaces? self._invisibleRoot = tkInvisibleWindow().activate() # self.clearInput = tkinter.BooleanVar() self.MapViewer = None def __on_ButtonClear_Press(self, Event=None): self.clearEntry() def __on_ButtonTransmit_Release(self, Event=None): self.usertransmit() def __on_EntryInput_Enter__C(self, Event=None): self.usertransmit() def __on_ButtonClearResponses_Press(self, Event=None): self.__TextResponses.clear() def showMessage(self, ev=None): msglb = self.__MessageLog._listbox sel = msglb.curselection() if len(sel) > 1: self.logwarning("Multiple messages selected to display. Can't.") msg = self.messages[int(sel[0])] msgdialog = TkMessageDialog(self.window, msg) def composeMessage(self, name="", node="", sender=None): if not sender: sender = self.name msg = Message(sender=sender, recipientnode=node, recipient=name) msgdialog = TkMessageDialog(self.window, msg, onclosecallback=self.transmit) def clearEntry(self): self.__EntryInput.delete(0, END) self.__FrameInput['bg'] = self.defaultcolors['bg'] # self.__EntryInput['fg'] = self.defaultcolors['fg'] def scanregistry(self, node=""): msg = Message(sender=self.name, recipientnode=node, recipient=self.systemregistry, func="listRegisteredComponents", arg=None ) self.transmit(msg) msg = Message(sender=self.name, recipientnode=node, recipient=self.systemregistry, func="listRegisteredTemplates", arg=None ) self.transmit(msg) def scangateways(self): msg = Message(sender=self.name, recipient=self.systemdispatcher, func="listgateways" ) self.transmit(msg) def dumpnodelist(self): from pprint import pprint pprint(self.nodelist) def scancomponent(self, name, node=""): self.logdebug("Scanning component '%s'." % name) msg = Message(sender=self.name, recipientnode=node, recipient=name, func="getComponentInfo", arg=None) self.transmit(msg) def createcomponent(self, name, node=""): self.loginfo("Creating component from template '%s'." % name) msg = Message(sender=self.name, recipientnode=node, recipient=self.systemregistry, func="createComponent", arg={'templatename': name}) self.transmit(msg) def copystring(self, name): self.window.clipboard_clear() self.window.clipboard_append(name) def callComplexMethod(self, componentname, node, func): self.loginfo("Creating function dialog for '%s'@'%s'." % (func, componentname)) componentlist = self.nodelist[node]['componentlist'] component = componentlist[componentname] componentinfo = component["info"] methods = componentinfo["methods"] methodregister = methods[func] InputDialog = TkRPCArgDialog(self.window, self.callComplexMethodFinal, componentname, node, func, methodregister) def callComplexMethodFinal(self, name, node, func, args): self.loginfo("Finally calling func '%s'@'%s' with args '%s'" % (func, name, args)) msg = Message(sender=self.name, recipientnode=node, recipient=name, func=func, arg=args) self.transmit(msg) def callSimpleMethod(self, name, node, func): self.loginfo("Calling '%s'@'%s'." % (func, name)) msg = Message(sender=self.name, recipient=name, recipientnode=node, func=func, arg=None) self.transmit(msg) def transmit(self, msg): self.logdebug("Transmitting Message '%s'" % msg) self.recordMessage(msg) self.send(msg, "outbox") def recordMessage(self, msg): self.messages.append(msg) self.updateMessageLog() def updateMessageLog(self): loglistbox = self.__MessageLog._listbox loglistbox.delete(0, END) # GAH. Addition should be sufficient. CHANGE! for msg in sorted(self.messages, key=lambda msg: msg.timestamp): loglistbox.insert(END, msg) if msg.recipient == self.name: loglistbox.itemconfig(END, bg='green', fg='black') else: loglistbox.itemconfig(END, bg='red', fg='black') def editidentity(self): self.logerror("Not implemented. Here is a dump of this node's identity:") self.loginfo(identity.Systemidentity) self.loginfo(identity.SystemUUID) def usertransmit(self): def send(msg): if self.fixsender.get() and msg.sender != self.name: self.loginfo("Fixing sender to '%s'." % self.name) msg.sender = self.name self.loginfo("Transmitting message '%s'" % msg) self.transmit(msg) self.__FrameInput['bg'] = self.defaultcolors['bg'] message = self.__EntryInput.get() if len(message) <= 1: self.logdebug("No message to send entered.") return try: msg = jsonpickle.decode(message) send(msg) except ValueError as e: errmsg = 'Invalid JSON:\n%s' % e self.logerror(e) if "column" in errmsg: col = errmsg.split("(char ")[1].split(")")[0] col = col.split(" -")[0] self.__EntryInput.icursor(col) self.logwarning(errmsg) self.__FrameInput['bg'] = 'red' # self.__FrameInput['fg'] = 'yellow' messagebox.showinfo("Transmit failed!", errmsg) if self.autoclear.get(): self.clearEntry() def rebuildNodeMenu(self): NodeMenu = self.__MenuNodes NodeMenu.delete(4, END) for node in self.nodelist: NodeMenu.add_cascade(menu=self.nodelist[node]['menu'], label=node if node != "" else "LOCAL") def __handleNewNode(self, node): if node not in self.nodelist: self.loginfo("New node appeared! Hmm.") else: self.loginfo("Node rescanned.") print self.__MenuNodes componentlist = {} ComponentMenu = Menu(self.__MenuNodes) ComponentMenu.add_command(label="Scan", command=lambda node=node: self.scanregistry(node)) ComponentMenu.add_command(label="Copy Name", command=lambda node=node: self.copystring(node)) ComponentMenu.add_separator() nodeinfo = {'componentlist': componentlist, 'menu': ComponentMenu} self.nodelist[node] = nodeinfo def handleResponse(self, msg): self.recordMessage(msg) def __addComponents(components, node): componentlist = self.nodelist[node]['componentlist'] ComponentMenu = self.nodelist[node]['menu'] for comp in components: self.loginfo("Adding component '%s@%s'" % (comp, node)) if self.autoscan.get() and comp not in componentlist: self.scancomponent(comp, node) FuncMenu = Menu(ComponentMenu) FuncMenu.add_command(label="Scan", command=lambda (name,node)=(comp, node): self.scancomponent(name, node)) FuncMenu.add_command(label="Copy Name", command=lambda name=comp: self.copystring(name)) FuncMenu.add_command(label="Compose...", command=lambda (name,node)=(comp,node): self.composeMessage(name, node)) FuncMenu.add_separator() FuncMenu = Menu(ComponentMenu) ComponentMenu.add_cascade(label=comp, menu=FuncMenu) componentlist[comp] = {'menu': FuncMenu} def __handleListRegisteredTemplates(msg): MenuTemplates = self.__MenuTemplates MenuTemplates.delete(0, END) for template in sorted(msg.arg): node = '' MenuTemplates.add_command(label=template, command=lambda (name,node)=(template, node): self.createcomponent(name, node)) self.__MenuTemplates = MenuTemplates def __handleComponentInfo(msg): node = msg.sendernode if node not in self.nodelist: self.logerror('Node unknown') else: componentlist = self.nodelist[node]['componentlist'] if msg.sender not in componentlist: if self.autoscan.get(): self.loginfo("Unknown component '%s'. Rescanning registry." % msg.senderid) self.scanregistry(node) else: self.loginfo("Unknown component's ('%s') info encountered. Ignoring.") else: self.logdebug("Got a component's ('%s') RPC info. Parsing." % msg.sender) if componentlist[msg.sender] == 'scanned': self.logdebug("Scan from a self-created component returned.") component = msg.sender result = msg.arg componentlist[component]["info"] = result FuncMenu = componentlist[component]["menu"] FuncMenu.delete(5, END) mr = result['methods'] for meth in mr: self.logdebug("Got method '%s'." % meth) if len(mr[meth]['args']) > 0: FuncMenu.add_command(label=meth, command=lambda (node, name, meth)=(node, component, meth): self.callComplexMethod(name, node, meth)) else: FuncMenu.add_command(label=meth, command=lambda (node, name, meth)=(node, component, meth): self.callSimpleMethod(name, node, meth)) def __handleCreateComponent(msg): node = msg.sendernode component = msg.arg if node not in self.nodelist: self.__handleNewNode(node) componentlist = self.nodelist[node]['componentlist'] __addComponents([component], node) def __handleRegisteredComponents(msg): node = msg.sendernode self.loginfo("Got a list of registered components from '%s'. Parsing." % node) self.__handleNewNode(node) # Schema nodelist: # {nodeUUID: {'componentlist': componentlist, 'menu': ComponentMenu} # Schema componentlist: # {componentname: {'funclist': funclist, 'menu': funcmenu} # Schema funclist: # {func: menu} components = msg.arg __addComponents(components, node) self.rebuildNodeMenu() def __handleGatewayList(msg): self.loginfo("Received a list of connected nodes.") for node in msg.arg: self.__handleNewNode(node) if self.autoscan.get(): self.scanregistry(node) self.rebuildNodeMenu() if isinstance(msg, Message): if msg.sender == self.systemdispatcher: if msg.func == "listgateways": __handleGatewayList(msg) if msg.sender == self.systemregistry and not msg.error: if msg.func == "createComponent": __handleCreateComponent(msg) if msg.func == "listRegisteredComponents": __handleRegisteredComponents(msg) elif msg.func == "listRegisteredTemplates": __handleListRegisteredTemplates(msg) if msg.func == "getComponentInfo": if not msg.error: __handleComponentInfo(msg) if msg.func in ("renderArea", "renderCoord"): if not msg.error: if self.MapViewer: self.MapViewer.drawMap(msg.arg) else: self.MapViewer = TkMapDialog(msg.arg) self.MapViewer.activate() def scanlinetest(self): polygon = [[50, 5], [100, 270], [150, 270], [220, 30]] ScanlineTestDialog = TkScanlineTestDialog(polygon) def quit(self): self.logcritical("Shutting down hard.") try: import cherrypy self.loginfo("WebGate running. Stopping cherrypy first.") cherrypy.engine.stop() except ImportError: self.loginfo("WebGate not running. Not killing cherrypy.") Scheduler.scheduler.run.stop() def setupWindow(self): self.logdebug("Setting up TkAdmin GUI") Pmw.initialise(self.window) self.window.title(self.title) ### Menu ### self.__FrameMenu = Frame(self.window) self.__FrameMenu.pack(anchor='n', side='top') self.__Menu = Menu(self.window) self.__MenuFile = Menu(self.__Menu) self.__MenuEdit = Menu(self.__Menu) self.__MenuMessage = Menu(self.__Menu) self.__MenuSettings = Menu(self.__Menu) self.__MenuSystem = Menu(self.__Menu) self.__Menu.add_cascade(menu=self.__MenuFile, label="File") self.__Menu.add_cascade(menu=self.__MenuEdit, label="Edit") self.__Menu.add_cascade(menu=self.__MenuMessage, label="Message") self.__Menu.add_cascade(menu=self.__MenuSettings, label="Settings") self.__Menu.add_cascade(menu=self.__MenuSystem, label="System") self.window.config(menu=self.__Menu) self.__MenuFile.add_command(label="Update Message Log", command=self.updateMessageLog) self.__MenuFile.add_command(label="Quit", command=self.quit) self.autoscan = BooleanVar() self.fixsender = BooleanVar() self.autoclear = BooleanVar() self.showresponses = BooleanVar() self.__MenuMessage.add_command(label="View", command=self.showMessage) self.__MenuMessage.add_command(label="Compose New", command=self.composeMessage) self.__MenuSettings.add_checkbutton(label="Fix sender", onvalue=True, offvalue=False, variable=self.fixsender) self.__MenuSettings.add_checkbutton(label="Autoscan", onvalue=True, offvalue=False, variable=self.autoscan) self.__MenuSettings.add_checkbutton(label="Autoclear", onvalue=True, offvalue=False, variable=self.autoclear) self.__MenuSettings.add_checkbutton(label="Show responses", onvalue=True, offvalue=False, variable=self.showresponses) self.__MenuSystem.add_command(label="View/Edit identity", command=self.editidentity) self.__MenuTemplates = Menu(self.__MenuSystem) self.__MenuSystem.add_cascade(label='Create Component', menu=self.__MenuTemplates) self.__MenuNodes = Menu(self.__Menu) self.__MenuNodes.add_command(label="Update connected nodes", command=self.scangateways) self.__MenuNodes.add_command(label="Scan Local", command=self.scanregistry) self.__MenuNodes.add_command(label="Dump Nodelist", command=self.dumpnodelist) self.__MenuNodes.add_separator() self.__Menu.add_cascade(menu=self.__MenuNodes, label="Nodes") ### /Menu ### ### Output ### self.__FrameOutput = Frame(self.window) self.__FrameOutput.pack(side='top', fill='both', expand='yes') self.__NotebookOutput = Pmw.NoteBook(self.__FrameOutput) self.__NotebookOutput.pack(fill='both', expand=1) self.__PageMessages = self.__NotebookOutput.add('Messages') self.__PageMap = self.__NotebookOutput.add('Map') self.__PageResponses = self.__NotebookOutput.add('Responses') #self.__PageLog = self.__NotebookOutput.add('Log') # Needs a loggercomponent and revised logging first self.__MessageLog = Pmw.ScrolledListBox(self.__PageMessages) self.__MessageLog.pack(expand='yes', fill='both') self.__NotebookOutput.tab('Messages').focus_set() self.__FrameInput = Frame(self.window, borderwidth=2) self.__FrameInput.pack(anchor='s', expand='no', fill='x', side='top') self.__FrameStatusbar = Frame(self.window, relief='raised') self.__FrameStatusbar.pack(anchor='sw', side='top') # ,fill='x' self.__LabelStatus = Label(self.__FrameStatusbar, text='Ready.') self.__LabelStatus.pack(anchor='w', expand='yes', side='top') # ,fill='both' self.__FrameResponses = Frame(self.__PageResponses, background="yellow") self.__FrameResponsesHeader = Frame(self.__FrameResponses) self.__LabelResponses = Label(self.__FrameResponsesHeader, text='Responses') self.__LabelResponses.pack(anchor='e', side='right', fill='x') self.__ButtonClearResponses = Button(self.__FrameResponsesHeader, text='Clear') self.__ButtonClearResponses.pack(anchor='w', side='left') self.__FrameResponsesHeader.pack(anchor='n', fill='x', side=TOP) self.__TextResponses = Pmw.ScrolledText(self.__FrameResponses) self.__TextResponses.pack(expand=1, fill='both', side=BOTTOM) self.__FrameResponses.pack(expand=1, fill="both") #self.__FrameLog = Frame(self.__PageLog) #self.__FrameLog.pack(side='left', expand=1, fill="both") #self.__FrameLogHeader = Frame(self.__FrameLog) #self.__FrameLogHeader.pack(anchor='n',expand='yes', fill='x', side='top') #self.__LabelLog = Label(self.__FrameLogHeader,text='Log') #self.__LabelLog.pack(anchor='e',side='right', fill='both') #self.__ButtonClearLog = Button(self.__FrameLogHeader, text='Clear') #self.__ButtonClearLog.pack(anchor='w',side='left') #self.__TextLog = Pmw.ScrolledText(self.__FrameLog) #self.__TextLog.pack(expand=1,fill='both') self.__MapCanvas = Canvas(self.__PageMap) self.__MapCanvas.pack(expand=1, fill='both') self.__NotebookOutput.setnaturalsize() ### /Output ### ### Input ### self.__FrameInputEntry = Frame(self.__FrameInput) self.__EntryInput = Entry(self.__FrameInput) self.__EntryInput.pack(expand='yes', fill='both', side='left') self.__FrameTransmitButton = Frame(self.__FrameInput) self.__FrameTransmitButton.pack(anchor='w', side='left') self.__ButtonTransmit = Button(self.__FrameTransmitButton , text='Transmit') self.__ButtonTransmit.pack(expand='yes', fill='both', side='top') self.__FrameClearButton = Frame(self.__FrameInput) self.__FrameClearButton.pack(anchor='w', side='left') self.__ButtonClear = Button(self.__FrameClearButton, text='Clear') self.__ButtonClear.pack(expand='yes', fill='both', side='top') self.__FrameInputEntry.pack(side='left') ### /Input ### ### Bindings ### self.__MessageLog._listbox.bind("<Double-Button-1>", self.showMessage) self.__ButtonClearResponses.bind('<ButtonRelease-1>' , self.__on_ButtonClearResponses_Press) self.__ButtonTransmit.bind('<ButtonRelease-1>' , self.__on_ButtonTransmit_Release) self.__ButtonClear.bind('<ButtonPress-1>', self.__on_ButtonClear_Press) self.__EntryInput.bind('<Control-Return>', self.__on_EntryInput_Enter__C) self.defaultcolors = {'bg': self.window['bg'], 'fg': self.__EntryInput['fg']} def main(self): """ Main loop. Stub method, reimplement with your own functionality. Must regularly call self.tkupdate() to ensure tk event processing happens. """ if self.autoscan.get(): self.loginfo("Local autoscan initiated.") self.scanregistry() while not self.isDestroyed(): yield 1 if self.dataReady("control"): msg = self.recv("control") if isinstance(msg, producerFinished) or isinstance(msg, shutdownMicroprocess): self.send(msg, "signal") self.window.destroy() if self.dataReady("inbox"): msg = self.recv("inbox") self.logdebug("Received message '%s'" % msg) self.handleRPC(msg) if self.showresponses.get(): self.__TextResponses.insert(END, "%s\n" % msg) self.tkupdate()
class Plotter(object): def __init__(self, fig): self._scope = None self.fig = fig self.plt = fig.add_subplot(111) self.ch1, self.ch2 = self.plt.plot([], [], [], []) self.pool = ThreadPool() self.ch1b = BooleanVar() self.ch1b.set(True) self.ch2b = BooleanVar() self.ch2b.set(True) self._fft = BooleanVar() self._fft.set(False) self._xy = BooleanVar() self._xy.set(False) self._USB_voltage = None @property def scope(self): return self._scope @scope.setter def scope(self, port): self._scope = DPScope(port) @property def both_channels(self): return self.ch1b.get() and self.ch2b.get() @property def xy(self): return self._xy.get() @property def fft(self): return self._fft.get() @property def USB_voltage(self): if not self._USB_voltage: self.scope.adcon_from(0) self.scope.set_dac(0, 3000) self.scope.set_dac(1, 3000) real_dac = sum(self.scope.measure_offset()) / 2 self.scope.set_dac(0, 0) self.scope.set_dac(1, 0) nominal_dac = 3 * (1023 / 5.) self._USB_voltage = 5. * (nominal_dac / real_dac) return self._USB_voltage def to_volt(self, adc, gain=1, pregain=1): multiplier = (self.USB_voltage/5.) * (20./256) * pregain * gain return adc * multiplier def read_volt(self): return map(self.to_volt, self.scope.read_adc()) def poll(self): self.arm() self.plot(*self.parse(self.read())) self.scope.abort() def read(self, nofb=205): data = None while not data: data = self.scope.read_back(nofb) return data[1:] # need first byte? def parse(self, data): ch1 = data ch2 = [] if self.both_channels: ch1, ch2 = channels(data) if self.fft: ch1 = fft(ch1) ch2 = fft(ch2) if self.xy: return ch1, ch2, [], [] else: return [], ch1, [], ch2 def reader(self, nofb=205): while True: yield self.read(nofb) def arm(self): if self.both_channels: self.scope.arm(0) else: self.scope.arm_fft(0, self.ch1b.get() or self.ch2b.get()*2) def plot(self, x1=[], y1=[], x2=[], y2=[]): if len(y1) and not len(x1): x1 = range(len(y1)) if len(y2) and not len(x2): x2 = range(len(y2)) self.ch1.set_data(x1, y1) self.ch2.set_data(x2, y2) self.plt.relim() self.plt.autoscale_view() self.fig.canvas.draw()
class mSim(Frame): def __init__(self, parent): self.serialStatus = False #create variables self.startmotor = BooleanVar() self.logstate = BooleanVar() self.loggedData = [] self.throttlevar = StringVar() self.throttleval = IntVar() #default values self.throttlevar.set("0%") self.throttleval.set(0) #base frame init Frame.__init__(self, parent) self.parent = parent self.initUI() self.centerWindow() self.PERIOD_LENGTH_Log = 100 #milliseconds self.PERIOD_LENGTH_Scan = 1000 #milliseconds self.PERIOD_LENGTH_Refresh = 300 #milliseconds self.parent.after(0, self.runScan) self.parent.after(0, self.runLog) self.parent.after(0, self.runRefresh) def runScan(self): #serial port scanning function """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/tty[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/tty.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass menu = self.drop["menu"] menu.delete(0, "end") menu.add_command(label="None", command=lambda value="None": self.selected_s_Port.set(value)) for string in result: menu.add_command(label=string, command=lambda value=string: self.selected_s_Port.set(value)) self.parent.after(self.PERIOD_LENGTH_Scan, self.runScan) def runLog(self): #this will probably not work since you're not appending to if (self.logstate.get() == True) and (self.serialStatus == True): #logging data data = dict(zip(*[self.SC.dict.keys(), zip(*self.SC.dict.values())[-1]])) if 'l' not in locals(): # a dictionary with a deque of the recent data for each message type -Austin l = [] if self.loggedData == []: #if empty add titles l=[data.keys()] data = data.values() self.loggedData.append(data) self.parent.after(self.PERIOD_LENGTH_Log, self.runLog) def runRefresh(self): #Refresh figures function self.a.clear() self.b.clear() self.c.clear() self.d.clear() if not self.serialStatus: #TODO: Put SerialComm data buffer here v . Timestamps (from python?) on x axis, values on y-axis #Helpful Info: plot([xvals],[yvals]) self.a.plot([0],[0]) self.b.plot([0],[0]) self.c.plot([0],[0]) self.d.plot([0],[0]) else: self.SC.processData(5) # This param is the number of bytes to try for a message -Austin timestamps = [val / 1000.0 if val != None else val for val in self.SC.dict['Timestamp']] self.a.plot(timestamps, self.SC.dict['Thrust']) self.b.plot(timestamps, self.SC.dict['Rot Speed']) self.c.plot(timestamps, self.SC.dict['Current']) self.d.plot(timestamps, self.SC.dict['Voltage']) #set labels for graphs (could make automatic later) self.a.set_xlabel('time (s)') self.a.set_ylabel('Thrust (N)') self.b.set_xlabel('time (s)') self.b.set_ylabel('RPM') self.c.set_xlabel('time (s)') self.c.set_ylabel('Current (A)') self.d.set_xlabel('time (s)') self.d.set_ylabel('Voltage (V)') #try drawing the canvas try: self.canvas.draw() except: pass #just ignore it, you'll do better next time self.parent.after(self.PERIOD_LENGTH_Refresh, self.runRefresh) def centerWindow(self): w = 900 #eh, who needs scaling anyways h = 600 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)) def initUI(self): #Parent Frame self.parent.title("Test Stand Control Panel") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) # Frame 1 (top) frame1 = Frame(self) frame1.pack(fill=X, expand=1) #Start motor button startButton = Button(frame1, text="Start Motor", command=self.startMotor) startButton.pack(side=LEFT, padx=5, pady=5) #Throttle slider lbl1 = Label(frame1, text="Throttle (0-100):", width=14) lbl1.pack(side=LEFT, padx=5, pady=5) self.scale = Scale(frame1, from_=0, to=100, command=self.onScaleThrottle) self.scale.pack(side=LEFT, padx=15) self.label = Label(frame1, text="throttle", textvariable=self.throttlevar, width=5) self.label.pack(side=LEFT) #Throttlesweep checkbutton self.autovar = BooleanVar() cb = Checkbutton(frame1, text="Throttle Sweep", variable=self.autovar, command=self.onClickAuto) cb.pack(side=LEFT, padx=15) #Com port selection field droplbl = Label(frame1, text="Serial Port:", width=10) droplbl.pack(side=LEFT, padx=5, pady=5) self.selected_s_Port = StringVar() self.s_Ports = [] self.drop = OptionMenu(frame1,self.selected_s_Port,"None",*self.s_Ports) self.drop.pack(side=LEFT, padx=5) #baudrate selection field (disabled) ## drop2lbl = Label(frame1, text="Baudrate:", width=9) ## drop2lbl.pack(side=LEFT, padx=5, pady=5) ## self.baudrate = StringVar() ## baudrates = [9600, 19200, 38400, 57600, 115200] ## drop2 = OptionMenu(frame1,self.baudrate,*baudrates) ## drop2.pack(side=LEFT, padx=5) #Start serial button comsButton = Button(frame1, text="Start Serial", command=self.startSerial) comsButton.pack(side=LEFT, padx=5, pady=5) #Stop serial button comsStopButton = Button(frame1, text="Stop Serial", command=self.stopSerial) comsStopButton.pack(side=LEFT, padx=5, pady=5) # Frame 2 (second line) frame2 = Frame(self) frame2.pack(fill=X, expand=1) #Amperage entry lbl2 = Label(frame2, text="Max Motor Current (A):", width=21) lbl2.pack(side=LEFT, padx=5, pady=5) self.MaxA_Entry = Entry(frame2) self.MaxA_Entry.pack(side="left", fill=X, padx=5, expand=False) self.MaxA_Entry.insert(0, 10) #Voltage entry lbl3 = Label(frame2, text="Max Motor Voltage (V):", width=20) lbl3.pack(side=LEFT, padx=5, pady=5) self.MaxV_Entry = Entry(frame2) self.MaxV_Entry.pack(side="left", fill=X, padx=5, expand=False) self.MaxV_Entry.insert(0, 14) #Update button updateButton = Button(frame2, text="Update Values", command=self.updateValues) updateButton.pack(side=LEFT, padx=5, pady=5) # Graph Frame framegraph = Frame(self) framegraph.pack(fill=X, expand=1) #Init figures f = Figure(figsize=(4,4), dpi=100) self.a = f.add_subplot(2, 2, 1) self.d = f.add_subplot(2, 2, 4) self.c = f.add_subplot(2, 2, 3) self.b = f.add_subplot(2, 2, 2) f.set_tight_layout(True) self.canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(f, master=self) self.canvas.show() self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) #Display Toolbar toolbar = NavigationToolbar2TkAgg(self.canvas, framegraph) toolbar.update() self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) # Frame 0 (Bottom text) frame0 = Frame(self) frame0.pack(side="bottom", fill="x", expand=1) #Display text (allows to give user information) self.textboxvar = StringVar() self.info = Label(frame0, textvariable=self.textboxvar) self.info.pack(side=LEFT, padx=5, pady=5) # Button Frame (large buttons, near bottom) s = Style() #has its own style s.configure('My.TFrame',background='#f7edc3') #fancy colors framered = Frame(self, style='My.TFrame') framered.pack(side="bottom", fill="x", expand=1) #used the tk instead of ttk library for this, allows font and color mods #Save Button self.saveButton = tk.Button(framered, text="Save Data", bg='green', font=('Arial',20,'bold'), command=self.saveData) self.saveButton.pack(side="left", padx=5, pady=5) #Log button self.logButton = tk.Button(framered, text="Start Data Logging", bg="blue", font=('Arial',20,'bold'), command=self.logData) self.logButton.pack(side="left", padx=5, pady=5) #Stop button self.stopButton = tk.Button(framered, text="Stop Motor", bg='red', font=('Arial',20,'bold'), command=self.stopMotor) self.stopButton.pack(side="right", padx=5, pady=5) #Button behavior functions (hopefully self-explanatory) def onClickAuto(self): #for the throttle sweep (should rename) pass #(I guess I can make it do something if I want) def MaxA(self): #self.MaxA_Entry.get() pass def MaxV(self): pass #not sure why these are even functions def onScaleThrottle(self, val): throttle = str(int(float(val))) self.throttlevar.set(throttle + "%") self.throttleval.set(throttle) try: self.SC.sendThrottleSetting(self.throttleval.get()) except: self.textboxvar.set("Something went wrong, is serial connected?") def startSerial(self): COM_Port = self.selected_s_Port.get() #print type(COM_Port) #print COM_Port if "COM" in COM_Port: self.textboxvar.set("Starting Serial on port " + self.selected_s_Port.get()) #serialThread = Thread(target=SerialComm, args=(COM_Port)) #probably want to pass the self.vars? #serialThread.start() #threads.append(serialThread) try: self.ser = serial.Serial(self.selected_s_Port.get(), 9600) #Baud rate = 9600 self.SC = SerialComm(self.ser, 50) #Dict deques' maxlength = 50 for key in self.SC.dict.keys(): #Initialize dict deques with values so no length errors -Austin for i in range(self.SC.dict[key].maxlen): self.SC.dict[key].append(None) self.serialStatus = True except Exception,e: #if the com port is wrong dont start serial print str(e) self.textboxvar.set("Error starting serial on port " + self.selected_s_Port.get() + ": " + str(e)) else:
class FindReplacePanel(PluginPanel): name = 'Text Find & Replace' title = _("Text Find & Replace") def init(self, master): PluginPanel.init(self, master) top = self.panel top = TFrame(top, borderwidth=2, style='FlatFrame') top.pack(side=TOP, expand=1, fill=X) button_frame = TFrame(top, borderwidth=2, style='FlatFrame') button_frame.pack(side=BOTTOM, fill=BOTH, expand=1) button = TButton(button_frame, text=_('Apply'), command=self.replace) button.pack(side=TOP) #---------------------------------------------------------- main_frame = TFrame(top, style='FlatFrame', borderwidth=3) main_frame.pack(side=TOP, fill=X) self.find_var = StringVar(top) self.find_var.set('') findField = TEntryExt(main_frame, textvariable=self.find_var) findField.pack(side=RIGHT) label = TLabel(main_frame, style='FlatLabel', text=_("Find:") + " ") label.pack(side=RIGHT, anchor=E) #--------------------------------------------------------- main_frame = TFrame(top, style='FlatFrame', borderwidth=3) main_frame.pack(side=TOP, fill=X) self.replace_var = StringVar(top) self.replace_var.set('') replaceField = TEntryExt(main_frame, textvariable=self.replace_var) replaceField.pack(side=RIGHT) label = TLabel(main_frame, style='FlatLabel', text=_("Replace to:") + " ") label.pack(side=RIGHT, anchor=E) main_frame = TFrame(top, style='FlatFrame', borderwidth=3) main_frame.pack(side=TOP) #--------------------------------------------------------- label = TLabel(top, text=" " + _("Parameters") + " ", style="FlatLabel") label.pack() parametersFrameLabel = TLabelframe(top, labelwidget=label, style='Labelframe', borderwidth=4) parametersFrameLabel.pack(side=TOP, fill=X, pady=4, padx=4) parametersFrame = TFrame(parametersFrameLabel, style='FlatFrame') self.var_case_sensitive = BooleanVar(top) self.var_case_sensitive.set(False) self.case_sensitive_check = TCheckbutton( parametersFrame, text=_("Case sensitive"), variable=self.var_case_sensitive) self.case_sensitive_check.pack(side=TOP, anchor=W, padx=5) self.var_whole_word = BooleanVar(top) self.var_whole_word.set(False) self.whole_word_check = TCheckbutton(parametersFrame, text=_("Whole word"), variable=self.var_whole_word) self.whole_word_check.pack(side=TOP, anchor=W, padx=5) self.var_regexp = BooleanVar(top) self.var_regexp.set(False) self.regexpCheck = TCheckbutton(parametersFrame, text=_("RegExp search"), variable=self.var_regexp, command=self.disable_enable_action) self.regexpCheck.pack(side=TOP, anchor=W, padx=5) parametersFrame.pack(side=TOP, fill=X, pady=2) ################################################################ def replace_text(self, objects, toReplace, replaceTo): for object in objects: if object.is_Text: if self.var_regexp.get(): if self.var_case_sensitive.get(): p = re.compile(toReplace) else: p = re.compile(toReplace, re.I) text = p.sub(replaceTo, object.text) app.mw.document.SelectObject(object) app.mw.document.CallObjectMethod(object.__class__, _('Text Replace'), 'SetText', text) continue if self.var_whole_word.get(): if not self.var_case_sensitive.get(): if object.text.lower() == toReplace.lower(): text = replaceTo app.mw.document.SelectObject(object) app.mw.document.CallObjectMethod( object.__class__, _('Text Replace'), 'SetText', text) else: if object.text == toReplace: text = replaceTo app.mw.document.SelectObject(object) app.mw.document.CallObjectMethod( object.__class__, _('Text Replace'), 'SetText', text) else: if object.text.lower().find(toReplace.lower(), 0, len(object.text)) != -1: if not self.var_case_sensitive.get(): text = object.text.lower().replace( toReplace.lower(), replaceTo) else: text = object.text.replace(toReplace, replaceTo) app.mw.document.SelectObject(object) app.mw.document.CallObjectMethod( object.__class__, _('Text Replace'), 'SetText', text) if object.is_Group: self.replace_text(object.objects) ################################################################ def replace(self): textObjects = [] textToReplace = self.find_var.get().decode('utf-8') replaceTo = self.replace_var.get().decode('utf-8') for layer in app.mw.document.layers: self.replace_text(layer.objects, textToReplace, replaceTo) app.mw.canvas.ForceRedraw() ################################################################ def disable_enable_action(self): if self.var_regexp.get(): self.whole_word_check['state'] = DISABLED else: self.whole_word_check['state'] = NORMAL ################################################################ def whole_word_action(self): pass
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.centerUI(w=520,h=270) def initUI(self): self.parent.title("FIND SPE 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 self.graph_cb = BooleanVar() self.bins = IntVar() self.path = StringVar() self.n_files = IntVar() self.start_s = IntVar() self.end_s = IntVar() self.guess = IntVar() search = Image.open("next_logo.jpg") search_temp = search.resize((160, 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) #Number of Files and Bins. Spin Box self.n_files.set("2000") sb1 = Spinbox(self, from_=1, to=10000, width=6, textvariable=self.n_files) sb1.grid(row=1,column=4, sticky=W) sb1_label = Label(self, text="Files") sb1_label.grid(row=1,column=3, padx=5, sticky=E) self.bins.set("50") sb2 = Spinbox(self, from_=10, to=200, width=6, textvariable=self.bins) sb2.grid(row=1,column=6, sticky=W) sb2_label = Label(self, text="Hist. Bins") sb2_label.grid(row=1,column=5, padx=5, sticky=E) # INTEGRATION LIMITS Integration_label = Label(self, text="INTEGRATION", font = "Verdana 12 bold") Integration_label.grid(row=3,column=4, padx=5, columnspan = 2) self.start_s.set("1732") sb3 = Spinbox(self, from_=1, to=10000, width=6, textvariable=self.start_s) sb3.grid(row=4,column=4, sticky=W) sb3_label = Label(self, text="StartPoint") sb3_label.grid(row=4,column=3, padx=5, sticky=E) self.end_s.set("1752") sb4 = Spinbox(self, from_=1, to=10000, width=6, textvariable=self.end_s) sb4.grid(row=4,column=6, sticky=W) sb4_label = Label(self, text="EndPoint") sb4_label.grid(row=4,column=5, padx=5, sticky=E) sb4_label = Label(self, text="") sb4_label.grid(row=4,column=7, padx=5, sticky=E) # FITTING PARAMETERS Integration_label = Label(self, text="FITTING", font = "Verdana 12 bold") Integration_label.grid(row=6,column=4, padx=5, columnspan = 2) self.guess.set("-20") sb5 = Spinbox(self, from_=-50, to=-1, width=6, textvariable=self.guess) sb5.grid(row=7,column=4, sticky=W) sb5_label = Label(self, text="SPE guess") sb5_label.grid(row=7,column=5, padx=5, sticky=W) #Check buttons cb1 = Checkbutton(self, text="MultiGraph Output", variable=self.graph_cb ) cb1.select() cb1.grid(row=7,column=6, sticky=W) #Text Box #self.path.set("F:/DATOS_DAC/spe_1230/2046/pmt_0_trace_evt_") self.path.set("spe_1230_2046.h5.z") e1 = Entry(self, textvariable=self.path, width=45) e1.grid(row=10,column=3, sticky=W, columnspan=10, padx=10, pady=5) e1_label = Label(self, text="DataSet path (including name file)") e1_label.grid(row=9,column=3,sticky=W, columnspan=10, padx=10) # Main buttons obtn = Button(self, text="GO!!", command=self.SPE_f) obtn.grid(row=14, column=5, sticky=E, pady=5) cbtn = Button(self, text="Quit", command=self.quit) cbtn.grid(row=14, column=6, sticky=E, pady=5) hbtn = Button(self, text="Help") hbtn.grid(row=14, column=0, sticky=W, pady=5) def SPE_f(self): global a if (self.graph_cb.get()==True): b=a a=a+1 else: b=0 SPE.find_SPE_h5(base_path=self.path.get(), n_files=self.n_files.get(), start=self.start_s.get(), end=self.end_s.get(), bins=self.bins.get(), guess=self.guess.get(), n_figure=b) 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 Tagging(Frame): def __init__(self, parent, options): if options == None: options = {} DefaultOptions = {'colorspace':'RGB', 'K':6, 'km_init':'first', 'verbose':False, 'single_thr':0.6, 'metric':'basic'} for op in DefaultOptions: if not op in options: options[op] = DefaultOptions[op] self.options = options self.K_ant = 0 self.num_im=-1 Frame.__init__(self, parent) self.parent = parent self.parent.title("TAGGING") self.F1 = Frame(parent, width=150,borderwidth=2,relief=GROOVE) self.F2 = Frame(parent, width=150,borderwidth=2,relief=GROOVE) self.F3 = Frame(parent) self.F4 = Frame(parent,borderwidth=2,relief=GROOVE) self.F5 = Frame(parent,borderwidth=2,relief=GROOVE) self.F1.pack(side=LEFT, fill=Y, pady = 4, padx=4) self.F2.pack(side=LEFT, fill=Y, pady = 4) self.F3.pack(side=TOP, expand=True, fill=BOTH, pady = 4, padx = 4) self.F4.pack(side=TOP, fill=BOTH, expand=0, padx = 4) self.F5.pack(side=BOTTOM, fill=BOTH, expand=0, pady = 4, padx = 4) self.F1.pack_propagate(0) self.F2.pack_propagate(0) self.F3.pack_propagate(0) lbl = Label(self.F1, text="Groundtruth") lbl.grid(row=0,sticky=W) Frame(self.F1,borderwidth=1,relief=GROOVE,height=2).grid(row=1,sticky=W) lbl = Label(self.F2, text="Detected") lbl.grid(row=0,sticky=W, columnspan=2) Frame(self.F2,borderwidth=1,relief=GROOVE,height=2).grid(row=1,sticky=W, columnspan=2) self.filename = Button(self.F3,text="filename",command=self.ChooseFile) self.filename.pack(side=TOP,expand=0) # #matplotlib setup # plt.ion() self.figure=plt.figure(figsize=(2,2), frameon=False) self.axes=self.figure.add_subplot(111) self.Canvas=FigureCanvasTkAgg(self.figure, master=self.F3) # self.Canvas.show() self.Canvas.get_tk_widget().pack(side=TOP,fill=BOTH,expand=1 ) plt.axis('off') b = Button(self.F4,text=" <<<10 ",command=self.PreviousFast) b.pack(side=LEFT, padx=(20,2), pady=3) b = Button(self.F4,text=" <<1 ",command=self.Previous) b.pack(side=LEFT, pady=3) self.im_name = Button(self.F4,text="image",bd=0, command=self.Results) self.im_name.pack(side=LEFT, expand=True) b = Button(self.F4,text=" 1>> ",command=self.Next) b.pack(side=LEFT) b = Button(self.F4,text=" 10>>> ",command=self.NextFast) b.pack(side=LEFT, padx=(2,20)) F51 = Frame(self.F5) F52 = Frame(self.F5) F53 = Frame(self.F5) F51.pack(fill=BOTH, expand=1, side=LEFT) Frame(self.F5,borderwidth=1,relief=GROOVE,width=2).pack(side=LEFT, fill=Y) F52.pack(fill=BOTH, expand=1, side=LEFT) Frame(self.F5,borderwidth=1,relief=GROOVE,width=2).pack(side=LEFT, fill=Y) F53.pack(fill=BOTH, expand=1, side=LEFT) Label(F51, text="Color space").pack() Frame(F51,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) Label(F52, text="K-Means").pack() Frame(F52,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) Label(F53, text="Labelling").pack() Frame(F53,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) self.ColorMode = StringVar() self.ColorMode.set(self.options[COLORSSPACE['key']]) for text, mode in COLORSSPACE['options_gui']: b = Radiobutton(F51, text=text, variable=self.ColorMode, value=mode, command=self.Results) b.pack(anchor=W) Frame(F51,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) Label(F51, text="Grouping", padx=20).pack() Frame(F51,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) self.Group = BooleanVar() self.Group.set(True) b = Checkbutton(F51, text='Group same label colors', variable=self.Group, command=self.Results) b.pack(anchor=W) F521 = Frame(F52) F522 = Frame(F52) F521.pack(fill=BOTH) F522.pack(fill=BOTH) # F523 = Frame(F52) # F523.pack(fill=BOTH) self.K = StringVar() self.K.set(self.options['K']) # f = Frame(F52) # f.pack(side=TOP, fill=BOTH, expand=0) Label(F521, text="K : ").pack(side=LEFT) Entry(F521, textvariable=self.K, width=3, justify=CENTER).pack(side=LEFT, padx=4) # Label(F52, text="Init", padx=20).pack(anchor=W) # Frame(F521,borderwidth=1,relief=GROOVE,width=2).pack(side=RIGHT, fill=Y, padx=2) self.Fitting = StringVar() self.Fitting.set(self.options[FITTING['key']]) # f = Frame(F52) # f.pack(side=RIGHT, fill=BOTH, expand=0) for text, mode in FITTING['options_gui']: b = Radiobutton(F521, text=text, variable=self.Fitting, value=mode, command=self.Results) b.pack(anchor=W,padx=4) Frame(F522,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) Label(F522, text="Centroid Init", padx=20).pack() Frame(F522,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) # IM = [('First points','first'),('Randomize', 'random'),('Distribtued','distributed'),('Other','Other')] self.KMInit = StringVar() self.KMInit.set(self.options[CENTROIDSINIT['key']]) for text, mode in CENTROIDSINIT['options_gui']: b = Radiobutton(F522, text=text, variable=self.KMInit, value=mode, command=self.Results) b.pack(anchor=W) self.Thr = StringVar() self.Thr.set(self.options['single_thr']) f = Frame(F53) f.pack(side=TOP, fill=BOTH, expand=0) Label(f, text="single\nbasic >\ncolor", justify=LEFT).pack(side=LEFT) Entry(f, textvariable=self.Thr, width=4, justify=CENTER).pack(side=LEFT) # self.Synonymous = BooleanVar() # self.Synonymous.set(self.options['synonyms']) # b = Checkbutton(F53, text='Synonymous', variable=self.Synonymous, command=self.Results) # b.pack(anchor=W) Frame(F53,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) Label(F53, text="Similarity Metric", padx=2).pack() Frame(F53,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) self.Metric = StringVar() self.Metric.set(self.options[SIMILARITY['key']]) for text, mode in SIMILARITY['options_gui']: b = Radiobutton(F53, text=text, variable=self.Metric, value=mode, command=self.Results) b.pack(anchor=W) def ChooseFile(self): filename = tkFileDialog.askopenfilename(initialdir='Images', filetypes=[("Text files","*.txt")]) if filename =='': return self.ImageFolder = os.path.dirname(filename) self.filename['text'] = os.path.basename(filename) self.GT = lb.loadGT(filename) self.num_im = 0 self.Results() def Previous(self): self.num_im -= 1 if self.num_im<-1: self.num_im=0 elif self.num_im<0: self.num_im=0 return self.Results() def PreviousFast(self): self.num_im -= 10 if self.num_im<0: self.num_im=0 self.Results() def Next(self): self.num_im += 1 if self.num_im>=len(self.GT): self.num_im=len(self.GT)-1 return self.Results() def NextFast(self): self.num_im += 10 if self.num_im>=len(self.GT): self.num_im=len(self.GT)-1 self.Results() def Results(self): if self.num_im<0 or self.num_im>=len(self.GT): return #self.parent.config(cursor="wait") self.parent.update() self.im_name['text'] = self.GT[self.num_im][0] im = io.imread(self.ImageFolder+"/"+self.GT[self.num_im][0]) self.options['K'] = int(self.K.get()) self.options['single_thr'] = float(self.Thr.get()) # self.options['synonyms'] = self.Synonymous.get() self.options[COLORSSPACE['key']] = self.ColorMode.get() self.options[CENTROIDSINIT['key']] = self.KMInit.get() self.options[SIMILARITY['key']] = self.Metric.get() self.options[FITTING['key']] = self.Fitting.get() if self.options['fitting'] != 'None': if self.K_ant==0: self.K_ant = self.options['K'] self.options['K'] = 0 self.K.set(0) pass else: if self.K_ant>0: self.K.set(self.K_ant) self.options['K'] = self.K_ant self.K_ant = 0 self.labels, self.which, self.km = lb.processImage(im, self.options) if self.options['K'] == 0: self.K.set(self.km.K) if not self.Group.get(): self.labels = [w for ww in [[w]*len(z) for w,z in zip(self.labels,self.which)] for w in ww] self.which = [[w] for ww in self.which for w in ww] # get percentages for every label percent = np.zeros((len(self.which),1)) for i,w in enumerate(self.which): for k in w: percent[i] += np.sum(self.km.clusters==k) percent = percent*100/self.km.clusters.size # get color for every label from image sh = im.shape; im = np.reshape(im, (-1, im.shape[2])) colors = np.zeros((len(self.which),3)) for i,w in enumerate(self.which): for k in w: colors[i] += np.mean(im[self.km.clusters==k,:],0) colors[i] /= len(w) im = np.reshape(im, sh) self.im = im self.CBgt = self.CreateCheckList(self.F1, self.GT[self.num_im][1]) self.CBdetected = self.CreateCheckList(self.F2, self.labels, percent, colors) l = Label(self.F2,text='similarity: '+'%.2f' % (lb.similarityMetric(self.labels, self.GT[self.num_im][1], self.options)*100)+'%') l.grid(columnspan=2,sticky=W+E+N+S) self.F2.grid_rowconfigure(self.F2.grid_size()[1]-1, weight=1) self.CheckLabels() #self.parent.config(cursor="") self.parent.update() self.Segment() # self.ShowImage(im) def Segment(self): all_widgetes = self.F2.winfo_children() cb = [w for w in all_widgetes if w.winfo_class() == 'Checkbutton'] lab_colors = np.zeros((len(cb),3)) for i,c in enumerate(cb): lab_colors[i,0] = int(c.cget('bg')[1:3], 16) lab_colors[i,1] = int(c.cget('bg')[3:5], 16) lab_colors[i,2] = int(c.cget('bg')[5:7], 16) ims = np.empty_like(self.im) ims = np.reshape(ims, (-1, ims.shape[2])) for i,w in enumerate(self.which): for k in w: ims[self.km.clusters==k]=lab_colors[i] ims = np.reshape(ims, self.im.shape) self.ShowImage(np.hstack((ims,self.im))) def ShowImage(self,im): self.axes.imshow(im) plt.axis('off') self.Canvas.draw() def CreateCheckList(self, frame, labels, values=None, colors=None): all_widgetes = [w for w in frame.winfo_children() if w.winfo_class() == 'Checkbutton'] for w in all_widgetes: w.destroy() all_widgetes = [w for w in frame.winfo_children() if w.winfo_class() == 'Label'] for w in all_widgetes[1:]: w.destroy() var = [] if values is not None: add_text = ["%5.1f" % (values[i]) +'%' for i in range(len(values))] for i in range(len(labels)): var.append(BooleanVar()) fgc = "black" if colors is not None: mycolor = '#%02x%02x%02x' % (colors[i,0], colors[i,1], colors[i,2]) if (colors[i,0]+colors[i,1]+colors[i,2])/3/255<=0.5: fgc = "#FFFFFF" else: mycolor = frame.cget('bg') cb = Checkbutton(frame, text=labels[i], state=DISABLED, variable=var[i], bg=mycolor, disabledforeground=fgc, anchor=W) # cb.pack(anchor=W, fill=X, padx=2) cb.grid(row=i+2,column=0,sticky=W+E) if values is not None: cb = Label(frame, text=add_text[i], bg=mycolor, fg=fgc, anchor=E) cb.grid(row=i+2,column=1,sticky=W+E+N+S) frame.grid_rowconfigure(i+2, weight=0) return var def CheckLabels(self): for i in range(len(self.labels)): if self.labels[i] in self.GT[self.num_im][1]: self.CBdetected[i].set(True) for i in range(len(self.GT[self.num_im][1])): if self.GT[self.num_im][1][i] in self.labels: self.CBgt[i].set(True)
class SearchEngine: """Handles searching a text widget for Find, Replace, and Grep.""" def __init__(self, root): """Initialize Variables that save search state. The dialogs bind these to the UI elements present in the dialogs. """ self.root = root self.patvar = StringVar(root, '') self.revar = BooleanVar(root, False) self.casevar = BooleanVar(root, False) self.wordvar = BooleanVar(root, False) self.wrapvar = BooleanVar(root, True) self.backvar = BooleanVar(root, False) def getpat(self): return self.patvar.get() def setpat(self, pat): self.patvar.set(pat) def isre(self): return self.revar.get() def iscase(self): return self.casevar.get() def isword(self): return self.wordvar.get() def iswrap(self): return self.wrapvar.get() def isback(self): return self.backvar.get() def setcookedpat(self, pat): """Set pattern after escaping if re.""" if self.isre(): pat = re.escape(pat) self.setpat(pat) def getcookedpat(self): pat = self.getpat() if not self.isre(): pat = re.escape(pat) if self.isword(): pat = '\\b%s\\b' % pat return pat def getprog(self): """Return compiled cooked search pattern.""" pat = self.getpat() if not pat: self.report_error(pat, 'Empty regular expression') return None else: pat = self.getcookedpat() flags = 0 if not self.iscase(): flags = flags | re.IGNORECASE try: prog = re.compile(pat, flags) except re.error as what: args = what.args msg = args[0] col = arg[1] if len(args) >= 2 else -1 self.report_error(pat, msg, col) return None return prog def report_error(self, pat, msg, col = -1): msg = 'Error: ' + str(msg) if pat: msg = msg + '\nPattern: ' + str(pat) if col >= 0: msg = msg + '\nOffset: ' + str(col) tkMessageBox.showerror('Regular expression error', msg, master=self.root) def search_text(self, text, prog = None, ok = 0): """Return (lineno, matchobj) or None for forward/backward search. This function calls the right function with the right arguments. It directly return the result of that call. Text is a text widget. Prog is a precompiled pattern. The ok parameteris a bit complicated as it has two effects. If there is a selection, the search begin at either end, depending on the direction setting and ok, with ok meaning that the search starts with the selection. Otherwise, search begins at the insert mark. To aid progress, the search functions do not return an empty match at the starting position unless ok is True. """ if not prog: prog = self.getprog() if not prog: return None wrap = self.wrapvar.get() first, last = get_selection(text) if self.isback(): if ok: start = last else: start = first line, col = get_line_col(start) res = self.search_backward(text, prog, line, col, wrap, ok) else: if ok: start = first else: start = last line, col = get_line_col(start) res = self.search_forward(text, prog, line, col, wrap, ok) return res def search_forward(self, text, prog, line, col, wrap, ok = 0): wrapped = 0 startline = line chars = text.get('%d.0' % line, '%d.0' % (line + 1)) while chars: m = prog.search(chars[:-1], col) if m: if ok or m.end() > col: return (line, m) line = line + 1 if wrapped and line > startline: break col = 0 ok = 1 chars = text.get('%d.0' % line, '%d.0' % (line + 1)) if not chars and wrap: wrapped = 1 wrap = 0 line = 1 chars = text.get('1.0', '2.0') return None def search_backward(self, text, prog, line, col, wrap, ok = 0): wrapped = 0 startline = line chars = text.get('%d.0' % line, '%d.0' % (line + 1)) while 1: m = search_reverse(prog, chars[:-1], col) if m: if ok or m.start() < col: return (line, m) line = line - 1 if wrapped and line < startline: break ok = 1 if line <= 0: if not wrap: break wrapped = 1 wrap = 0 pos = text.index('end-1c') line, col = map(int, pos.split('.')) chars = text.get('%d.0' % line, '%d.0' % (line + 1)) col = len(chars) - 1 return None
class PmaConvert: def __init__(self, config): root = Tk() # Root Definition root.geometry('1100x700') root.title('PMA Convert') # Configuration and Variables self.file_selection = '' self.is_converting = False self.options = config['option_definitions'] gui_config = config['gui_config'] # UI ## Frames self.main_frame = Frame(root) self.position_main_frame(gui_config['screen_orientation']) ## Components self.log = Text(self.main_frame, bd=1, relief=SUNKEN, width=140, height=23, state=DISABLED, spacing3=1, wrap=WORD) choose_text = ('1. Choose XLSForm (.xls or .xlsx) file(s) for ' 'conversion.') self.choose_files_label = Label(self.main_frame, text=choose_text) # TODO: Get spacing to work. # self.choose_files_label.grid(row=3, column=3, padx=(50, 50)) # self.choose_files_label.grid(row=3, column=3, pady=(50, 50)) self.choose_files_label.pack() self.choose_files_button = Button(self.main_frame, text='Choose file...', fg='black', command=self.on_open) self.choose_files_button.pack() out_text = 'Choose location for output file(s).' self.output_location_label = Label(self.main_frame, text=out_text) self.output_location_button = Button(self.main_frame, text='Choose location...', fg='black') if gui_config['output_location_on'] is True: self.output_location_label.pack() self.output_location_button.pack() self.choose_options_label = Label(self.main_frame, text='2. Choose conversion options.') self.choose_options_label.pack() ### Create Options Checkboxes # Task: Dynamically generate: http://stackoverflow.com/questions/... # ...553784/can-you-use-a-string-to-instantiate-a-class-in-python self.preexisting = BooleanVar() pre_text = self.options['preexisting']['label'] self.preexisting_opt = Checkbutton(self.main_frame, text=pre_text, variable=self.preexisting) self.preexisting_opt.pack() self.regular = BooleanVar() reg_text = self.options['regular']['label'] self.regular_opt = Checkbutton(self.main_frame, text=reg_text, variable=self.regular) self.regular_opt.pack() self.novalidate = BooleanVar() noval_text = self.options['novalidate']['label'] self.novalidate_opt = Checkbutton(self.main_frame, text=noval_text, variable=self.novalidate) self.novalidate_opt.pack() self.ignore_version = BooleanVar() ig_text = self.options['ignore_version']['label'] self.ignore_version_opt = Checkbutton(self.main_frame, text=ig_text, variable=self.ignore_version) self.ignore_version_opt.pack() self.linking_warn = BooleanVar() link_text = self.options['linking_warn']['label'] self.linking_warn_option = Checkbutton(self.main_frame, text=link_text, variable=self.linking_warn) self.linking_warn_option.pack() self.debug = BooleanVar() debug_text = self.options['debug']['label'] self.debug_option = Checkbutton(self.main_frame, text=debug_text, variable=self.debug) self.debug_option.pack() self.extras = BooleanVar() extras_text = self.options['extras']['label'] self.extras_option = Checkbutton(self.main_frame, text=extras_text, variable=self.extras) self.extras_option.pack() self.convert_label = Label(self.main_frame, text='3. Run conversion.') self.convert_label.pack() # Task: Add xscrollcommand and yscrollcommand. self.convert_button = Button(self.main_frame, text='Convert', fg='black', command=self.convert) self.convert_button.pack() self.log.pack(fill=X, expand=1) self.log_text('PMA Convert allows you to convert .xls or .xlsx form ' 'definition files to files which are compatible with ODK ' 'Collect.\n\nIf you need to copy and paste from this ' 'log, highlight the text and press CTRL+C to copy. Then ' 'press CTRL+V to paste.\n\n' '====================================================\n\n' 'Awaiting file selection.') # Task: Fix menus. They're not working. self.context_menu = Menu(self.main_frame, tearoff=0) self.context_menu.add_command(label="Convert", command=self.convert) self.main_frame.bind("<Button-3>", self.popup) # - Note: Strangely this stopped anchoring to bottom suddenly, for some # reason. So it is temporarily disabled. self.status_bar = Label(self.main_frame, text='Awaiting file selection.', bd=1, relief=SUNKEN, anchor=W) if gui_config['status_bar_on'] is True: self.status_bar.pack(side=BOTTOM, fill=X) # Run root.mainloop() # Functions def popup(self, event): # Note: Currently doesn't work. self.context_menu.post(event.x_root, event.y_root) # display the popup menu try: self.context_menu.tk_popup(event.x_root, event.y_root, 0) finally: # make sure to release the grab (Tk 8.0a1 only) self.context_menu.grab_release() def position_main_frame(self, orientation): if orientation == 'center': x, y, a = .5, .5, 'c' return self.main_frame.place(relx=x, rely=y, anchor=a) elif orientation == 'top': return self.main_frame.pack() else: return self.main_frame.pack() def on_open(self): file_types = [ ('XLS Files', '*.xls'), ('XLSX Files', '*.xlsx'), ('All files', '*') ] try: self.file_selection = tkFileDialog.askopenfilename( filetypes=file_types, title='Open one or more files.', message='Open one or more files', multiple=1 ) except: self.file_selection = tkFileDialog.askopenfilename( filetypes=file_types, title='Open one or more files.', multiple=1 ) if self.file_selection != '': self.set_status('Click on Convert to convert files.') log_output = 'Ready for conversion: \n' for file in self.file_selection: log_output += '* ' + str(file) + '\n' log_output = log_output[:-1] # Removes the last '\n'. self.log.configure(self.log_text(log_output)) def set_status(self, new_status): self.status_bar.configure(text=new_status) def log_text(self, new_text): self.log.configure(state=NORMAL) self.log.insert(END, str(new_text) + '\n\n') self.log.configure(state=DISABLED) self.log.bind("<1>", lambda event: self.log.focus_set()) def convert(self): if self.file_selection != '': f = self.file_selection kwargs = { SUFFIX: u'', PREEXISTING: self.preexisting.get(), PMA: not self.regular.get(), CHECK_VERSIONING: not self.ignore_version.get(), STRICT_LINKING: not self.linking_warn.get(), VALIDATE: not self.novalidate.get(), EXTRAS: self.extras.get(), DEBUG: self.debug.get() } buffer = StringIO.StringIO() if not kwargs[DEBUG]: sys.stdout = buffer sys.stderr = buffer else: self.log_text('--> DEBUG MODE: check console output') try: xlsform_convert(f, **kwargs) except ConvertError as e: print unicode(e) except OSError as e: # Should catch WindowsError, impossible to test on Mac traceback.print_exc() print e if not kwargs[DEBUG]: sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ self.log_text(buffer.getvalue())
def main(argv): if len(argv) == 1: root = Tk() root.title("Randominions 4") mapfilevar = StringVar() outfilevar = StringVar() outfilevar.set("newrandommap.map") modfilevar = StringVar() lvl1thronevar = IntVar() lvl1thronevar.set(0) lvl2thronevar = IntVar() lvl2thronevar.set(0) lvl3thronevar = IntVar() lvl3thronevar.set(0) landstartvar = IntVar() landstartvar.set(0) waterstartvar = IntVar() waterstartvar.set(0) coaststartvar = IntVar() coaststartvar.set(0) foreststartvar = IntVar() foreststartvar.set(0) swampstartvar = IntVar() swampstartvar.set(0) cavestartvar = IntVar() cavestartvar.set(0) indystrengthvar = IntVar() indystrengthvar.set(100) rarechancevar = IntVar() rarechancevar.set(10) magepowervar = IntVar() magepowervar.set(2) allowsacred = BooleanVar() allowsacred.set(False) Label(root, text="Map:").grid(row=0, sticky=E) Entry(root, width=50, textvariable=mapfilevar).grid(row=0, column=1) Label(root, text="Output map:").grid(row=4, sticky=E) Entry(root, width=50, textvariable=outfilevar).grid(row=4, column=1) Label(root, text="Nation mod file:").grid(row=5, sticky=E) Entry(root, width=50, textvariable=modfilevar).grid(row=5, column=1) Label(root, text="Rare indy chance(%):").grid(row=6, sticky=E) Entry(root, width=5, textvariable=rarechancevar).grid(row=6, column=1, sticky=W) Label(root, text="Indy strength(%):").grid(row=7, sticky=E) Entry(root, width=5, textvariable=indystrengthvar).grid(row=7, column=1, sticky=W) Label(root, text="Max nation mage power:").grid(row=8, sticky=E) Entry(root, width=5, textvariable=magepowervar).grid(row=8, column=1, sticky=W) Label(root, text="Allow sacred units:").grid(row=9, sticky=E) Checkbutton(root, variable=allowsacred).grid(row=9, column=1, sticky=W) Label(root, text="Level 1 thrones:").grid(row=0, column=3, sticky=E) Entry(root, width=3, textvariable=lvl1thronevar).grid(row=0, column=4) Label(root, text="Level 2 thrones:").grid(row=1, column=3, sticky=E) Entry(root, width=3, textvariable=lvl2thronevar).grid(row=1, column=4) Label(root, text="Level 3 thrones:").grid(row=2, column=3, sticky=E) Entry(root, width=3, textvariable=lvl3thronevar).grid(row=2, column=4) Label(root, text="Land nations:").grid(row=3, column=3, sticky=E) Entry(root, width=3, textvariable=landstartvar).grid(row=3, column=4) Label(root, text="Water nations:").grid(row=4, column=3, sticky=E) Entry(root, width=3, textvariable=waterstartvar).grid(row=4, column=4) Label(root, text="Coastal starts:").grid(row=5, column=3, sticky=E) Entry(root, width=3, textvariable=coaststartvar).grid(row=5, column=4) Label(root, text="Forest starts:").grid(row=6, column=3, sticky=E) Entry(root, width=3, textvariable=foreststartvar).grid(row=6, column=4) Label(root, text="Swamp starts:").grid(row=7, column=3, sticky=E) Entry(root, width=3, textvariable=swampstartvar).grid(row=7, column=4) Label(root, text="Cave starts:").grid(row=8, column=3, sticky=E) Entry(root, width=3, textvariable=cavestartvar).grid(row=8, column=4) Label(root, text="Indies:").grid(row=1, sticky=E) indylist = Listbox(root, width=50, height=4) indylist.grid(row=1, column=1, rowspan=3) Button(root, width=13, text="Choose Map", command=lambda : mapfilevar.set(askopenfilename(filetypes=[('Dominions 4 map files', '.map')]))).grid(row=0, column=2, sticky=W) Button(root, width=13, text="Choose Mod", command=lambda : modfilevar.set(askopenfilename(filetypes=[('Dominions 4 mod file', '.dm')]))).grid(row=5, column=2, sticky=W) Button(root, width=13, text="Add indies", command=lambda : indylist.insert(END,askopenfilename(filetypes=[('JSON files', '.json'), ('Domions 4 mod files', '.dm')]))).grid(row=1, column=2, sticky=W) Button(root, width=13, text="Remove selected", command=lambda : indylist.delete(ANCHOR)).grid(row=2, column=2, sticky=W) Button(root, width=10, text="Quit", command=root.destroy).grid(row=10, column=0) Button(root, width=10, text="Generate!", \ command=lambda : runGenerator(mapfilevar.get(), indylist.get(0, END), outfilevar.get(), landstartvar.get(), waterstartvar.get(), \ coaststartvar.get(), foreststartvar.get(), swampstartvar.get(), cavestartvar.get(), lvl1thronevar.get(), \ lvl2thronevar.get(), lvl3thronevar.get(), rarechancevar.get(), indystrengthvar.get(), modfilevar.get(), magepowervar.get(), allowsacred.get())).grid(row=10, column=3) root.mainloop() elif len(argv) < 15: print "Usage: randominions4 mapfile targetmapfile indydefinition landnations waternations coaststarts foreststarts swampstarts cavestarts lvl1thrones lvl2thrones lvl3thrones rarechance indystrength" else: mapfile = argv[1] indyfile = argv[3] targetfile = argv[2] landcount = int(argv[4]) watercount = int(argv[5]) coaststarts = int(argv[6]) foreststarts = int(argv[7]) swampstarts = int(argv[8]) cavestarts = int(argv[9]) lvl1thrones = int(argv[10]) lvl2thrones = int(argv[11]) lvl3thrones = int(argv[12]) rarechance = int(argv[13]) strength = int(argv[14]) runGenerator(mapfile, [indyfile], targetfile, landcount, watercount, coaststarts, foreststarts, swampstarts, cavestarts, lvl1thrones, lvl2thrones, lvl3thrones, rarechance, strength, None, None, None)
class SearchEngine: """Handles searching a text widget for Find, Replace, and Grep.""" def __init__(self, root): """Initialize Variables that save search state. The dialogs bind these to the UI elements present in the dialogs. """ self.root = root self.patvar = StringVar(root, '') self.revar = BooleanVar(root, False) self.casevar = BooleanVar(root, False) self.wordvar = BooleanVar(root, False) self.wrapvar = BooleanVar(root, True) self.backvar = BooleanVar(root, False) def getpat(self): return self.patvar.get() def setpat(self, pat): self.patvar.set(pat) def isre(self): return self.revar.get() def iscase(self): return self.casevar.get() def isword(self): return self.wordvar.get() def iswrap(self): return self.wrapvar.get() def isback(self): return self.backvar.get() def setcookedpat(self, pat): """Set pattern after escaping if re.""" if self.isre(): pat = re.escape(pat) self.setpat(pat) def getcookedpat(self): pat = self.getpat() if not self.isre(): pat = re.escape(pat) if self.isword(): pat = '\\b%s\\b' % pat return pat def getprog(self): """Return compiled cooked search pattern.""" pat = self.getpat() if not pat: self.report_error(pat, 'Empty regular expression') return None else: pat = self.getcookedpat() flags = 0 if not self.iscase(): flags = flags | re.IGNORECASE try: prog = re.compile(pat, flags) except re.error as what: args = what.args msg = args[0] col = arg[1] if len(args) >= 2 else -1 self.report_error(pat, msg, col) return None return prog def report_error(self, pat, msg, col=-1): msg = 'Error: ' + str(msg) if pat: msg = msg + '\nPattern: ' + str(pat) if col >= 0: msg = msg + '\nOffset: ' + str(col) tkMessageBox.showerror('Regular expression error', msg, master=self.root) def search_text(self, text, prog=None, ok=0): """Return (lineno, matchobj) or None for forward/backward search. This function calls the right function with the right arguments. It directly return the result of that call. Text is a text widget. Prog is a precompiled pattern. The ok parameteris a bit complicated as it has two effects. If there is a selection, the search begin at either end, depending on the direction setting and ok, with ok meaning that the search starts with the selection. Otherwise, search begins at the insert mark. To aid progress, the search functions do not return an empty match at the starting position unless ok is True. """ if not prog: prog = self.getprog() if not prog: return None wrap = self.wrapvar.get() first, last = get_selection(text) if self.isback(): if ok: start = last else: start = first line, col = get_line_col(start) res = self.search_backward(text, prog, line, col, wrap, ok) else: if ok: start = first else: start = last line, col = get_line_col(start) res = self.search_forward(text, prog, line, col, wrap, ok) return res def search_forward(self, text, prog, line, col, wrap, ok=0): wrapped = 0 startline = line chars = text.get('%d.0' % line, '%d.0' % (line + 1)) while chars: m = prog.search(chars[:-1], col) if m: if ok or m.end() > col: return (line, m) line = line + 1 if wrapped and line > startline: break col = 0 ok = 1 chars = text.get('%d.0' % line, '%d.0' % (line + 1)) if not chars and wrap: wrapped = 1 wrap = 0 line = 1 chars = text.get('1.0', '2.0') return None def search_backward(self, text, prog, line, col, wrap, ok=0): wrapped = 0 startline = line chars = text.get('%d.0' % line, '%d.0' % (line + 1)) while 1: m = search_reverse(prog, chars[:-1], col) if m: if ok or m.start() < col: return (line, m) line = line - 1 if wrapped and line < startline: break ok = 1 if line <= 0: if not wrap: break wrapped = 1 wrap = 0 pos = text.index('end-1c') line, col = map(int, pos.split('.')) chars = text.get('%d.0' % line, '%d.0' % (line + 1)) col = len(chars) - 1 return None
class Studio(Frame): """The Studio class is a GUI for the digital library.""" _meter = None _grid = None _dual_box = None _auto_queue = None _entry = None _search_results = None _selected_cart = None def __init__(self): """Construct a Studio window.""" Frame.__init__(self) # make the window resizable top = self.master.winfo_toplevel() for row in range(2, GRID_ROWS + 2): for col in range(0, GRID_COLS): top.rowconfigure(row, weight=1) top.columnconfigure(col, weight=1) self.rowconfigure(row, weight=1) self.columnconfigure(col, weight=1) # initialize the title title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE) title.grid(row=0, column=0, columnspan=GRID_COLS) # initialize the meter self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data) self._meter.grid(row=1, column=0, columnspan=GRID_COLS) # initialize the cart grid self._grid = Grid(self, GRID_ROWS, GRID_COLS, True, self._cart_start, self._cart_stop, self._cart_end, self.add_cart) # initialize the dual box self._dual_box = DualBox(self) self._dual_box.grid(row=GRID_ROWS + 2, column=0, columnspan=4) # intialize the auto-queue control self._auto_queue = BooleanVar() self._auto_queue.set(False) control = Frame(self.master, bd=2, relief=Tkinter.SUNKEN) Checkbutton(control, text=TEXT_AUTOSLOT, variable=self._auto_queue, onvalue=True, offvalue=False).pack(anchor=Tkinter.NW) control.grid(row=GRID_ROWS + 2, column=4, columnspan=GRID_COLS - 4) # initialize the search box, button Label(control, font=FONT, text=TEXT_SEARCHBOX).pack(anchor=Tkinter.NW) self._entry = Entry(control, takefocus=True, width=45) self._entry.bind("<Return>", self.search) # self._entry.grid(row=GRID_ROWS + 3, column=0, columnspan=5) self._entry.pack(anchor=Tkinter.NW) self._entry.focus_set() button = Button(control, text=TEXT_SEARCH, command=self.search) # button.grid(row=GRID_ROWS + 3, column=5) button.pack(anchor=Tkinter.S) # begin the event loop self.master.protocol("WM_DELETE_WINDOW", self.master.destroy) self.master.title(TEXT_TITLE) self.master.mainloop() def _search_internal(self): """Search the digital library in a separate thread.""" query = self._entry.get() if len(query) >= 3: print "Searching library with query \"%s\"..." % query self._search_results = database.search_library(query) self._dual_box.fill(self._search_results) print "Found %d results." % len(self._search_results) def search(self, *args): """Search the digital library. :param args """ thread.start_new_thread(self._search_internal, ()) def select_cart(self, index): """Select a cart from the search results. :param index: index of cart in search results """ if index is not None: self._selected_cart = self._search_results[index] def add_cart(self, key): """Add the selected cart to the grid. :param key """ if not self._grid.has_cart(key) and self._selected_cart is not None: self._grid.set_cart(key, self._selected_cart) def _cart_start(self): """Start the meter when a cart starts.""" self._meter.start() def _cart_stop(self): """Reset the meter when a cart stops.""" self._meter.reset() def _cart_end(self, key): """Reset the meter when a cart ends. Also, if auto-queue is enabled, queue the next cart. :param key """ self._meter.reset() if self._auto_queue.get(): next_key = get_next_key(GRID_ROWS, GRID_COLS, key) if self._grid.has_cart(next_key): self._grid.start(next_key) def _get_meter_data(self): """Get meter data for the currently active cart.""" return self._grid.get_active_cell().get_cart().get_meter_data()