def __init__(self, app): self.app = app Toplevel.__init__(self, app) self.title("Reset Usage Counters") self.protocol("WM_DELETE_WINDOW", self.doCancel) f = Frame(self) f.pack() self.cbDL = {} for d in DLLIST: cbv = IntVar() t = "%s(%s)" % (DLNAMES[d], self.app.dataLoggers[d].getToNowStr()) cb = Checkbutton(f, text=t, variable=cbv) self.cbDL[d] = cbv cb.pack(anchor=W, padx=10) f = Frame(self) f.pack() self.bOK = Button(f, text="OK", width=12, command=self.doOK) self.bOK.pack(side=LEFT, padx=2, pady=5) self.bCancel = Button(f, text="Cancel", width=12, command=self.doCancel) self.bCancel.pack(side=LEFT, padx=2, pady=5)
def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent button_frame = Frame(self) button_frame.pack(side=TOP, fill=X, expand=0) text_frame = Frame(self) text_frame.pack(side=TOP, fill=BOTH, expand=1) t = Text(text_frame) t.pack(side=LEFT, fill=BOTH, expand=1) s = Scrollbar(text_frame) s.pack(side=LEFT, fill=Y, expand=1) bplay = Button(button_frame, text='Play', command=self.foo) bnext = Button(button_frame, text='Next') cplot = Checkbutton(button_frame, text="Backplot") cmat = Checkbutton(button_frame, text="Material") cbit = Checkbutton(button_frame, text="Bit") cpause1 = Checkbutton(button_frame, text="Pause after line") cpause2 = Checkbutton(button_frame, text="Pause after cmt") bplay.pack(side=LEFT) bnext.pack(side=LEFT) cplot.pack(side=LEFT) cmat.pack(side=LEFT) cbit.pack(side=LEFT) cpause1.pack(side=LEFT) cpause2.pack(side=LEFT)
def create_entry_ck(self, _row2use_, _i_=None, container=[]): ''' creates a too custom check row so it aparts here''' _row_ = Frame(_row2use_) if _i_ == None: _group_, _def_ids_, _def_fcoord_, _res_ens_ = container else: _group_ = self._entries_[_i_] _def_fcoord_ = self._defvals_[_i_] _def_ids_ = self.range_ids[_i_] _res_ens_ = self.range_ens[_i_] label0 = Label(_row_, width=1, text=" ", anchor='w') # first check button cvar = IntVar() label1 = Checkbutton(_row_, width=0, variable=cvar, command=self.checkbuttonstuff, anchor='w') self.ckb_c.append([cvar, label1]) # group description label2 = Label(_row_, width=6, text='Group ', anchor='w') Ent_gr = Entry(_row_, width=8) Ent_gr.insert('end', _group_) label2_2 = Label(_row_, width=5, text=" ids", anchor='w') # group ids Ent_ids = Entry(_row_, width=10) Ent_ids.insert('end', _def_ids_) label3 = Label(_row_, width=7, text=" K:xyz ", anchor='w') Ent_it = Entry(_row_, width=6) Ent_it.insert('end', _def_fcoord_) label4 = Label(_row_, width=5, text=" In run", anchor='w') Ent_ens = Entry(_row_, width=6) Ent_ens.insert('end', _res_ens_) finalspace = Label(_row_, width=5, text=" ", anchor='w') # Just packing label0.pack(side='left', padx=0) label1.pack(side='left', padx=2) label2.pack(side='left', padx=0) Ent_gr.pack(side='left', expand=True, fill=X) label2_2.pack(side='left', padx=0) Ent_ids.pack(side='left', expand=True, fill=X) label3.pack(side='left', padx=0) Ent_it.pack(side='left', expand=True, fill=X) label4.pack(side='left', padx=0) Ent_ens.pack(side='left', expand=True, fill=X) finalspace.pack(side='right', padx=0) _row_.pack(side='top', fill=X, pady=3) # For tracing purposes list appending self.ent_c.append([Ent_gr, Ent_ids, Ent_it, Ent_ens])
class PasswordDialog(Dialog): def __init__(self, title, prompt, parent): self.prompt = prompt Dialog.__init__(self, parent, title) def body(self, master): from Tkinter import Label from Tkinter import Entry from Tkinter import Checkbutton from Tkinter import IntVar from Tkinter import W self.checkVar = IntVar() Label(master, text=self.prompt).grid(row=0, sticky=W) self.e1 = Entry(master) self.e1.grid(row=0, column=1) self.cb = Checkbutton(master, text="Save to keychain", variable=self.checkVar) self.cb.pack() self.cb.grid(row=1, columnspan=2, sticky=W) self.configure(show='*') def apply(self): self.result = (self.e1.get(), self.checkVar.get() == 1)
class PasswordDialog(Dialog): def __init__(self, title, prompt, parent): self.prompt = prompt Dialog.__init__(self, parent, title) def body(self, master): from Tkinter import Label from Tkinter import Entry from Tkinter import Checkbutton from Tkinter import IntVar from Tkinter import W self.checkVar = IntVar() Label(master, text=self.prompt).grid(row=0, sticky=W) self.e1 = Entry(master) self.e1.grid(row=0, column=1) self.cb = Checkbutton(master, text="Save to keychain", variable=self.checkVar) self.cb.pack() self.cb.grid(row=1, columnspan=2, sticky=W) self.e1.configure(show='*') def apply(self): self.result = (self.e1.get(), self.checkVar.get() == 1)
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 __init__(self, parent=None, picks=[], side=LEFT, anchor=W, default=[]): Frame.__init__(self, parent) self.vars = [] for i,pick in enumerate(picks): var = IntVar() chk = Checkbutton(self, text=pick, variable=var) chk.pack(side=side, anchor=anchor, expand=YES) if i< len(default): var.set(default[i]) self.vars.append(var)
def create_entry(_main_row_, _desc_txt, _def_txt_, t_len, ckbc=None, fn=None): ''' creates a tkinter entry ''' _row_ = Frame(_main_row_) if ckbc <> None and fn <> None: label0 = Label(_row_, width=3, text=" ", anchor='w') cvar = IntVar() label1 = Checkbutton(_row_, width=0, variable=cvar, command=fn, anchor='w') label2 = Label(_row_, width=t_len, text=_desc_txt + " ", anchor='w') ckbc.append([cvar, label1]) else: label0 = Label(_row_, width=3, text=" >", anchor='w') label1 = Label(_row_, width=t_len, text=_desc_txt, anchor='w') label2 = Label(_row_, width=2, text=" :", anchor='w') if type(_def_txt_) == str: Ent_It = Entry(_row_) #, width=13) Ent_It.insert('end', _def_txt_) elif type(_def_txt_) in [list, tuple]: Ent_It = StringVar() aux_ddl = Drop_Down_List( _row_, textvariable=Ent_It, values=tuple(_def_txt_[1]), #state = "readonly" ) aux_ddl.bind("<Key>", lambda e: "break") # Magic Ent_It.set(_def_txt_[0]) finalspace = Label(_row_, width=5, text=" ", anchor='w') # Just packing label0.pack(side='left', padx=1) label1.pack(side='left', padx=6) label2.pack(side='left', padx=0) if type(_def_txt_) == str: Ent_It.pack(side='left', expand=True, fill=X) elif type(_def_txt_) in [list, tuple]: aux_ddl.pack(side='left', expand=True, fill=X) finalspace.pack(side='right', padx=0) _row_.pack(side='top', fill=X, pady=3) # For tracing purposes list appending return Ent_It
def __init__(self,parent=None): Frame.__init__(self,parent) self.parent = parent self.pack() # Pack.config(self) # same as self.pack() ABC.make_widgets(self) Button(self, text='Pop1', command=self.dialog1).pack() enable = {'ID1050': 0, 'ID1106': 0, 'ID1104': 0, 'ID1102': 0} for machine in enable: enable[machine] = Variable() l = Checkbutton(self, text=machine, variable=enable[machine]) l.pack() self.pack()
def create_option_buttons(self): f = self.make_frame("Options") btn = Checkbutton(f, variable=self.engine.revar, text="Regular expression") btn.pack(side="left", fill="both") if self.engine.isre(): btn.invoke() btn = Checkbutton(f, variable=self.engine.casevar, text="Match case") btn.pack(side="left", fill="both") if self.engine.iscase(): btn.invoke() btn = Checkbutton(f, variable=self.engine.wordvar, text="Whole word") btn.pack(side="left", fill="both") if self.engine.isword(): btn.invoke() if self.needwrapbutton: btn = Checkbutton(f, variable=self.engine.wrapvar, text="Wrap around") btn.pack(side="left", fill="both") if self.engine.iswrap(): btn.invoke()
def build_dlg(self): top = self.top label = Label(top, name = 'label', text = _("Please select the object categories whose " "default properties you want to change")) label.pack(side = TOP, anchor = W) frame = Frame(top) frame.pack(side = TOP) self.var_graphics = IntVar(top) if self.category != 'font': self.var_graphics.set(1) button = Checkbutton(frame, text = _("Graphics Objects"), state = (self.category == 'font' and DISABLED or NORMAL), variable = self.var_graphics) button.pack(side = TOP, anchor = W) self.var_text = IntVar(top) if self.category == 'font': self.var_text.set(1) button = Checkbutton(frame, text = _("Text Objects"), state = (self.category == 'line' and DISABLED or NORMAL), variable = self.var_text) button.pack(side = TOP, anchor = W) but_frame = Frame(top) but_frame.pack(side = TOP, fill = BOTH, expand = 1) button = Button(but_frame, text = _("OK"), command = self.ok) button.pack(side = LEFT, expand = 1) button = Button(but_frame, text = _("Cancel"), command = self.cancel) button.pack(side = RIGHT, expand = 1)
def create_std_buttons(self, master, update_from=1): button_frame = Frame(master) button = Checkbutton(button_frame, text=_("Auto Update"), variable=self.var_auto_update) button.pack(side=TOP, expand=1, fill=X) if update_from: button = UpdatedButton(button_frame, text=_("Update From..."), command=self.update_from_object) button.pack(side=TOP, expand=1, fill=X) button = UpdatedButton(button_frame, text=_("Apply"), command=self.do_apply, sensitivecb=self.can_apply) button.pack(side=LEFT, expand=1, fill=X) self.Subscribe(SELECTION, button.Update) button = UpdatedButton(button_frame, text=_("Close"), command=self.close_dlg) button.pack(side=RIGHT, expand=1, fill=X) return button_frame
def create_option_buttons(self): "Fill frame with Checkbuttons bound to SearchEngine booleanvars." f = self.make_frame("Options") btn = Checkbutton(f, anchor="w", variable=self.engine.revar, text="Regular expression") btn.pack(side="left", fill="both") if self.engine.isre(): btn.select() btn = Checkbutton(f, anchor="w", variable=self.engine.casevar, text="Match case") btn.pack(side="left", fill="both") if self.engine.iscase(): btn.select() btn = Checkbutton(f, anchor="w", variable=self.engine.wordvar, text="Whole word") btn.pack(side="left", fill="both") if self.engine.isword(): btn.select() if self.needwrapbutton: btn = Checkbutton(f, anchor="w", variable=self.engine.wrapvar, text="Wrap around") btn.pack(side="left", fill="both") if self.engine.iswrap(): btn.select()
class TimeBase(Frame): """ Base de temps scale_time : controle de la base de temps """ def __init__(self, parent=None): """ Initialisation parent : oscilloscope """ Frame.__init__(self) self.configure(bd=1, relief="sunken") self.parent = parent self.scale_time = Scale(self, length=100, orient="horizontal", label="Temps", showvalue=1, from_=1, to=10, tickinterval=1, command=self.update) self.scale_time.pack(expand="yes", fill="both") # choix d'afficher lissajoux ou pas self.check = Checkbutton(self, text="Afficher lissajou", selectcolor=self.parent.lissajoux.color_XY, command=self.parent.plot_all, variable=self.parent.drawXY, onvalue=1, offvalue=0) self.check.pack(side="top", expand="yes", fill="x") self.check.select() def get_time(self): """ recuperer la valeur courante de la base de temps """ return self.scale_time.get() def update(self, event): """mise a jour de la base de temps""" print("TimeBase.update_time_base()") print("Base de temps : ", self.scale_time.get()) if not isinstance(self.parent, Tk): self.parent.update_time(self.scale_time.get())
def __init__(self, wname='guippy', master=None): Tkinter.Frame.__init__(self, master) self.master.title(wname) self.radio_value = IntVar() self.radio_values = { 'test1': 0, 'test2': 1, 'test3': 2, } self.check_values = { 'test1': BooleanVar(), 'test2': BooleanVar(), 'test3': BooleanVar(), } self.option_value = StringVar() self.entry_value = StringVar() self.result_value = StringVar() self.radio_entry = StringVar() self.check_entry = StringVar() # widgets kwds = {'padx': 3, 'pady': 3, 'side': Tkinter.LEFT} ff = Frame(self) ff.pack(side=Tkinter.TOP, anchor='w') Button(ff, text='apply ', command=self.apply).pack(**kwds) Button(ff, text='reapply').pack(**kwds) ff = Frame(self) ff.pack(side=Tkinter.TOP, anchor='w') for key, val in sorted(self.radio_values.items()): _r = Radiobutton(ff, text=key, variable=self.radio_value, value=val) _r.pack(**kwds) Entry(ff, textvariable=self.radio_entry).pack(**kwds) ff = Frame(self) ff.pack(side=Tkinter.TOP, anchor='c') for key, val in sorted(self.check_values.items()): _w = Checkbutton(ff, text=key, variable=val) _w.pack(**kwds) Entry(ff, textvariable=self.check_entry).pack(**kwds)
def create_type_widgets(self): frm = self._wm['frmType'] self._type_chk = StringVar() chkType = Checkbutton(frm, text='', onvalue=1, offvalue=0, state=NORMAL, variable=self._type_chk, command=self.on_chk_type_click) self._type_chk.set(0) chkType.pack(side=LEFT, padx=8) lbType = Label(frm, text='%s' % LANG_MAP[self._lang]['Type']) lbType.pack(side=LEFT) self._type_var = StringVar() cmbType = ttk.Combobox(frm, width=8, textvariable=self._type_var) cmbType.pack(side=LEFT, padx=4) cmbType['value'] = LANG_MAP[self._lang]['TypeList'] lbStart = Label(frm, text='%s:' % LANG_MAP[self._lang]['Start']) lbStart.pack(side=LEFT, padx=4) self._type_start = StringVar() enStart = Entry(frm, width=8, textvariable=self._type_start) enStart.pack(side=LEFT) lbEnd = Label(frm, text='%s:' % LANG_MAP[self._lang]['End']) lbEnd.pack(side=LEFT, padx=4) self._type_end = StringVar() enEnd = Entry(frm, width=8, textvariable=self._type_end) enEnd.pack(side=LEFT) bnType = Button(frm, text='%s' % LANG_MAP[self._lang]['OK'], width=4, command=self.on_bn_type_click) bnType.pack(side=LEFT, padx=36) cmbType['state'] = DISABLED enStart['state'] = DISABLED enEnd['state'] = DISABLED bnType['state'] = DISABLED self._wm['chkType'] = chkType self._wm['lbType'] = lbType self._wm['lbStart'] = lbStart self._wm['lbEnd'] = lbEnd self._wm['cmbType'] = cmbType self._wm['enStart'] = enStart self._wm['enEnd'] = enEnd self._wm['bnType'] = bnType
class Checked(object): def __init__(self, parent_frame, check_text, set_checked=False, on_check_callback=None, on_uncheck_callback=None): self._checked_value = IntVar(value=1 if set_checked else 0) self._check = Checkbutton(parent_frame, text=check_text, variable=self._checked_value, command=self._on_check, anchor=W, justify=LEFT, width=15) self._check.pack(side=TOP) self._on_check_callback = on_check_callback self._on_uncheck_callback = on_uncheck_callback self._check_text = check_text def _on_check(self): if self._checked_value.get() == 1: #print '%s Checked' % self._check_text if self._on_check_callback: self._on_check_callback() else: #print '%s Un-hecked' % self._check_text if self._on_uncheck_callback: self._on_uncheck_callback() def display(self, show=True): if show: self._check.pack(side=TOP) else: self._check.pack_forget() def get_checked(self): return True if self._checked_value.get() == 1 else False def set_checked(self, is_checked): if is_checked: self._checked_value.set(1) else: self._checked_value.set(0) checked = property(fget=get_checked, fset=set_checked)
def addPage(self, name): page = ttk.Frame(self.panelControl) self.panelControl.add(page, text='signal ' + name) visible_checkbox = Checkbutton(page, text="Afficher") magnitude = Scale(page, length=250, orient="horizontal", label="Amplitude", sliderlength=20, showvalue=0, from_=0, to=5, tickinterval=1, name="magnitudeScale") frequency = Scale(page, length=250, orient="horizontal", label="Frequency", sliderlength=20, showvalue=0, from_=0, to=25, tickinterval=5, name="frequencyScale") phase = Scale(page, length=250, orient="horizontal", label="Phase", sliderlength=20, showvalue=0, from_=0, to=20, tickinterval=5, name="phaseScale") visible_checkbox.pack(fill="x", pady=6) magnitude.pack(expand=1, fill="both", pady=6) frequency.pack(expand=1, fill="both", pady=6) phase.pack(expand=1, fill="both", pady=6) self.panel_control_page.append({ 'visible': visible_checkbox, 'magnitude': magnitude, 'frequency': frequency, 'phase': phase })
def app(): root = Tk() root.geometry("500x500+100+200") lb1 = Label(root, text="I have many head...Choose one:") heads = Radiobutton(root, ) music_cb = Checkbutton(root, text="music") fullscreen_cb = Checkbutton(root, text="fullscreen") #全屏勾选,音乐勾选。 bt1 = Button(root, text="START", command=play_head) bt2 = Button(root, text="MoreHead", command=add_head) music_cb.pack() fullscreen_cb.pack() lb1.pack() bt1.pack() bt2.pack() root.mainloop()
def __init__(self, parent=None, picks=[], side=TOP, anchor=W): Frame.__init__(self, parent) from Tkinter import IntVar, Checkbutton, Button, BOTTOM, TOP from Tkinter import RIGHT, YES import sys self.vars = [] for pick in picks: var = IntVar() var.set(1) # change to 1 to set all checkboxes to true at start chk = Checkbutton(self, text=pick, variable=var) # chk.pack(side=side, anchor=anchor, expand=YES) chk.pack(side=TOP, anchor=anchor, expand=YES) self.vars.append(var) # print(type(self.vars)) self.vars[0].set(0) def combine_funcs(*funcs): def combined_func(*args, **kwargs): for f in funcs: f(*args, **kwargs) return combined_func def allstates(printit): # print(list(calc.state())) # global check # check = list(calc.state()) # check = {} for pick in picks: # check[pick] = calc.state()[picks.index(pick)] # print(picks.index(pick)) check[pick] = self.vars[picks.index(pick)].get() if printit == 1: print(check) return check Buttonframe = Frame(self) Button(Buttonframe, text='QUIT', command=sys.exit).pack(side=RIGHT) Button(Buttonframe, text='OK', command=combine_funcs(lambda: allstates(0), parent.destroy)).pack(side=RIGHT) Buttonframe.pack(side=BOTTOM)
def __init__(self, wname='guippy', master=None): Tkinter.Frame.__init__(self, master) self.master.title(wname) self.radio_value = IntVar() self.radio_values = {'test1': 0, 'test2': 1, 'test3': 2, } self.check_values = {'test1': BooleanVar(), 'test2': BooleanVar(), 'test3': BooleanVar(), } self.option_value = StringVar() self.entry_value = StringVar() self.result_value = StringVar() self.radio_entry = StringVar() self.check_entry = StringVar() # widgets kwds = {'padx':3, 'pady': 3, 'side': Tkinter.LEFT} ff = Frame(self) ff.pack(side=Tkinter.TOP, anchor='w') Button(ff, text='apply ', command=self.apply).pack(**kwds) Button(ff, text='reapply').pack(**kwds) ff = Frame(self) ff.pack(side=Tkinter.TOP, anchor='w') for key, val in sorted(self.radio_values.items()): _r = Radiobutton(ff, text=key, variable=self.radio_value, value=val) _r.pack(**kwds) Entry(ff, textvariable=self.radio_entry).pack(**kwds) ff = Frame(self) ff.pack(side=Tkinter.TOP, anchor='c') for key, val in sorted(self.check_values.items()): _w = Checkbutton(ff, text=key, variable=val) _w.pack(**kwds) Entry(ff, textvariable=self.check_entry).pack(**kwds)
def create_option_buttons(self): '''Return (filled frame, options) for testing. Options is a list of SearchEngine booleanvar, label pairs. A gridded frame from make_frame is filled with a Checkbutton for each pair, bound to the var, with the corresponding label. ''' frame = self.make_frame("Options")[0] engine = self.engine options = [(engine.revar, "Regular expression"), (engine.casevar, "Match case"), (engine.wordvar, "Whole word")] if self.needwrapbutton: options.append((engine.wrapvar, "Wrap around")) for var, label in options: btn = Checkbutton(frame, anchor="w", variable=var, text=label) btn.pack(side="left", fill="both") if var.get(): btn.select() return frame, options
class TrackingGotoSunDialog(Dialog): def __init__(self, parent = None, ): #set up dialog windows Dialog.__init__(self, parent = parent, title = "Tracking Go to Sun", buttons = ('OK',), defaultbutton = 'OK', ) main_frame = self.interior() top_frame = Frame(main_frame) self.seconds_ahead_field = EntryField(top_frame, labelpos = 'w', label_text = "seconds from now:", label_font = FIELD_LABEL_FONT, entry_width = FIELD_ENTRY_WIDTH, value = DEFAULT_SECONDS_AHEAD, validate = Validator(_min=0.0,_max=86400), #entry_state = 'readonly', ) self.seconds_ahead_field.pack(side='left', anchor="w", expand='no') top_frame.pack(side='top') self.delay_then_capture_variable = IntVar() self.delay_then_capture_button = Checkbutton(main_frame, text = "delay then capture", font = FIELD_LABEL_FONT, onvalue = 1, offvalue = 0, variable = self.delay_then_capture_variable, ) self.delay_then_capture_button.pack(side='top') def activate(self): "override activate to construct and send back the action and the new values" action = Dialog.activate(self) return action
def build_dlg(self): top = self.top self.var_style_name = StringVar(top) entry_name = MyEntry(top, textvariable = self.var_style_name, command = self.ok, width = 15) entry_name.pack(side = TOP, fill = X) properties = self.object.Properties() self.flags = {} for prop in property_names: type = property_types[prop] if type == FillProperty: state = self.object.has_fill and NORMAL or DISABLED elif type == LineProperty: state = self.object.has_line and NORMAL or DISABLED elif type == FontProperty: state = self.object.has_font and NORMAL or DISABLED else: # unknown property type! continue long, short = property_titles[prop] self.flags[prop] = var = IntVar(top) var.set(state == NORMAL) radio = Checkbutton(top, text = long, state = state, variable = var) radio.pack(side = TOP, anchor = W) but_frame = Frame(top) but_frame.pack(side = TOP, fill = BOTH, expand = 1) button = Button(but_frame, text = _("OK"), command = self.ok) button.pack(side = LEFT, expand = 1) button = Button(but_frame, text = _("Cancel"), command = self.cancel) button.pack(side = RIGHT, expand = 1) entry_name.focus()
class TimeBase(Frame): """ Base de temps scale_time : controle de la base de temps """ def __init__(self, parent=None): """ Initialisation parent : oscilloscope """ Frame.__init__(self) self.configure(bd=1, relief="sunken") self.parent = parent self.scale_time = Scale(self, length=100, orient="horizontal", label="Temps", showvalue=1, from_=1, to=10, tickinterval=1, command=self.update) self.scale_time.pack(expand="yes", fill="both") # choix d'afficher lissajoux ou pas self.check = Checkbutton(self,text="Afficher lissajou", selectcolor=self.parent.lissajoux.color_XY, command=self.parent.plot_all, variable=self.parent.drawXY, onvalue = 1, offvalue = 0) self.check.pack(side="top",expand="yes", fill="x") self.check.select() def get_time(self): """ recuperer la valeur courante de la base de temps """ return self.scale_time.get() def update(self, event): """mise a jour de la base de temps""" print("TimeBase.update_time_base()") print("Base de temps : ", self.scale_time.get()) if not isinstance(self.parent, Tk): self.parent.update_time(self.scale_time.get())
def __init__(self, wname="guippy", master=None): Tkinter.Frame.__init__(self, master) self.master.title(wname) self.radio_value = IntVar() self.radio_values = {"test1": 0, "test2": 1, "test3": 2} self.check_values = {"test1": BooleanVar(), "test2": BooleanVar(), "test3": BooleanVar()} self.option_value = StringVar() self.entry_value = StringVar() self.result_value = StringVar() self.radio_entry = StringVar() self.check_entry = StringVar() # widgets kwds = {"padx": 3, "pady": 3, "side": Tkinter.LEFT} ff = Frame(self) ff.pack(side=Tkinter.TOP, anchor="w") Button(ff, text="apply ", command=self.apply).pack(**kwds) Button(ff, text="reapply").pack(**kwds) ff = Frame(self) ff.pack(side=Tkinter.TOP, anchor="w") for key, val in sorted(self.radio_values.items()): _r = Radiobutton(ff, text=key, variable=self.radio_value, value=val) _r.pack(**kwds) Entry(ff, textvariable=self.radio_entry).pack(**kwds) ff = Frame(self) ff.pack(side=Tkinter.TOP, anchor="c") for key, val in sorted(self.check_values.items()): _w = Checkbutton(ff, text=key, variable=val) _w.pack(**kwds) Entry(ff, textvariable=self.check_entry).pack(**kwds)
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()
# The fieldname attribute is necessary to provide data to action entry = Entry(form) entry.fieldname = "entry" entry.grid(row=1, column=1, sticky=E + W) Label(form, text="Checkbuttons:").grid(row=2, column=0, sticky=E, pady=(8, 0)) column = Frame(form) column.grid(row=3, column=1, sticky=E + W) checkbutton0 = Checkbutton(column, text="Option 0") checkbutton0.fieldname = "checkbutton0" checkbutton0.pack(side=LEFT) checkbutton1 = Checkbutton(column, text="Option 1") checkbutton1.fieldname = "checkbutton1" checkbutton1.pack(side=LEFT) checkbutton2 = Checkbutton(column, text="Option 2") checkbutton2.fieldname = "checkbutton2" checkbutton2.pack(side=LEFT) Label(form, text="Radiobuttons:").grid(row=4, column=0, sticky=E, pady=(8, 0)) column = Frame(form) column.grid(row=5, column=1, sticky=E + W)
def build_dlg(self): top = self.top # The preview widget self.view = SketchView(top, self.document, width = 200, height = 200, background = 'white') self.view.pack(side = TOP, fill = BOTH, expand = 1) # PostScript Options frame = Frame(top, name = "options") frame.pack(side = TOP, fill = X) # EPS #self.var_create_eps = IntVar(top) #self.var_create_eps.set(1) #button = Checkbutton(frame, text = _("Create EPS file"), # variable = self.var_create_eps) #button.pack(side = LEFT, expand = 1, fill = X) # Rotate self.var_rotate = IntVar(top) self.var_rotate.set(0) button = Checkbutton(frame, text = _("Rotate ccw."), variable = self.var_rotate) button.pack(side = LEFT, expand = 1, fill = X) # Embed fonts self.var_embfnt = IntVar(top) self.var_embfnt.set(0) button = Checkbutton(frame, text = _("Embed fonts"), variable = self.var_embfnt) button.pack(side = LEFT, expand = 1, fill = X) # Print Command and Filename frame = Frame(top, name = "command") frame.pack(side = TOP) self.print_dest = StringVar(top) button = Radiobutton(frame, text = _("Printer"), value = 'printer', variable = self.print_dest, anchor = 'w') button.grid(column = 0,row = 0, sticky = 'ew') label = Label(frame, text = _("Command"), anchor = 'e') label.grid(column = 1, row = 0, sticky = 'ew') self.print_command = StringVar(top) self.print_command.set('lpr') entry = MyEntry(frame, textvariable = self.print_command) entry.grid(column = 2, row = 0, sticky = 'ew') button = Radiobutton(frame, text = _("EPS"), value = 'file', variable = self.print_dest, anchor = 'w') button.grid(column = 0, row = 1, sticky = 'ew') label = Label(frame, text = _("Filename"), anchor = 'e') label.grid(column = 1, row = 1, sticky = 'ew') self.print_filename = StringVar(top) self.print_filename.set('') entry = MyEntry(frame, textvariable = self.print_filename) entry.grid(column = 2, row = 1, sticky = 'ew') button = UpdatedButton(frame, text = _("..."), command = self.get_filename) button.grid(column = 3, row = 1, sticky = 'ew') frame = Frame(top) frame.pack(side = TOP) button = UpdatedButton(frame, text = _("Print"), command = self.do_print) button.pack(side = LEFT) button = UpdatedButton(frame, text = _("Close"), command = self.close_dlg) button.pack(side = LEFT) # init vars self.print_dest.set(config.preferences.print_destination)
class carGUI: carDict = {} carIDs = [] def __init__(self, master): self.master = master master.title("A simple GUI") # Initialize Canvas self.canv = Canvas(master) self.canv.pack(fill='both', expand=True) # Initialize X-Lane self.xTop = self.canv.create_line(0, 470, 1000, 470, fill='black', tags=('top')) self.xBottom = self.canv.create_line(0, 510, 1000, 510, fill='black', tags=('left')) # Initialize Y-Lane self.yLeft = self.canv.create_line(470, 0, 470, 1000, fill='blue', tags='right') self.yRight = self.canv.create_line(510, 0, 510, 1000, fill='blue', tags='bottom') # Highlight Intersection self.rect = self.canv.create_rectangle(470, 470, 510, 510, fill='green') # Show Regulation Lines self.xLimit = self.canv.create_line(470 - 40, 450, 470 - 40, 530, fill="red") self.yLimit = self.canv.create_line(450, 470 - 40, 530, 470 - 40, fill="red") # Create button to begin simulation b = Button(text="Start Simluation!", command=self.simClickListener) b.pack() # Create checkbox to differentiate real world sim from autonomous sim self.CheckVar = IntVar() self.checkConventional = Checkbutton(text="Conventional System", variable=self.CheckVar, \ onvalue=1, offvalue=0, height=5) self.checkConventional.pack() # Create text fields to show first in queue cars self.carDisplayX = self.canv.create_text(10, 10, anchor="nw", fill="red") self.carDisplayY = self.canv.create_text(600, 10, anchor="nw", fill="black") def drawCar(self, lane, ID): if (lane == 1): # Draw an X car self.rect = self.canv.create_rectangle(0, 485, 10, 495, fill='black') elif (lane == 2): # Draw a Y car self.rect = self.canv.create_rectangle(485, 0, 495, 10, fill='red') self.canv.addtag_below(self.rect, "HELLO") # Register the ID of the car self.carIDs.append(ID) # Ad the key value pair to the car dictionary for the GUI self.carDict[ID] = self.rect def moveCars(self, carList, timeInterval): self.master.update_idletasks() # THIS UPDATES THE GUI for i in range(0, len(carList)): self.canv.move(self.carDict[carList[i].ID], carList[i].velocityX * timeInterval, carList[i].velocityY * timeInterval) def highlightCar(self, car, color): self.canv.itemconfig(self.carDict[car.ID], fill=color) def simClickListener(self): from Simulation import simulation as sim sim(self) def updateCarInformationDisplay(self, car): carData = "position X = " + str(car.positionX) + "\nposition Y = " + \ str(car.positionY) + "\nvelocity X = " + str(car.velocityX) + \ "\nvelocity Y = " + str(car.velocityY) if (car.velocityX > 0): self.canv.itemconfig(self.carDisplayX, text=carData) else: self.canv.itemconfig(self.carDisplayY, text=carData)
class Generator(Frame): """ Vibration harmonique du type : e=a*sin(2*pi*f*t+p) scale_A : controleur d'Amplitude scale_F : controleur de Frequence scale_P : controleur de Phase """ def __init__(self, parent, name="X"): """ Initialisation parent : un oscilloscope name : nom du signal """ Frame.__init__(self) self.configure(bd=1, relief="sunken") self.parent = parent self.name = name self.drawVar = IntVar() self.signal = None self.draw = Checkbutton(self,text="Afficher "+self.name, selectcolor=eval('self.parent.view.color_'+name), variable=self.drawVar, onvalue = 1, offvalue = 0, command=self.parent.plot_all) self.draw.pack() self.draw.select() self.scale_A = Scale(self, length=100, orient="horizontal", label=name + " Amplitude", showvalue=1, from_=0, to=10, tickinterval=1, command=self.update_signal) self.scale_A.pack(expand="yes", fill="both") self.scale_F = Scale(self, length=100, orient="horizontal", label=name + " Fréquence", showvalue=1, from_=1, to=10, tickinterval=1, command=self.update_signal) self.scale_F.pack(expand="yes", fill="both") self.scale_P = Scale(self, length=100, orient="horizontal", label=name + " Phase", showvalue=1, from_=0, to=10, tickinterval=1, command=self.update_signal) self.scale_P.pack(expand="yes", fill="both") self.bind("<Configure>",self.update_signal) def update_signal(self, event): """ Mise a jour de signal si modifications (amplitude, frequence, phase) """ print("Vibration.update_signal()") print("Amplitude :", self.scale_A.get()) scaling=0.05 amp = scaling*self.scale_A.get() signal = self.generate_signal(a=amp,f=self.scale_F.get(), p=self.scale_P.get()) self.signal = signal if not isinstance(self.parent, Tk): self.parent.update_view(self.name, signal) self.parent.plot_all() return signal def generate_signal(self, a=1.0, f=2.0, p=0): """ Calcul de l'elongation : e=a*sin(2*pi*f*t+p) sur une periode a : amplitude f : frequence p : phase """ signal = [] samples = 1000 for t in range(0, samples): samples = float(samples) e = a * sin((2*pi*f*(t/samples)) - p) signal.append((t/samples,e)) return signal
class ToolBar(Frame): def __init__(self, root, printer, settings, logger, *arg): self.app = root self.printer = printer self.settings = settings self.logger = logger self.app.printing = False self.app.connected = False self.app.paused = False Frame.__init__(self, root, *arg) topBar = Frame(self) topBar.grid(row=1, column=1, columnspan=3, sticky=W) speedBar = Frame(self) speedBar.grid(row=1, column=5, sticky=E) bottomBar = Frame(self) bottomBar.grid(row=2, column=1, columnspan=6, sticky=W+E) self.bPort = Button(topBar, text="Port", width=BWIDTH, command=self.doPort) self.bPort.pack(side=LEFT, padx=2, pady=2) ports = self.scanSerial() self.spPort = Spinbox(topBar, values=ports, state="readonly") self.spPort.pack(side=LEFT, padx=2, pady=2) l = Label(topBar, text=" @ ") l.pack(side=LEFT, padx=2, pady=2) self.spBaud = Spinbox(topBar, values=baudChoices) self.spBaud.pack(side=LEFT, padx=2, pady=2) self.spBaud.delete(0, END) self.spBaud.insert(0, 115200) self.spBaud.config(state="readonly") self.bConnectMode = CM_CONNECT self.bConnect = Button(topBar, text=connectText[CM_CONNECT], width=BWIDTH, command=self.doConnect) self.bConnect.pack(side=LEFT, padx=2, pady=2) if len(ports) == 0: self.bConnect.config(state=DISABLED) else: self.bConnect.config(state=NORMAL) self.bReset = Button(topBar, text="Reset", width=BWIDTH, command=self.doReset, state=DISABLED) self.bReset.pack(side=LEFT, padx=2, pady=2) l = Label(speedBar, text="Speed:", justify=RIGHT) l.grid(row=1, column=1, sticky=E) self._speedJob = None self.currentSpeed = self.app.FeedMultiply self.scSpeed = Scale(speedBar, from_=MINSPEED, to=MAXSPEED, orient=HORIZONTAL, command=self.updateSpeedCommand) self.scSpeed.grid(row=1, column=2) self.scSpeed.set(self.currentSpeed); l = Label(speedBar, text="Fan:", width=10, anchor=E, justify=RIGHT) l.grid(row=1, column=3, sticky=E) self._fanJob = None self.currentFanSpeed = self.app.FanSpeed self.scFan = Scale(speedBar, from_=0, to=255, orient=HORIZONTAL, command=self.updateFanSpeedCommand) self.scFan.grid(row=1, column=4) self.scFan.set(self.currentFanSpeed); if self.settings.speedcommand is not None: self.cbvAssertFan = IntVar() if self.settings.forcefanspeed: self.cbvAssertFan.set(1) else: self.cbvAssertFan.set(0) self.cbAssertFan = Checkbutton(speedBar, text="Force", variable=self.cbvAssertFan, command=self.clickAssertFan) self.cbAssertFan.grid(row=1, column=5) self.bSliceMode = SM_SLICE self.bSlice = Button(bottomBar, text=sliceText[SM_SLICE], width=BWIDTH*2, command=self.doSlice) self.bSlice.pack(side=LEFT, padx=2, pady=2) self.bLoad = Button(bottomBar, text="Load GCode", width=BWIDTH, command=self.doLoad) self.bLoad.pack(side=LEFT, padx=2, pady=2) self.setSliceText() self.bSD = Button(bottomBar, text="SD", width=BWIDTH, command=self.doSD, state=DISABLED) self.bSD.pack(side=LEFT, padx=2, pady=2) self.bPrintMode = PR_PRINT self.bPrint = Button(bottomBar, text=printText[PR_PRINT], width=BWIDTH, command=self.doPrint, state=DISABLED) self.bPrint.pack(side=LEFT, padx=2, pady=2) self.bPauseMode = PM_PAUSE self.bPause = Button(bottomBar, text=pauseText[PM_PAUSE], width=BWIDTH, command=self.doPause, state=DISABLED) self.bPause.pack(side=LEFT, padx=2, pady=2) self.bAbandon = Button(bottomBar, text="Abandon SD Print", width=BWIDTH+8, command=self.doAbandon, state=DISABLED) self.bAbandon.pack(side=LEFT, padx=2, pady=2) self.cbvLiftOnPause = IntVar() if self.settings.liftonpause: self.cbvLiftOnPause.set(1) else: self.cbvLiftOnPause.set(0) self.cbLiftOnPause = Checkbutton(bottomBar, text="Lift Head/Retract on Pause", variable=self.cbvLiftOnPause, command=self.clickLiftOnPause) self.cbLiftOnPause.pack(side=LEFT, padx=2) self.cbvResumeAtPause = IntVar() if self.settings.resumeatpausepoint: self.cbvResumeAtPause.set(1) else: self.cbvResumeAtPause.set(0) self.cbResumeAtPause = Checkbutton(bottomBar, text="Resume print at pause point", variable=self.cbvResumeAtPause, command=self.clickResumeAtPause) self.cbResumeAtPause.pack(side=LEFT, padx=2) def clickAssertFan(self): if self.cbvAssertFan.get() == 1: self.settings.forcefanspeed = True self.settings.setModified() else: self.settings.forcefanspeed = False self.settings.setModified() def clickLiftOnPause(self): if self.cbvLiftOnPause.get() == 1: self.settings.liftonpause = True self.settings.setModified() else: self.settings.liftonpause = False self.settings.setModified() def clickResumeAtPause(self): if self.cbvResumeAtPause.get() == 1: self.settings.resumeatpausepoint = True self.settings.setModified() else: self.settings.resumeatpausepoint = False self.settings.setModified() def setSliceText(self): if self.settings.slicer == SLIC3R: sl = "slic3r:%s" % self.app.slic3r.getProfile() else: sl = "skeinforge:%s" % self.app.skeinforge.getProfile() sliceText[SM_SLICE] = "Slice (%s)" % sl if self.bSliceMode == SM_SLICE: self.bLoad.config(state=NORMAL) self.app.allowLoadGCodeMenu(True) lt = len(sliceText[SM_SLICE])+2 if lt < BWIDTH: lt = BWIDTH self.bSlice.config(text=sliceText[SM_SLICE], width=lt) def updateSpeedCommand(self, *arg): if self._speedJob: self.app.master.after_cancel(self._speedJob) self._speedJob = self.app.master.after(500, self.updateSpeed) def updateSpeed(self, *arg): v = self.scSpeed.get() self.setSpeed(v) def setSpeed(self, v): if v < MINSPEED or v > MAXSPEED: self.logger.logMsg("Attempt to change speed outside of allowable range (%d-%d)" % (MINSPEED, MAXSPEED)) elif int(v) != self.currentSpeed: if self.app.connected: self.currentSpeed = int(v) self.logger.logMsg("changing speed percentage to %d%%" % self.currentSpeed) cmd = "M220 S%d" % self.currentSpeed self.printer.send_now(cmd) else: self.logger.logMsg("Printer is off-line") self.scSpeed.set(self.currentSpeed) def updateFanSpeedCommand(self, *arg): if self._fanJob: self.app.master.after_cancel(self._fanJob) self._fanJob = self.app.master.after(500, self.updateFanSpeed) def updateFanSpeed(self, *arg): v = self.scFan.get() self.setFanSpeed(v) self.app.FanSpeed = v def forceFanSpeed(self, v): self.currentFanSpeed = -1 self.setFanSpeed(v) def setFanSpeed(self, v): if int(v) != self.currentFanSpeed: if self.app.connected: self.currentFanSpeed = int(v) cmd = "M106 S%d" % self.currentFanSpeed self.printer.send_now(cmd) else: self.logger.logMsg("Printer is off-line") self.scFan.set(self.currentFanSpeed) def syncSpeeds(self): self.currentSpeed = self.app.FeedMultiply self.scSpeed.set(self.currentSpeed) self.currentFanSpeed = self.app.FanSpeed self.scFan.set(self.currentFanSpeed) def initializeToolbar(self): self.bReset.config(state=DISABLED) self.bSliceMode = SM_SLICE self.bSlice.config(text=sliceText[SM_SLICE]) self.bLoad.config(state=NORMAL) self.app.allowLoadGCodeMenu(True) if not self.app.sdprinting and not self.app.sdpaused: self.bPrintMode = PR_PRINT self.bPrint.config(text=printText[PR_PRINT], state=DISABLED) self.bPauseMode = PM_PAUSE self.bPause.config(text=pauseText[PM_PAUSE], state=DISABLED) def setSDPrint(self): self.bPause.config(text=pauseText[PM_PAUSE], state=NORMAL) self.bPauseMode = PM_PAUSE self.bPrint.config(text=printText[PR_PRINT], state=DISABLED) self.bPrintMode = PR_PRINT self.bAbandon.config(state=NORMAL) def clearSDPrint(self): self.bPause.config(text=pauseText[PM_PAUSE], state=DISABLED) self.bPauseMode = PM_PAUSE self.bPrint.config(text=printText[PR_PRINT], state=DISABLED) self.bPrintMode = PR_PRINT self.bAbandon.config(state=DISABLED) self.checkAllowPrint() def setCancelMode(self): self.bSliceMode = SM_CANCEL self.bSlice.config(text=sliceText[SM_CANCEL], width=BWIDTH) self.bLoad.config(state=DISABLED) self.app.allowLoadGCodeMenu(False) self.app.allowSliceMenu(False) def setLoading(self, flag): if flag: self.bLoad.config(state=DISABLED) self.bSlice.config(state=DISABLED) self.app.allowLoadGCodeMenu(False) self.app.allowSliceMenu(False) else: self.bLoad.config(state=NORMAL) self.bSlice.config(state=NORMAL) self.app.allowLoadGCodeMenu(True) self.app.allowSliceMenu(True) def clearCancelMode(self): self.bSliceMode = SM_SLICE lt = len(sliceText[SM_SLICE])+2 if lt < BWIDTH: lt = BWIDTH self.bSlice.config(text=sliceText[SM_SLICE], width=lt) self.bLoad.config(state=NORMAL) self.app.allowLoadGCodeMenu(True) self.app.allowSliceMenu(True) def doConnect(self): if self.bConnectMode == CM_CONNECT: port = self.spPort.get() baud = int(self.spBaud.get()) self.printer.onlinecb = self.onlinecb try: self.printer.connect(port, baud) except SerialException: self.logger.logMsg("Unable to open printer port %s" % port) else: if self.app.printing: self.logger.logMsg("Please wait until printing has finished or is paused") else: self.printer.disconnect() self.printer.onlinecb = None self.app.printerConnected(False) # self.app.connected = False self.bConnectMode = CM_CONNECT self.bConnect.config(text=connectText[CM_CONNECT]) self.bReset.config(state=DISABLED) self.bSD.config(state=DISABLED) if self.app.paused: self.bPrint.config(text=printText[PR_PRINT], state=DISABLED) self.bPrintMode = PR_PRINT self.bPause.config(text=pauseText[PM_PAUSE], state=DISABLED) self.bPauseMode = PM_PAUSE self.app.printing = False self.app.paused = False def doReset(self): if tkMessageBox.askyesno("Reset?", "Are you sure you want to reset the printer?", parent=self.app): self.printer.reset() self.printer.printing = 0 self.app.printing = False self.bSlice.config(state=NORMAL) self.bLoad.config(state=NORMAL) self.app.allowLoadGCodeMenu(True) self.app.allowSliceMenu(True) self.bPrintMode = PR_PRINT self.bPrint.config(text=printText[PR_PRINT], state=NORMAL) if self.app.paused: self.printer.paused = 0 self.bPause.config(text=pauseText[PM_PAUSE], state=DISABLED) self.bPauseMode = PM_PAUSE self.app.paused = False def onlinecb(self): self.logger.logMsg("Printer is on-line") self.app.printerConnected(True) # self.app.connected = True self.bConnectMode = CM_DISCONNECT self.bConnect.config(text=connectText[CM_DISCONNECT]) self.bReset.config(state=NORMAL) self.bSD.config(state=NORMAL) self.checkAllowPrint() def checkAllowPrint(self): if self.app.connected and len(self.app.gcode) != 0 and not self.app.printing and not self.app.sdprinting: self.bPrint.config(text=printText[PR_PRINT], state=NORMAL) self.bPrintMode = PR_PRINT def printComplete(self): self.app.endTime = time.time() self.app.elapsedTime = self.app.endTime - self.app.startTime self.logger.logMsg("Printing completed at %s" % time.strftime('%H:%M:%S', time.localtime())) self.logger.logMsg("Total elapsed time: %s" % formatElapsed(self.app.elapsedTime)) self.bPrintMode = PR_PRINT self.bPrint.config(text=printText[PR_PRINT], state=NORMAL) self.bPauseMode = PM_PAUSE self.bPause.config(text=pauseText[PM_PAUSE], state=DISABLED) self.app.printing = False self.bSlice.config(state=NORMAL) self.bLoad.config(state=NORMAL) self.app.allowLoadGCodeMenu(True) self.app.allowSliceMenu(True) self.app.paused = False self.app.gc.updatePrintProgress(0) self.app.closeAllReports() if self.settings.endprintmacro is not None: self.app.doMacro(name=self.settings.endprintmacro, silent=True) def doPause(self): if self.bPauseMode == PM_PAUSE: if self.app.printing: self.app.paused = True self.printer.pause() elif self.app.sdprinting: self.app.sdpaused = True self.printer.send_now("M25") self.app.sdprinting = False self.bPause.config(text=pauseText[PM_RESUME]) self.bPauseMode = PM_RESUME self.bPrint.config(text=printText[PR_RESTART], state=NORMAL) self.bPrintMode = PR_RESTART else: if self.app.sdpaused: self.printer.send_now("M24") self.app.sdpaused = False self.app.sdprinting = True self.bPause.config(text=pauseText[PM_PAUSE]) self.bPauseMode = PM_PAUSE self.bPrint.config(text=printText[PR_PRINT], state=DISABLED) self.bPrintMode = PR_PRINT else: self.hitPrint = False if self.settings.resumeatpausepoint: self.printer.send_now("G1 X%s Y%s F%s" % (self.app.pausePoint[XAxis], self.app.pausePoint[YAxis], self.settings.xyfeed)) self.printer.send_now("G1 Z%s F%s" % (self.app.pausePoint[ZAxis], self.settings.zfeed)) self.printer.send_now("G92 E%s" % self.app.pausePoint[EAxis]) self.printer.send_now("G1 F%s" % self.settings.xyfeed) self.printer.startcb = self.startcb self.printer.resume() def doAbandon(self): self.printer.send_now("M25") self.app.sdpaused = False self.app.sdprinting = False self.clearSDPrint() def doSlice(self): if self.bSliceMode == SM_SLICE: self.bLoad.config(state=DISABLED) self.app.allowLoadGCodeMenu(False) self.app.openSTLFile() else: self.app.slicerCancel = True self.bLoad.config(state=NORMAL) self.app.allowLoadGCodeMenu(True) def doLoad(self): self.app.openGCodeFile() def doPrint(self): if self.app.sdpaused: self.printer.send_now("M26 S0") self.printer.send_now("M24") self.app.sdpaused = False self.app.sdprinting = True self.bPause.config(text=pauseText[PM_PAUSE]) self.bPauseMode = PM_PAUSE self.bPrint.config(text=printText[PR_PRINT], state=DISABLED) self.bPrintMode = PR_PRINT else: if len(self.app.gcode) == 0: self.logger.logMsg("Nothing to print") else: #if not self.app.paused: self.app.gc.updatePrintProgress(0, restart=True) self.bPauseMode = PM_PAUSE self.bPause.config(text=pauseText[PM_PAUSE], state=NORMAL) self.hitPrint = True self.printer.startcb = self.startcb self.printer.startprint(self.app.gcode) def startcb(self): self.printer.startcb = None if not self.app.paused: self.app.startTime = time.time() self.logger.logMsg("Printing Started at %s" % time.strftime('%H:%M:%S', time.localtime(self.app.startTime))) self.app.printing = True self.bSlice.config(state=DISABLED) self.bLoad.config(state=DISABLED) self.app.allowLoadGCodeMenu(False) self.app.allowSliceMenu(False) self.bPrint.config(text=printText[PR_RESTART], state=DISABLED) self.bPrintMode = PR_RESTART self.printer.endcb = self.endcb else: if self.hitPrint: self.app.startTime = time.time() self.logger.logMsg("Printing restarted at %s" % time.strftime('%H:%M:%S', time.localtime())) else: self.logger.logMsg("Printing resumed at %s" % time.strftime('%H:%M:%S', time.localtime())) self.bPause.config(text=pauseText[PM_PAUSE]) self.bPauseMode = PM_PAUSE self.app.printing = True self.bSlice.config(state=DISABLED) self.bLoad.config(state=DISABLED) self.app.allowLoadGCodeMenu(False) self.app.allowSliceMenu(False) self.app.paused = False self.bPrint.config(state=DISABLED) self.printer.endcb = self.endcb def endcb(self): self.printer.endcb = None if not self.app.paused: self.printComplete() if self.app.sduploading: self.app.sduploading = False self.printer.send_now("M29") else: self.app.event_generate(MWM_REQUESTPOSITIONREPORT) # record the current printer position and how many intervals were willing to wait fo the response self.maxWait114 = MAXWAIT114; self.waitPos = self.printer.queueindex self.check114Response() def check114Response(self) : # tick off 1 interval, and make sure we haven't either received the report or we've waited max intervals self.maxWait114 -= 1 if self.app.m114count == 0 or self.maxWait114 <= 0: # one way or the other we're done waiting here if self.maxWait114 <= 0: self.app.m114count = 0 self.logger.logMsg("Location report not received - proceeding") self.app.pausePoint[XAxis] = self.app.location[XAxis] self.app.pausePoint[YAxis] = self.app.location[YAxis] self.app.pausePoint[ZAxis] = self.app.location[ZAxis] self.app.pausePoint[EAxis] = self.app.location[EAxis] self.logger.logMsg("Pause location: X:%f Y:%f Z:%f E:%f" % (self.app.pausePoint[XAxis], self.app.pausePoint[YAxis], self.app.pausePoint[ZAxis], self.app.pausePoint[EAxis])) if self.settings.liftonpause: self.printer.send_now("G1 E%s F%s" % (self.app.pausePoint[EAxis]-2, self.settings.efeed)) self.printer.send_now("G1 Z%s F%s" % (self.app.pausePoint[ZAxis]+10, self.settings.zfeed)) self.bPause.config(text=pauseText[PM_RESUME]) self.bPauseMode = PM_RESUME self.app.printing = False self.bSlice.config(state=NORMAL) self.bLoad.config(state=NORMAL) self.app.allowLoadGCodeMenu(True) self.app.allowSliceMenu(True) if self.app.sduploading: self.bPrint.config(text=printText[PR_PRINT], state=DISABLED) self.bPrintMode = PR_PRINT else: self.bPrint.config(text=printText[PR_RESTART], state=NORMAL) self.bPrintMode = PR_RESTART else: # we still are waiting for the report, but reset everything if the printer is still moving if self.waitPos != self.printer.queueindex: self.waitPos = self.printer.queueindex self.maxWait114 = MAXWAIT114 self.app.master.after(500, self.check114Response) def doPort(self): l = self.scanSerial() self.spPort.config(values=l) if len(l) == 0: self.bConnect.config(state=DISABLED) else: self.bConnect.config(state=NORMAL) def scanSerial(self): """scan for available ports. return a list of device names.""" baselist=[] if os.name=="nt": try: key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM") i=0 while(1): baselist+=[_winreg.EnumValue(key,i)[1]] i+=1 except: pass return baselist+glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*') +glob.glob("/dev/tty.*")+glob.glob("/dev/cu.*")+glob.glob("/dev/rfcomm*") def doSD(self): self.app.doSD()
class sideWindow(AppShell): ################################################################# # sideWindow(AppShell) # This class will open a side window wich contains a scene graph and # a world setting page. ################################################################# appversion = '1.0' appname = 'Navigation Window' frameWidth = 325 frameHeight = 580 frameIniPosX = 0 frameIniPosY = 110 padx = 0 pady = 0 lightEnable = 0 ParticleEnable = 0 basedriveEnable = 0 collision = 0 backface = 0 texture = 1 wireframe = 0 enableBaseUseDrive = 0 def __init__(self, worldColor,lightEnable,ParticleEnable, basedriveEnable,collision, backface, texture, wireframe, grid, widgetVis, enableAutoCamera, parent = None, nodePath = render, **kw): self.worldColor = worldColor self.lightEnable = lightEnable self.ParticleEnable = ParticleEnable self.basedriveEnable = basedriveEnable self.collision = collision self.backface = backface self.texture = texture self.wireframe = wireframe self.grid = grid self.enableAutoCamera = enableAutoCamera self.widgetVis = widgetVis # Define the megawidget options. optiondefs = ( ('title', self.appname, None), ) self.defineoptions(kw, optiondefs) if parent == None: self.parent = Toplevel() else: self.parent = parent AppShell.__init__(self, self.parent) self.parent.geometry('%dx%d+%d+%d' % (self.frameWidth, self.frameHeight,self.frameIniPosX,self.frameIniPosY)) self.parent.resizable(False,False) ## Disable the ability to resize for this Window. def appInit(self): print '----SideWindow is Initialized!!' def createInterface(self): # The interior of the toplevel panel interior = self.interior() mainFrame = Frame(interior) ## Creat NoteBook self.notebookFrame = Pmw.NoteBook(mainFrame) self.notebookFrame.pack(fill=Tkinter.BOTH,expand=1) sgePage = self.notebookFrame.add('Tree Graph') envPage = self.notebookFrame.add('World Setting') self.notebookFrame['raisecommand'] = self.updateInfo ## Tree Grapgh Page self.SGE = seSceneGraphExplorer.seSceneGraphExplorer( sgePage, nodePath = render, scrolledCanvas_hull_width = 270, scrolledCanvas_hull_height = 570) self.SGE.pack(fill = Tkinter.BOTH, expand = 0) ## World Setting Page envPage = Frame(envPage) pageFrame = Frame(envPage) self.LightingVar = IntVar() self.LightingVar.set(self.lightEnable) self.LightingButton = Checkbutton( pageFrame, text = 'Enable Lighting', variable = self.LightingVar, command = self.toggleLights) self.LightingButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.CollisionVar = IntVar() self.CollisionVar.set(self.collision) self.CollisionButton = Checkbutton( pageFrame, text = 'Show Collision Object', variable = self.CollisionVar, command = self.showCollision) self.CollisionButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.ParticleVar = IntVar() self.ParticleVar.set(self.ParticleEnable) self.ParticleButton = Checkbutton( pageFrame, text = 'Show Particle Dummy', variable = self.ParticleVar, command = self.enableParticle) self.ParticleButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.baseUseDriveVar = IntVar() self.baseUseDriveVar.set(self.basedriveEnable) self.baseUseDriveButton = Checkbutton( pageFrame, text = 'Enable base.usedrive', variable = self.baseUseDriveVar, command = self.enablebaseUseDrive) self.baseUseDriveButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.backfaceVar = IntVar() self.backfaceVar.set(self.backface) self.backfaceButton = Checkbutton( pageFrame, text = 'Enable BackFace', variable = self.backfaceVar, command = self.toggleBackface) self.backfaceButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.textureVar = IntVar() self.textureVar.set(self.texture) self.textureButton = Checkbutton( pageFrame, text = 'Enable Texture', variable = self.textureVar, command = self.toggleTexture) self.textureButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.wireframeVar = IntVar() self.wireframeVar.set(self.wireframe) self.wireframeButton = Checkbutton( pageFrame, text = 'Enable Wireframe', variable = self.wireframeVar, command = self.toggleWireframe) self.wireframeButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.gridVar = IntVar() self.gridVar.set(self.grid) self.gridButton = Checkbutton( pageFrame, text = 'Enable Grid', variable = self.gridVar, command = self.toggleGrid) self.gridButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.widgetVisVar = IntVar() self.widgetVisVar.set(self.widgetVis) self.widgetVisButton = Checkbutton( pageFrame, text = 'Enable WidgetVisible', variable = self.widgetVisVar, command = self.togglewidgetVis) self.widgetVisButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.enableAutoCameraVar = IntVar() self.enableAutoCameraVar.set(self.enableAutoCamera) self.enableAutoCameraButton = Checkbutton( pageFrame, text = 'Enable Auto Camera Movement for Loading Objects', variable = self.enableAutoCameraVar, command = self.toggleAutoCamera) self.enableAutoCameraButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.backgroundColor = ColorEntry( pageFrame, text = 'BG Color', value=self.worldColor) self.backgroundColor['command'] = self.setBackgroundColorVec self.backgroundColor['resetValue'] = [0,0,0,0] self.backgroundColor.pack(side=Tkinter.LEFT, expand=False) self.bind(self.backgroundColor, 'Set background color') pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) envPage.pack(expand=False) ## Set all stuff done self.notebookFrame.setnaturalsize() mainFrame.pack(fill = 'both', expand = 1) def createMenuBar(self): # We don't need menu bar here. self.menuBar.destroy() def onDestroy(self, event): ################################################################# # onDestroy(self, event) # This function will be called when user closed the side window. # Here we will send out a message with whole data set we will need # for the next time user open the side window. ################################################################# messenger.send('SW_close',[self.worldColor, self.lightEnable, self.ParticleEnable, self.basedriveEnable, self.collision, self.backface, self.texture, self.wireframe, self.grid, self.widgetVis, self.enableAutoCamera]) ''' If you have open any thing, please rewrite here! ''' pass ############################### def updateInfo(self, page = 'Tree Graph'): ################################################################# # updateInfo(self, page = 'Tree Graph') # This function will be called when each time user change the main # page of the window. # What it dose is to call right function to restore the data for current selected page. ################################################################# if page=='Tree Graph': self.updateTreeGraph() elif page == 'World Setting': self.updateWorldSetting() def updateTreeGraph(self): ################################################################# # updateTreeGraph(self) # When scene graoh page has been opend, call sceneGraphExplorer to # updata the tree. ################################################################# self.SGE.update() pass def updateWorldSetting(self): ################################################################# # updateWorldSetting(self) # When world setting page has been selected, this function will # reset those check box in the page to reflect the current world setting. ################################################################# self.LightingVar.set(self.lightEnable) self.CollisionVar.set(self.collision) self.ParticleVar.set(self.ParticleEnable) self.baseUseDriveVar.set(self.basedriveEnable) self.backgroundColor.set(value = self.worldColor) pass def toggleLights(self): ################################################################# # toggleLights(self) # send out a message to let sceneEditor know we need to toggle the light. # Then, sceneEditor will pass the message to dataHolder to disable/enable # the lights. (lightManager is inside the dataHolder) ################################################################# self.lightEnable = (self.lightEnable+1)%2 messenger.send('SW_lightToggle') pass def showCollision(self): ################################################################# # showCollision(self) # This function will send out a message to sceneEditor to toggle # the visibility of collision objects. ################################################################# self.collision = (self.collision+1)%2 messenger.send('SW_collisionToggle', [self.collision]) pass def enableParticle(self): ################################################################# # enableParticle(self) # This function will send out a message to sceneEditor to toggle # the visibility of particle objects. ################################################################# self.ParticleEnable = (self.ParticleEnable+1)%2 messenger.send('SW_particleToggle', [self.ParticleEnable]) pass def enablebaseUseDrive(self): ################################################################# # enablebaseUseDrive(self) # This function will toggle the usage of base.useDrive. # Well, it may not usefull at all. # # We won't send out any message in this time to notice # the sceneEditor this event happend. # In the other hand, we will restore it back when # the side window has been closed. # ################################################################# if self.enableBaseUseDrive==0: print 'Enabled' base.useDrive() self.enableBaseUseDrive = 1 else: print 'disabled' #base.useTrackball() base.disableMouse() self.enableBaseUseDrive = 0 self.basedriveEnable = (self.basedriveEnable+1)%2 pass def toggleBackface(self): ################################################################# # toggleBackface(self) # This function will toggle the back face setting. so it will # render the polygon with two sides. ################################################################# base.toggleBackface() self.backface = (self.backface+1)%2 return def toggleBackfaceFromMainW(self): ################################################################# # toggleBackfaceFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the back face setting in the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.backface = (self.backface+1)%2 self.backfaceButton.toggle() return def toggleTexture(self): ################################################################# # toggleTexture(self) # This function will toggle the txture using option for the whole scene. ################################################################# base.toggleTexture() self.texture = (self.texture+1)%2 return def toggleTextureFromMainW(self): ################################################################# # toggleTextureFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the texture usage from the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.texture = (self.texture+1)%2 self.textureButton.toggle() return def toggleWireframe(self): ################################################################# # toggleWireframe(self) # This function will toggle the wire frame mode. ################################################################# base.toggleWireframe() self.wireframe = (self.wireframe+1)%2 return def toggleWireframeFromMainW(self): ################################################################# # toggleWireframeFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the wire frame mode in the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.wireframe = (self.wireframe+1)%2 self.wireframeButton.toggle() return def toggleGrid(self): ################################################################# # toggleGrid(self) # This function will toggle the usage of the grid. ################################################################# self.grid = (self.grid+1)%2 if self.grid==1: SEditor.grid.enable() else: SEditor.grid.disable() def togglewidgetVis(self): ################################################################# # togglewidgetVis(self) # This function will toggle the visibility of the widget of the grid. ################################################################# self.widgetVis = (self.widgetVis+1)%2 SEditor.toggleWidgetVis() if SEditor.widget.fActive: messenger.send('shift-f') return def toggleWidgetVisFromMainW(self): ################################################################# # toggleWidgetVisFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the visibility of widgets ('v') from the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.widgetVis = (self.widgetVis+1)%2 self.widgetVisButton.toggle() return def setBackgroundColorVec(self,color): ################################################################# # setBackgroundColorVec(self,color) # Call back function # This will be called from the colorEntry on the world setting page. # The "color" here is a list containing three integer data, R, G and B. ################################################################# base.setBackgroundColor(color[0]/255.0, color[1]/255.0, color[2]/255.0) self.worldColor = [color[0],color[1],color[2],0] def toggleAutoCamera(self): ################################################################# # toggleAutoCamera(self) # This function will toggle the usage of the auto-camera movement # when user loaded model or actor into the scene. ################################################################# self.enableAutoCamera = (self.enableAutoCamera+1)%2 SEditor.toggleAutoCamera() return def selectPage(self,page='Tree Graph'): ################################################################# ################################################################# self.notebookFrame.selectpage(page)
def start(): #CREATE THE WINDOW global prefstr window = Tkinter.Tk() screen_width = window.winfo_screenwidth() # width of the screen screen_height = window.winfo_screenheight() # height of the screen window.title("EvE Route Optimizer") window.geometry('%dx%d+%d+%d' % (680, 640, (screen_width / 2) - 340, (screen_height / 2) - 320)) window.configure(background='gray') result = ScrolledText.ScrolledText(window, width=60, height=20) result.configure(font=("Arial Bold", 12), fg="white") result.configure(background='black') start_field = Entry(window, width=37, font=("Arial Bold", 12)) end_field = Entry(window, width=37, font=("Arial Bold", 12)) fixed_end_field = Entry(window, width=37, font=("Arial Bold", 12)) iteration_field = Entry(window, width=6, font=("Arial Bold", 12)) start_field.insert(0, "Origin") end_field.insert(0, "Destination") fixed_end_field.insert(0, "Fixed End Point") iteration_field.insert(0, "Cycles") result.pack() start_field.pack() end_field.pack() fixed_end_field.pack() iteration_field.pack() fixed_end_field.configure(state=DISABLED) try: version_url = "https://sites.google.com/site/ustleveonline/route_optimizer_version" version_response = urllib.urlopen(version_url).read() local_version_file = open("route_optimizer_version", "r") local_version = local_version_file.read() if str(local_version) != str(version_response): result.insert( INSERT, "\nAn update for EvE Route Optimizer is available.\n") result.see("end") webbrowser.open( "https://sites.google.com/site/ustleveonline/route-optimizer", new=1, autoraise=True) else: result.insert(INSERT, "\nEvE Route Optimizer is up to date.\n") result.see("end") except: result.insert(INSERT, "\n" + "ERROR: Please check your internet connection!") result.see("end") #ADD A WAYPOINT def add_waypoint(Event=None): global o_system global d_system global waypoint_adding_done waypoint_adding_done = False o_system = start_field.get() d_system = end_field.get() if (o_system != "" and d_system != "" and o_system != "Origin" and d_system != "Destination"): try: number_of_routes = len(routes) start_field.delete(0, 'end') end_field.delete(0, 'end') start_field.insert(0, d_system) create_route(False) if len(routes) > number_of_routes: result.insert( INSERT, "\n" + "Added Route: " + o_system + " to " + d_system) result.see("end") else: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") waypoint_adding_done = True except: result.insert(INSERT, "\n" + "ERROR: Invalid!") result.see("end") #CREATE ROUTE USING GIVEN WAYPOINTS def create_route(optimizing): global routes global waypoints global o_system global d_system global prefstr #GET ORIGIN ID try: o_base = "https://esi.evetech.net/latest/search/?categories=solar_system&search=" o_end = "&strict=true" o_url = o_base + o_system + o_end o_response = urllib.urlopen(o_url).read() o_split_response = o_response.split(":") o_id_section = o_split_response[1] o_id_leftbracket = o_id_section.replace('[', '') o_id_rightbracket = o_id_leftbracket.replace(']', '') o_id_final = o_id_rightbracket.replace('}', '') except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #GET DESTINATION ID try: d_base = "https://esi.evetech.net/latest/search/?categories=solar_system&search=" d_end = "&strict=true" d_url = d_base + d_system + d_end d_response = urllib.urlopen(d_url).read() d_split_response = d_response.split(":") d_id_section = d_split_response[1] d_id_leftbracket = d_id_section.replace('[', '') d_id_rightbracket = d_id_leftbracket.replace(']', '') d_id_final = d_id_rightbracket.replace('}', '') except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #GET ROUTE try: r_base = "https://esi.evetech.net/latest/route/" r_end = "/?datasource=tranquility&flag=" r_type = prefstr r_slash = "/" r_url = r_base + o_id_final + r_slash + d_id_final + r_end + r_type except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #IF THIS ROUTE IS PART OF THE ORIGINAL REQUEST, ADD IT TO THE LIST try: if optimizing == False: r_response = urllib.urlopen(r_url).read() routes.append(r_response) waypoints.append(o_system) else: r_response = urllib.urlopen(r_url).read() return r_response except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #OPTIMIZE THE ROUTE def optimize(): global o_system global d_system global routes global waypoints global optimized_routes global previous_routes global tested_routes global total_routes global final_routes global origins global destinations global initialized global cycles global final_best_route global fixed_endpoint_name result.insert(INSERT, "\n") last_destination = "" last_route = [None] * 10000 best_route = [None] * 10000 sys1 = "" sys2 = "" waypoints.append(d_system) #GET AND DISPLAY THE TOTAL ROUTE DISTANCE IN NUMBER OF JUMPS total_distance = 0 for route in routes: split_route = route.split(",") total_distance += len(split_route) result.insert(INSERT, "\n" + "Number of jumps: " + str(total_distance)) result.see("end") if fixed_endpoint == False: #GET ID FOR THE ORIGIN split_for_origin = routes[0].split(",") first_origin = split_for_origin[0].split("[")[1] #GET ID FOR THE LAST STOP final_route = routes[len(routes) - 1] split_final_route = final_route.split(",") last_stop = split_final_route[len(split_final_route) - 1].split("]")[0] try: #CONVERT ID TO NAME FOR ORIGIN first_begin_url = "https://esi.evetech.net/latest/universe/systems/" first_end_url = "/?datasource=tranquility&language=en-us" first_final_url = first_begin_url + first_origin + first_end_url first_response = urllib.urlopen(first_final_url).read() first_final_origin = first_response.split(":")[2].split( ",")[0].replace('"', "") d_system = first_final_origin #CONVERT ID TO NAME FOR DESTINATION endpoint_begin_url = "https://esi.evetech.net/latest/universe/systems/" endpoint_end_url = "/?datasource=tranquility&language=en-us" endpoint_final_url = endpoint_begin_url + last_stop + endpoint_end_url endpoint_response = urllib.urlopen(endpoint_final_url).read() endpoint_final_response = endpoint_response.split( ":")[2].split(",")[0].replace('"', "") o_system = endpoint_final_response except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #GET AND DISPLAY THE TOTAL ROUTE DISTANCE INCLUDING RETURN TO ORIGIN return_route = create_route(True) return_distance = len(return_route.split(",")) result.insert( INSERT, "\n" + "Including return to origin: " + str(total_distance + return_distance) + "\n") result.see("end") else: #SET DESTINATION TO THE FIXED ENDPOINT if fixed_endpoint_name != "" and fixed_endpoint_name != "Fixed End Point": try: d_system = fixed_endpoint_name except: result.insert(INSERT, "\n" + "ERROR: Invalid Fixed End Point!") result.see("end") #GET THE ID FOR THE LAST STOP final_route = routes[len(final_routes) - 1] split_final_route = final_route.split(",") last_stop = split_final_route[len(split_final_route) - 1].split("]")[0] try: #CONVERT ID TO NAME FOR DESTINATION endpoint_begin_url = "https://esi.evetech.net/latest/universe/systems/" endpoint_end_url = "/?datasource=tranquility&language=en-us" endpoint_final_url = endpoint_begin_url + last_stop + endpoint_end_url endpoint_response = urllib.urlopen(endpoint_final_url).read() endpoint_final_response = endpoint_response.split( ":")[2].split(",")[0].replace('"', "") o_system = endpoint_final_response except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #GET AND DISPLAY THE TOTAL TRIP DISTANCE INCLUDING RETURN TO ORIGIN return_route = create_route(True) return_distance = len(return_route.split(",")) result.insert( INSERT, "\n" + "Including fixed end point: " + str(total_distance + return_distance) + "\n") result.see("end") try: cycles = int(iteration_field.get()) except: cycles = 1 count = 0 while count < cycles: count += 1 result.insert(INSERT, "\nCycle " + str(count) + ":\n") result.see("end") for route in routes: try: #CONVERT ID TO NAME FOR ORIGIN split_route = route.split(",") origin = split_route[0].split("[")[1] begin_url = "https://esi.evetech.net/latest/universe/systems/" end_url = "/?datasource=tranquility&language=en-us" final_url = begin_url + origin + end_url response = urllib.urlopen(final_url).read() final_origin = response.split(":")[2].split( ",")[0].replace('"', "") o_system = final_origin except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #ADD THE ORIGIN AS A DESTINATION SO IT'S NOT INCLUDED IN POTENTIAL ROUTES if initialized == False: destinations.append(o_system) initialized = True last_destination = o_system #WHEN THE ROUTE IS CHANGED, THE PREVIOUS WAYPOINT MUST BE UPDATED elif o_system != last_destination: o_system = last_destination #RESET THE BOOLEAN VALUES FOR ROUTE UPDATES optimized = False passed = False result.insert( INSERT, "\n" + "Finding the shortest route from " + o_system + " to another waypoint.\n") result.see("end") for waypoint in waypoints: if o_system != waypoint and passed == False: #PREVENT ROUTING TO THE CURRENT SYSTEM d_system = waypoint potential_route = create_route( True ) #CREATE A ROUTE TO GET THE LENGTH IN NUMBER OF JUMPS split_pot = potential_route.split(",") #FIND THE SHORTEST ROUTE FROM THE CURRENT LOCATION TO ANOTHER LOCATION IN THE LIST if optimized == True: split_best = best_route.split(",") if d_system not in destinations and o_system not in origins and len( best_route ) != 10000 and potential_route not in tested_routes: result.insert( INSERT, "\nChecking route " + str(o_system) + " to " + str(d_system) + ": " + str(len(split_pot)) + " jumps. Best found: " + str(len(split_best)) + " jumps.") result.see("end") if len(split_pot) < len( split_best ) and d_system not in destinations and o_system not in origins: best_route = potential_route sys1 = o_system sys2 = d_system elif len(split_pot) == len( split_best ) and d_system not in destinations and o_system not in origins: passed = True optimized = False else: if len(split_pot) < len( last_route ) and d_system not in destinations and o_system not in origins: if d_system not in destinations and o_system not in origins and len( best_route ) != 10000 and potential_route not in tested_routes: result.insert( INSERT, "\nChecking route " + str(o_system) + " to " + str(d_system) + ": " + str(len(split_pot)) + " jumps. Best found: " + str(len(last_route)) + " jumps.") result.see("end") best_route = potential_route sys1 = o_system sys2 = d_system optimized = True elif len(split_pot) == len( last_route ) and d_system not in destinations and o_system not in origins: passed = True optimized = False else: last_route = split_pot #OPTIMAL ROUTE WAS FOUND if optimized == True: result.insert( INSERT, "\n\n" + "Optimized route: " + sys1 + " to " + sys2 + "\n") result.see("end") optimized_routes.append(best_route) origins.append(sys1) destinations.append(sys2) last_destination = sys2 #OPTIMAL ROUTE WAS NOT FOUND, SO THE NEXT WAYPOINT IN THE LIST IS USED elif optimized == False: finished = False for waypoint in waypoints: if finished == False: if o_system != waypoint and waypoint not in destinations: #GET THE FIRST UNUSED WAYPOINT d_system = waypoint potential_route = create_route(True) if potential_route not in tested_routes: #THIS ROUTE HAS NOT YET BEEN EXAMINED tested_routes.append(potential_route) optimized_routes.append(potential_route) result.insert( INSERT, "\n\n" + "No exceptional route found. Creating route: " + o_system + " to " + d_system + "\n") result.see("end") origins.append(o_system) destinations.append(d_system) last_destination = d_system finished = True if finished == False: #ALL POSSIBLE ROUTES HAVE BEEN EXAMINED FOR THIS WAYPOINT SO THE SHORTEST ONE IS SELECTED previous_best_route = [None] * 10000 best_tested_route = [] for route in tested_routes: split_route = str(route).split(",") origin = split_route[0].split("[")[1] try: o_begin_url = "https://esi.evetech.net/latest/universe/systems/" o_end_url = "/?datasource=tranquility&language=en-us" o_final_url = o_begin_url + origin + o_end_url o_response = urllib.urlopen(o_final_url).read() o_final_response = o_response.split( ":")[2].split(",")[0].replace('"', "") except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!" ) result.see("end") if o_final_response == o_system: if len(previous_best_route) != 10000: result.insert( INSERT, "\n" + "Comparing potential routes for this waypoint: " + str(len(split_route)) + " jumps VS " + str(len(previous_best_route)) + " jumps.") result.see("end") s_destination = split_route[len(split_route) - 1].split("]")[0] try: s_d_begin_url = "https://esi.evetech.net/latest/universe/systems/" s_d_end_url = "/?datasource=tranquility&language=en-us" s_d_final_url = s_d_begin_url + s_destination + s_d_end_url s_d_response = urllib.urlopen( s_d_final_url).read() s_d_final_response = s_d_response.split( ":")[2].split(",")[0].replace('"', "") except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!" ) result.see("end") if s_d_final_response not in destinations and len( split_route) < len( previous_best_route): best_tested_route = route previous_best_route = split_route split_best_route = str(best_tested_route).split(",") origin = split_best_route[0].split("[")[1] destination = split_best_route[len(split_best_route) - 1].split("]")[0] try: o_begin_url = "https://esi.evetech.net/latest/universe/systems/" o_end_url = "/?datasource=tranquility&language=en-us" o_final_url = o_begin_url + origin + o_end_url o_response = urllib.urlopen(o_final_url).read() t_o_final_response = o_response.split( ":")[2].split(",")[0].replace('"', "") d_begin_url = "https://esi.evetech.net/latest/universe/systems/" d_end_url = "/?datasource=tranquility&language=en-us" d_final_url = d_begin_url + destination + d_end_url d_response = urllib.urlopen(d_final_url).read() t_d_final_response = d_response.split( ":")[2].split(",")[0].replace('"', "") except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!" ) result.see("end") optimized_routes.append(best_tested_route) result.insert( INSERT, "\n\n" + "All possible routes considered. Using route: " + t_o_final_response + " to " + t_d_final_response + "\n") result.see("end") origins.append(t_o_final_response) destinations.append(t_d_final_response) last_destination = t_d_final_response finished = True total_routes.append(optimized_routes) previous_routes = optimized_routes optimized_routes = [] origins = [] destinations = [] optimized = False initialized = False #SELECT THE BEST ROUTE FROM ALL CYCLES previous_best_distance = 10000 for route in total_routes: total_route_distance = 0 for r in route: s_r = r.split(",") total_route_distance += len(s_r) if previous_best_distance != 10000: result.insert( INSERT, "\n" + "Comparing optimized routes: " + str(total_route_distance) + " jumps VS " + str(previous_best_distance) + " jumps.") result.see("end") if total_route_distance < previous_best_distance: final_best_route = route previous_best_distance = total_route_distance #DISPLAY THE OPTIMIZED ROUTE previous_destination = "" for route in final_best_route: split_route = str(route).split(",") origin = split_route[0].split("[")[1] destination = split_route[len(split_route) - 1].split("]")[0] #CONVERT THE ID TO NAME FOR EACH ROUTE try: o_begin_url = "https://esi.evetech.net/latest/universe/systems/" o_end_url = "/?datasource=tranquility&language=en-us" o_final_url = o_begin_url + origin + o_end_url o_response = urllib.urlopen(o_final_url).read() o_final_response = o_response.split(":")[2].split( ",")[0].replace('"', "") d_begin_url = "https://esi.evetech.net/latest/universe/systems/" d_end_url = "/?datasource=tranquility&language=en-us" d_final_url = d_begin_url + destination + d_end_url d_response = urllib.urlopen(d_final_url).read() d_final_response = d_response.split(":")[2].split( ",")[0].replace('"', "") #SET THE CURRENT SYSTEM TO INITIALIZE ITERATION if previous_destination == "": previous_destination = o_final_response result.insert(INSERT, "\n\n" + "New Route:" + "\n") result.see("end") #SET THE CURRENT SYSTEM TO THE PREVIOUS DESTINATION if o_final_response == previous_destination: final_routes.append(route) previous_destination = d_final_response result.insert( INSERT, "\n" + o_final_response + " to " + d_final_response) result.see("end") else: #THIS IS FOR DEBUGGING AND SHOULD NEVER HAPPEN result.insert( INSERT, "\n" + "ERROR: Out of order! " + o_final_response + ":" + d_final_response) result.see("end") except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #GET AND DISPLAY THE TOTAL TRIP DISTANCE IN NUMBER OF JUMPS total_distance = 0 for route in final_routes: split_route = route.split(",") total_distance += len(split_route) result.insert(INSERT, "\n\n" + "Number of jumps: " + str(total_distance)) result.see("end") if fixed_endpoint == False: #GET THE ID FOR THE ORIGIN split_for_origin = final_routes[0].split(",") first_origin = split_for_origin[0].split("[")[1] #GET THE ID FOR THE LAST STOP final_route = final_routes[len(final_routes) - 1] split_final_route = final_route.split(",") last_stop = split_final_route[len(split_final_route) - 1].split("]")[0] try: #CONVERT ID TO NAME FOR ORIGIN first_begin_url = "https://esi.evetech.net/latest/universe/systems/" first_end_url = "/?datasource=tranquility&language=en-us" first_final_url = first_begin_url + first_origin + first_end_url first_response = urllib.urlopen(first_final_url).read() first_final_origin = first_response.split(":")[2].split( ",")[0].replace('"', "") d_system = first_final_origin #CONVERT ID TO NAME FOR DESTINATION endpoint_begin_url = "https://esi.evetech.net/latest/universe/systems/" endpoint_end_url = "/?datasource=tranquility&language=en-us" endpoint_final_url = endpoint_begin_url + last_stop + endpoint_end_url endpoint_response = urllib.urlopen(endpoint_final_url).read() endpoint_final_response = endpoint_response.split( ":")[2].split(",")[0].replace('"', "") o_system = endpoint_final_response except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #GET AND DISPLAY THE TOTAL TRIP DISTANCE INCLUDING RETURN TO ORIGIN return_route = create_route(True) return_distance = len(return_route.split(",")) result.insert( INSERT, "\n" + "Including return to origin: " + str(total_distance + return_distance) + "\n") result.see("end") else: #SET DESTINATION TO THE FIXED ENDPOINT d_system = fixed_endpoint_name #GET THE ID FOR THE LAST STOP final_route = final_routes[len(final_routes) - 1] split_final_route = final_route.split(",") last_stop = split_final_route[len(split_final_route) - 1].split("]")[0] try: #CONVERT ID TO NAME FOR DESTINATION endpoint_begin_url = "https://esi.evetech.net/latest/universe/systems/" endpoint_end_url = "/?datasource=tranquility&language=en-us" endpoint_final_url = endpoint_begin_url + last_stop + endpoint_end_url endpoint_response = urllib.urlopen(endpoint_final_url).read() endpoint_final_response = endpoint_response.split( ":")[2].split(",")[0].replace('"', "") o_system = endpoint_final_response except: result.insert( INSERT, "\n" + "ERROR: Unable to get data from esi.evetech.net!") result.see("end") #GET AND DISPLAY THE TOTAL TRIP DISTANCE INCLUDING RETURN TO ORIGIN return_route = create_route(True) return_distance = len(return_route.split(",")) result.insert( INSERT, "\n" + "Including fixed end point: " + str(total_distance + return_distance) + "\n") result.see("end") #RESET VARIABLES SO ANOTHER SET OF WAYPOINTS CAN BE ENTERED previous_routes = [] total_routes = [] tested_routes = [] final_best_route = [] routes = [] optimized_routes = [] final_routes = [] waypoints = [] o_system = "" d_system = "" origins = [] destinations = [] initialized = False start_field.delete(0, 'end') end_field.delete(0, 'end') start_field.insert(0, "Origin") end_field.insert(0, "Destination") result.insert(INSERT, "\n") result.see("end") #START THE OPTIMIZATION THREAD def begin_optimization(): global waypoint_adding_done if waypoint_adding_done == True: optimization_thread = threading.Thread(target=optimize) optimization_thread.start() #CHANGE THE ROUTE PREFERENCE def change_preference(): global prefstr if preference.get() == 1: prefstr = "shortest" if preference.get() == 2: prefstr = "secure" if preference.get() == 3: prefstr = "insecure" #CHANGE THE FIXED ENDPOINT def set_fixed_endpoint(): global fixed_endpoint_name global fixed_endpoint if fixed.get() == 1: fixed_endpoint = True fixed_end_field.configure(state=NORMAL) else: fixed_endpoint = False fixed_end_field.configure(state=DISABLED) #FINALIZE FIXED ENDPOINT def lock_fixed_endpoint(Event=None): global fixed_endpoint_name fixed_endpoint_name = fixed_end_field.get() fixed_end_field.configure(state=DISABLED) #SETUP BUTTONS fixed = IntVar() fixed_end_button = Checkbutton(window, text="Fixed End-Point", variable=fixed, command=set_fixed_endpoint, onvalue=1, offvalue=0, bg="gray", font=("Arial Bold", 12)) fixed_end_button.pack() preference = IntVar() R1 = Radiobutton(window, text="Shortest", variable=preference, value=1, command=change_preference, bg="gray", font=("Arial Bold", 12)) R1.pack() R2 = Radiobutton(window, text="Secure", variable=preference, value=2, command=change_preference, bg="gray", font=("Arial Bold", 12)) R2.pack() R3 = Radiobutton(window, text="Insecure", variable=preference, value=3, command=change_preference, bg="gray", font=("Arial Bold", 12)) R3.pack() button = Button(window, text="Optimize", font=("Arial Bold", 12), bg="gray", fg="blue", command=begin_optimization) button.pack() end_field.bind( "<Return>", add_waypoint ) #ALLOWS THE RETURN KEY TO ADD A WAYPOINT INSTEAD OF CLICKING THE BUTTON fixed_end_field.bind("<Return>", lock_fixed_endpoint) window.mainloop()
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("IAF CALC 0.01") self.pack(fill=BOTH, expand=1) self.configure(background='white') frameTOP = Frame(self) frameTOP.config(bg="white") frameTOP.pack(side=TOP) frameFILES = Frame(frameTOP) frameFILES.pack(side=LEFT, padx=10) # --- BUTTON FOR FILE 1 --- # frameF1 = LabelFrame(frameFILES, text="Eyes open file:", relief=FLAT, borderwidth=1, background="white") frameF1.pack(fill=X, expand=1) self.nameF1 = Entry(frameF1, width=50) self.nameF1.config(bg="lightgray") self.nameF1.pack(side=LEFT) self.nameF1.delete(0, END) self.nameF1.insert(0, "") self.buttonLoadFile1 = Button(frameF1, text="...", command=self.askOpenFile1) self.buttonLoadFile1.pack(side=LEFT, padx=5, pady=5) # ----------------------- # # --- BUTTON FOR FILE 2 --- # frameF2 = LabelFrame(frameFILES, text="Eyes closed file:", relief=FLAT, borderwidth=1, background="white") frameF2.pack(fill=X, expand=1) self.nameF2 = Entry(frameF2, width=50) self.nameF2.config(bg="lightgray") self.nameF2.pack(side=LEFT) self.nameF2.delete(0, END) self.nameF2.insert(0, "") self.buttonLoadFile2 = Button(frameF2, text="...", command=self.askOpenFile2) self.buttonLoadFile2.pack(side=LEFT, padx=5, pady=5) # ----------------------- # # --- BUTTON FOR FILE OUTPUT --- # frameO = LabelFrame(frameFILES, text="Output directory:", relief=FLAT, borderwidth=1, background="white") frameO.pack(fill=X, expand=1) self.nameO = Entry(frameO, width=50) self.nameO.config(bg="lightgray") self.nameO.pack(side=LEFT) self.nameO.delete(0, END) self.nameO.insert(0, "") self.buttonSelectOutput = Button(frameO, text="...", command=self.askOutputDirectory) self.buttonSelectOutput.pack(side=LEFT, padx=5, pady=5) # -------------------------------# # self.pack() # self.pack(fill=Y, expand=1) # ---------- PSD PARAMETER SELECTION ---------- # framePARAM = Frame(frameTOP) framePARAM.config(bg="white") framePARAM.pack(side=LEFT, fill=X) frame = LabelFrame(framePARAM, text="PSD Parameters", relief=RIDGE, borderwidth=1, background="white") frame.pack(fill=BOTH, expand=1, side=TOP) wFs = Label(frame, text="Fs:", bg="white") wFs.pack(side=LEFT) self.inputFs = Entry(frame, width=5) self.inputFs.pack(side=LEFT, padx=5) self.inputFs.delete(0, END) self.inputFs.insert(0, "500") wWS = Label(frame, text="Window size:", bg="white") wWS.pack(side=LEFT) self.inputWinSize = Entry(frame, width=5) self.inputWinSize.pack(side=LEFT, padx=5) self.inputWinSize.delete(0, END) self.inputWinSize.insert(0, "1024") wOL = Label(frame, text="Overlap:", bg="white") wOL.pack(side=LEFT) self.inputOverlap = Entry(frame, width=5) self.inputOverlap.pack(side=LEFT, padx=5) self.inputOverlap.delete(0, END) self.inputOverlap.insert(0, "512") wWT = Label(frame, text="Window function:", bg="white") wWT.pack(side=LEFT) variable = StringVar(frame) variable.set("Hamming") # default value self.inputWinType = OptionMenu(frame, variable, "Hamming", "Bartlett", "Blackman", "Hanning", "None") self.inputWinType.config(bg="white", width=10) self.inputWinType.pack(side=LEFT) buttonRun = Button(frame, text="GO!", command=self.goTime) buttonRun.pack(side=RIGHT) # Channel selector frameCh = LabelFrame(framePARAM, text="Channels", relief=RIDGE, borderwidth=1, background="white") frameCh.pack(fill=BOTH, expand=1, side=TOP) self.EOch1 = IntVar() self.inputEOch1 = Checkbutton(frameCh, text="1", variable=self.EOch1, bg="white") self.inputEOch1.pack(side=LEFT) self.EOch2 = IntVar() self.inputEOch2 = Checkbutton(frameCh, text="2", variable=self.EOch2, bg="white") self.inputEOch2.pack(side=LEFT) self.EOch3 = IntVar() self.inputEOch3 = Checkbutton(frameCh, text="3", variable=self.EOch3, bg="white") self.inputEOch3.pack(side=LEFT) self.EOch4 = IntVar() self.inputEOch4 = Checkbutton(frameCh, text="4", variable=self.EOch4, bg="white") self.inputEOch4.pack(side=LEFT) self.EOch5 = IntVar() self.inputEOch5 = Checkbutton(frameCh, text="5", variable=self.EOch5, bg="white") self.inputEOch5.pack(side=LEFT) self.EOch6 = IntVar() self.inputEOch6 = Checkbutton(frameCh, text="6", variable=self.EOch6, bg="white") self.inputEOch6.pack(side=LEFT) self.EOch7 = IntVar() self.inputEOch7 = Checkbutton(frameCh, text="7", variable=self.EOch7, bg="white") self.inputEOch7.pack(side=LEFT) self.EOch8 = IntVar() self.inputEOch8 = Checkbutton(frameCh, text="8", variable=self.EOch8, bg="white") self.inputEOch8.pack(side=LEFT) # IAF Calculation parameters frameIAF = LabelFrame(framePARAM, text="IAF Search Limits", relief=RIDGE, borderwidth=1, background="white") frameIAF.pack(fill=BOTH, expand=1, side=TOP) labelLowBound = Label(frameIAF, text="Lower limit (Hz):", bg="white") labelLowBound.pack(side=LEFT) self.inputLowBound = Entry(frameIAF, width=5) self.inputLowBound.pack(side=LEFT, padx=5) self.inputLowBound.delete(0, END) self.inputLowBound.insert(0, "7") labelUpBound = Label(frameIAF, text="Upper limit (Hz):", bg="white") labelUpBound.pack(side=LEFT) self.inputUpBound = Entry(frameIAF, width=5) self.inputUpBound.pack(side=LEFT, padx=5) self.inputUpBound.delete(0, END) self.inputUpBound.insert(0, "14") self.GaussVar = IntVar() self.inputGauss = Checkbutton(frameIAF, text="Gauss", variable=self.GaussVar, bg="white") self.inputGauss.pack(side=LEFT) buttonRun = Button(frameIAF, text="IAF!", command=self.calculateIAF) buttonRun.pack(side=RIGHT) self.pack() # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # END OF TOP FRAME # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # my variables self.chSelect = 0 self.chOther = 0 self.P1 = ndarray(1) self.f1 = ndarray(1) self.P2 = ndarray(1) self.f2 = ndarray(1) self.filename1 = "..." self.filename2 = "..." self.IAF = 10 self.doGauss = True # FIGURE STUFF !!! self.Pmax = 0 self.Pmin = 0 self.Dmax = 0 self.Dmin = 0 frameBOTTOM = Frame(self) frameBOTTOM.config(bg="white") frameBOTTOM.pack(side=BOTTOM, pady=10) frameFig = LabelFrame(frameBOTTOM, text="Spectrum", relief=RIDGE, borderwidth=1, background="white") frameFig.pack(fill=X, expand=1, side=LEFT, padx=10) self.fig1 = matplotlib.figure.Figure(figsize=(7, 3), dpi=100) #,frameon=False) self.fig1.set_facecolor('white') self.fig = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg( self.fig1, master=frameFig) self.a1 = self.fig1.add_subplot(121) self.a2 = self.fig1.add_subplot(122) self.fig.show() self.fig.get_tk_widget().pack(side=BOTTOM) frameConfig = LabelFrame(frameBOTTOM, text="Filter configuration", relief=RAISED, borderwidth=1, background="white") frameConfig.pack(fill=BOTH, expand=1, side=RIGHT, padx=10) frameIAF = LabelFrame(frameConfig, text="Individual Alpha Frequency (IAF)") frameIAF.config(bg="white") frameIAF.pack(expand=1, side=TOP, padx=10) self.inputIAF = Entry(frameIAF, width=5) self.inputIAF.pack(side=LEFT, padx=5) self.inputIAF.delete(0, END) self.inputIAF.insert(0, "0") self.buttonWriteDefault = Button(frameIAF, text="Update Filters", command=self.updateFilters) self.buttonWriteDefault.pack(side=LEFT, padx=5, pady=5) frameFilters = LabelFrame(frameConfig, text="Filters", relief=RAISED, borderwidth=1, background="white") frameFilters.pack(fill=X, expand=1, side=TOP) # THETA FRAME frameTheta = LabelFrame(frameFilters, text="Theta", relief=RAISED, borderwidth=1, background="white") frameTheta.pack(expand=1, side=TOP, pady=5, padx=5) self.inputThetaLow = Entry(frameTheta, width=8) self.inputThetaLow.pack(side=LEFT, padx=5, pady=5) self.inputThetaLow.delete(0, END) self.inputThetaLow.insert(0, "0") self.inputThetaHigh = Entry(frameTheta, width=8) self.inputThetaHigh.pack(side=LEFT, padx=5, pady=5) self.inputThetaHigh.delete(0, END) self.inputThetaHigh.insert(0, "0") # BETA FRAME frameBeta = LabelFrame(frameFilters, text="Beta", relief=RAISED, borderwidth=1, background="white") frameBeta.pack(expand=1, side=TOP, pady=5, padx=5) self.inputBetaLow = Entry(frameBeta, width=8) self.inputBetaLow.pack(side=LEFT, padx=5, pady=5) self.inputBetaLow.delete(0, END) self.inputBetaLow.insert(0, "0") self.inputBetaHigh = Entry(frameBeta, width=8) self.inputBetaHigh.pack(side=LEFT, padx=5, pady=5) self.inputBetaHigh.delete(0, END) self.inputBetaHigh.insert(0, "0") # SMR FRAME frameSMR = LabelFrame(frameFilters, text="SMR", relief=RAISED, borderwidth=1, background="white") frameSMR.pack(expand=1, side=TOP, pady=5, padx=5) self.inputSMRLow = Entry(frameSMR, width=8) self.inputSMRLow.pack(side=LEFT, padx=5, pady=5) self.inputSMRLow.delete(0, END) self.inputSMRLow.insert(0, "0") self.inputSMRHigh = Entry(frameSMR, width=8) self.inputSMRHigh.pack(side=LEFT, padx=5, pady=5) self.inputSMRHigh.delete(0, END) self.inputSMRHigh.insert(0, "0") frameButtons = LabelFrame(frameConfig, text="Commands", relief=RAISED, borderwidth=1, background="white") frameButtons.pack(expand=1, side=BOTTOM) self.buttonWriteConfig = Button(frameButtons, text="Write Filters", command=self.writeFilters) self.buttonWriteConfig.pack(side=LEFT, padx=5, pady=5) self.buttonWriteDefault = Button(frameButtons, text="Reset to Defaults", command=self.resetIAFtoDefault) self.buttonWriteDefault.pack(side=LEFT, padx=5, pady=5) # self.buttonVisualize = Button(frameButtons, text="VIS",command=self.resetIAFtoDefault) # self.buttonVisualize.pack(side=LEFT,padx=5,pady=5) self.buttonPrintFig = Button(frameButtons, text="Print Figure", command=self.printFigureToFile) self.buttonPrintFig.pack(side=LEFT, padx=5, pady=5) def getChannelList(self): # Initialize self.chSelect = asarray([]) self.chOther = asarray([]) if self.EOch1.get(): self.chSelect = append(self.chSelect, 0) else: self.chOther = append(self.chOther, 0) if self.EOch2.get(): self.chSelect = append(self.chSelect, 1) else: self.chOther = append(self.chOther, 1) if self.EOch3.get(): self.chSelect = append(self.chSelect, 2) else: self.chOther = append(self.chOther, 2) if self.EOch4.get(): self.chSelect = append(self.chSelect, 3) else: self.chOther = append(self.chOther, 3) if self.EOch5.get(): self.chSelect = append(self.chSelect, 4) else: self.chOther = append(self.chOther, 4) if self.EOch6.get(): self.chSelect = append(self.chSelect, 5) else: self.chOther = append(self.chOther, 5) if self.EOch7.get(): self.chSelect = append(self.chSelect, 6) else: self.chOther = append(self.chOther, 6) if self.EOch8.get(): self.chSelect = append(self.chSelect, 7) else: self.chOther = append(self.chOther, 7) def updateFilters(self): # SET THETA self.inputThetaLow.delete(0, END) self.inputThetaLow.insert(0, "%.2f" % (float(self.inputIAF.get()) * 0.4)) self.inputThetaHigh.delete(0, END) self.inputThetaHigh.insert(0, "%.2f" % (float(self.inputIAF.get()) * 0.6)) # SET BETA self.inputBetaLow.delete(0, END) self.inputBetaLow.insert(0, "%.2f" % (float(self.inputIAF.get()) * 1.2)) self.inputBetaHigh.delete(0, END) self.inputBetaHigh.insert(0, 25) # SET SMR self.inputSMRLow.delete(0, END) self.inputSMRLow.insert(0, "%.2f" % (float(self.inputIAF.get()) * 1.2)) self.inputSMRHigh.delete(0, END) self.inputSMRHigh.insert(0, "%.2f" % (float(self.inputIAF.get()) * 1.5)) def resetIAFtoDefault(self): self.inputIAF.delete(0, END) self.inputIAF.insert(0, "10") self.updateFilters() def calculateIAF(self): self.getChannelList() print "LOLOL calculating IAF" m1 = 20 * log10(mean(self.P1[self.chSelect.astype(int), :], axis=0)) m2 = 20 * log10(mean(self.P2[self.chSelect.astype(int), :], axis=0)) d = m2 - m1 if self.GaussVar.get(): # print d.shape # print gauss_signal.shape d_gauss = d[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] gauss_signal = signal.gaussian(d_gauss.shape[0], 1) d_gauss = d_gauss * gauss_signal d[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] = d_gauss self.a2 = plotIAF(self.f1, d, "purple", self.a2, "IAF") # Get dat IAF val d_search = d[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] f_search = self.f1[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] f_idx = argmax(d_search) print f_search[f_idx] self.inputIAF.delete(0, END) self.inputIAF.insert(0, "%.2f" % (f_search[f_idx])) # Autoscale self.Dmin = amin(d_search) - 2 self.Dmax = amax(d_search) + 2 self.a2.set_ylim( self.Dmin, self.Dmax) # little modifier to differentiate the peak # IAF position self.a2.vlines(f_search[f_idx], self.Dmin, self.Dmax, color="Cyan") # Search limits self.a2.vlines(int(self.inputLowBound.get()), self.Dmin, self.Dmax, linestyles=":", linewidth=0.25) self.a2.vlines(int(self.inputUpBound.get()), self.Dmin, self.Dmax, linestyles=":", linewidth=0.25) self.fig.show() # Set filter configs def goTime(self): print "ITS GO TIME!" print self.filename1 print self.filename2 self.getChannelList() print self.chSelect print self.chOther self.f1, self.P1 = computeSpectrum(self.filename1, int(self.inputFs.get()), int(self.inputWinSize.get()), int(self.inputOverlap.get())) self.f2, self.P2 = computeSpectrum(self.filename2, int(self.inputFs.get()), int(self.inputWinSize.get()), int(self.inputOverlap.get())) # Plotting time self.a1.cla() self.a1 = plotSpectrum(self.f1, self.P1, "blue", self.a1, "Power spectrum", self.chSelect, self.chOther) self.a1 = plotSpectrum(self.f2, self.P2, "red", self.a1, "Power spectrum", self.chSelect, self.chOther) # Trying to autoscale P1_ROI = 20 * log10(self.P1[:, bitwise_and(self.f1 > 1, self.f1 < 20)]) P2_ROI = 20 * log10(self.P2[:, bitwise_and(self.f2 > 1, self.f2 < 20)]) self.Pmax = amax([amax(P1_ROI), amax(P2_ROI)]) self.Pmin = amin([(amin(P1_ROI)), amin(P2_ROI)]) self.a1.set_ylim(self.Pmin, self.Pmax) # Autoscale success :> self.fig.show() def writeFilters(self): f_theta = open(self.nameO.get() + "/theta.f", "w") f_theta.write( "<OpenViBE-SettingsOverride>\n\t<SettingValue>Butterworth</SettingValue>\n\t<SettingValue>Band pass</SettingValue>\n\t<SettingValue>4</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>0.5</SettingValue>\n</OpenViBE-SettingsOverride>" .format(float(self.inputThetaLow.get()), float(self.inputThetaHigh.get()))) f_theta.close() f_beta = open(self.nameO.get() + "/beta.f", "w") f_beta.write( "<OpenViBE-SettingsOverride>\n\t<SettingValue>Butterworth</SettingValue>\n\t<SettingValue>Band pass</SettingValue>\n\t<SettingValue>4</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>0.5</SettingValue>\n</OpenViBE-SettingsOverride>" .format(float(self.inputBetaLow.get()), float(self.inputBetaHigh.get()))) f_beta.close() f_smr = open(self.nameO.get() + "/smr.f", "w") f_smr.write( "<OpenViBE-SettingsOverride>\n\t<SettingValue>Butterworth</SettingValue>\n\t<SettingValue>Band pass</SettingValue>\n\t<SettingValue>4</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>0.5</SettingValue>\n</OpenViBE-SettingsOverride>" .format(float(self.inputSMRLow.get()), float(self.inputSMRHigh.get()))) f_smr.close() def printFigureToFile(self): self.fig1.savefig(self.nameO.get() + "/IAF_spectrum.png") def askOpenFile1(self): ftypes = [('asdadfh', '*.txt'), ('All files', '*')] dlg = tkFileDialog.Open(self, filetypes=ftypes) self.filename1 = dlg.show() self.nameF1.delete(0, END) self.nameF1.insert(0, self.filename1) def askOpenFile2(self): ftypes = [('asdadfh', '*.txt'), ('All files', '*')] dlg = tkFileDialog.Open(self, filetypes=ftypes) self.filename2 = dlg.show() self.nameF2.delete(0, END) self.nameF2.insert(0, self.filename2) def askOutputDirectory(self): dlg = tkFileDialog.askdirectory() #self.outputdir = dlg.show() self.outputdir = dlg self.nameO.delete(0, END) self.nameO.insert(0, self.outputdir)
class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() # First row f1 = LabelFrame(self, text='NAND file with No$GBA footer', padx=10, pady=10) # NAND Button self.nand_mode = False nand_icon = PhotoImage( data=('R0lGODlhEAAQAIMAAAAAADMzM2ZmZpmZmczMzP///wAAAAAAAAA' 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAMAAAYALAAAAAAQAB' 'AAAARG0MhJaxU4Y2sECAEgikE1CAFRhGMwSMJwBsU6frIgnR/bv' 'hTPrWUSDnGw3JGU2xmHrsvyU5xGO8ql6+S0AifPW8kCKpcpEQA7')) self.nand_button = Button(f1, image=nand_icon, command=self.change_mode, state=DISABLED) self.nand_button.image = nand_icon self.nand_button.pack(side='left') self.nand_file = StringVar() Entry(f1, textvariable=self.nand_file, state='readonly', width=40).pack(side='left') Button(f1, text='...', command=self.choose_nand).pack(side='left') f1.pack(padx=10, pady=10, fill=X) # Second row f2 = Frame(self) # Check box self.twilight = IntVar() self.twilight.set(1) self.chk = Checkbutton( f2, text='Install latest TWiLight Menu++ on custom firmware', variable=self.twilight) self.chk.pack(padx=10, anchor=W) # NAND operation frame self.nand_frame = LabelFrame(f2, text='NAND operation', padx=10, pady=10) self.nand_operation = IntVar() self.nand_operation.set(0) Radiobutton(self.nand_frame, text='Uninstall unlaunch or install v1.4 stable', variable=self.nand_operation, value=0, command=lambda: self.enable_entries(False)).pack(anchor=W) Radiobutton(self.nand_frame, text='Remove No$GBA footer', variable=self.nand_operation, value=1, command=lambda: self.enable_entries(False)).pack(anchor=W) Radiobutton(self.nand_frame, text='Add No$GBA footer', variable=self.nand_operation, value=2, command=lambda: self.enable_entries(True)).pack(anchor=W) fl = Frame(self.nand_frame) self.cid_label = Label(fl, text='eMMC CID', state=DISABLED) self.cid_label.pack(anchor=W, padx=(24, 0)) self.cid = StringVar() self.cid_entry = Entry(fl, textvariable=self.cid, width=20, state=DISABLED) self.cid_entry.pack(anchor=W, padx=(24, 0)) fl.pack(side='left') fr = Frame(self.nand_frame) self.console_id_label = Label(fr, text='Console ID', state=DISABLED) self.console_id_label.pack(anchor=W) self.console_id = StringVar() self.console_id_entry = Entry(fr, textvariable=self.console_id, width=20, state=DISABLED) self.console_id_entry.pack(anchor=W) fr.pack(side='right') f2.pack(fill=X) # Third row f3 = Frame(self) self.start_button = Button(f3, text='Start', width=16, command=self.hiya, state=DISABLED) self.start_button.pack(side='left', padx=(0, 5)) Button(f3, text='Quit', command=root.destroy, width=16).pack(side='left', padx=(5, 0)) f3.pack(pady=(10, 20)) self.folders = [] self.files = [] ################################################################################################ def change_mode(self): if (self.nand_mode): self.nand_frame.pack_forget() self.chk.pack(padx=10, anchor=W) self.nand_mode = False else: if askokcancel( 'Warning', ('You are about to enter NAND mode. Do it only if you know ' 'what you are doing. Proceed?'), icon=WARNING): self.chk.pack_forget() self.nand_frame.pack(padx=10, pady=(0, 10), fill=X) self.nand_mode = True ################################################################################################ def enable_entries(self, status): self.cid_label['state'] = (NORMAL if status else DISABLED) self.cid_entry['state'] = (NORMAL if status else DISABLED) self.console_id_label['state'] = (NORMAL if status else DISABLED) self.console_id_entry['state'] = (NORMAL if status else DISABLED) ################################################################################################ def choose_nand(self): name = askopenfilename(filetypes=(('nand.bin', '*.bin'), ('DSi-1.mmc', '*.mmc'))) self.nand_file.set(name.encode(getpreferredencoding())) self.nand_button['state'] = (NORMAL if self.nand_file.get() != '' else DISABLED) self.start_button['state'] = (NORMAL if self.nand_file.get() != '' else DISABLED) ################################################################################################ def hiya(self): if not self.nand_mode: showinfo( 'Info', 'Now you will be asked to choose the SD card path that will be used ' 'for installing the custom firmware (or an output folder).\n\nIn order to avoid ' 'boot errors please assure it is empty before continuing.') self.sd_path = askdirectory() # Exit if no path was selected if self.sd_path == '': return # If adding a No$GBA footer, check if CID and ConsoleID values are OK elif self.nand_operation.get() == 2: cid = self.cid.get() console_id = self.console_id.get() # Check lengths if len(cid) != 32: showerror('Error', 'Bad eMMC CID') return elif len(console_id) != 16: showerror('Error', 'Bad Console ID') return # Parse strings to hex try: cid = cid.decode('hex') except TypeError: showerror('Error', 'Bad eMMC CID') return try: console_id = bytearray(reversed(console_id.decode('hex'))) except TypeError: showerror('Error', 'Bad Console ID') return dialog = Toplevel(self) # Open as dialog (parent disabled) dialog.grab_set() dialog.title('Status') # Disable maximizing dialog.resizable(0, 0) frame = Frame(dialog, bd=2, relief=SUNKEN) scrollbar = Scrollbar(frame) scrollbar.pack(side=RIGHT, fill=Y) self.log = ThreadSafeText(frame, bd=0, width=52, height=20, yscrollcommand=scrollbar.set) self.log.pack() scrollbar.config(command=self.log.yview) frame.pack() Button(dialog, text='Close', command=dialog.destroy, width=16).pack(pady=10) # Center in window dialog.update_idletasks() width = dialog.winfo_width() height = dialog.winfo_height() dialog.geometry( '%dx%d+%d+%d' % (width, height, root.winfo_x() + (root.winfo_width() / 2) - (width / 2), root.winfo_y() + (root.winfo_height() / 2) - (height / 2))) # Check if we'll be adding a No$GBA footer if self.nand_mode and self.nand_operation.get() == 2: Thread(target=self.add_footer, args=(cid, console_id)).start() else: Thread(target=self.check_nand).start() ################################################################################################ def check_nand(self): self.log.write('Checking NAND file...') # Read the NAND file try: with open(self.nand_file.get(), 'rb') as f: # Go to the No$GBA footer offset f.seek(-64, 2) # Read the footer's header :-) bstr = f.read(0x10) if bstr == b'DSi eMMC CID/CPU': # Read the CID bstr = f.read(0x10) self.cid.set(hexlify(bstr).upper()) self.log.write('- eMMC CID: ' + self.cid.get()) # Read the console ID bstr = f.read(8) self.console_id.set( hexlify(bytearray(reversed(bstr))).upper()) self.log.write('- Console ID: ' + self.console_id.get()) # Check we are making an unlaunch operation or removing the No$GBA footer if self.nand_mode: if self.nand_operation.get() == 0: Thread(target=self.decrypt_nand).start() else: Thread(target=self.remove_footer).start() pass else: Thread(target=self.get_latest_hiyacfw).start() else: self.log.write('ERROR: No$GBA footer not found') except IOError: self.log.write('ERROR: Could not open the file ' + path.basename(self.nand_file.get())) ################################################################################################ def get_latest_hiyacfw(self): # Try to use already downloaded HiyaCFW archive filename = 'HiyaCFW.7z' try: if path.isfile(filename): self.log.write('\nPreparing HiyaCFW...') else: self.log.write('\nDownloading latest HiyaCFW release...') conn = urlopen( 'https://api.github.com/repos/RocketRobz/hiyaCFW/releases/latest' ) latest = jsonify(conn) conn.close() urlretrieve(latest['assets'][0]['browser_download_url'], filename) self.log.write('- Extracting HiyaCFW archive...') exe = path.join(sysname, '7za') proc = Popen([ exe, 'x', '-bso0', '-y', filename, 'for PC', 'for SDNAND SD card' ]) ret_val = proc.wait() if ret_val == 0: self.folders.append('for PC') self.folders.append('for SDNAND SD card') # Got to decrypt NAND if bootloader.nds is present Thread(target=self.decrypt_nand if path.isfile( 'bootloader.nds') else self.extract_bios).start() else: self.log.write('ERROR: Extractor failed') except (URLError, IOError) as e: self.log.write('ERROR: Could not get HiyaCFW') if self.twilight.get(): self.log.write( '\nPlease download the latest versions of HiyaCFW and\nTWiLight Menu++ from:' ) self.log.write( '\nhttps://github.com/RocketRobz/hiyaCFW/releases') self.log.write( 'https://github.com/RocketRobz/TWiLightMenu/releases') self.log.write('\nThen place the files in this folder.') else: self.log.write( '\nPlease download the latest version of HiyaCFW from:') self.log.write( '\nhttps://github.com/RocketRobz/hiyaCFW/releases') self.log.write('\nThen place the file in this folder.') except OSError: self.log.write('ERROR: Could not execute ' + exe) ################################################################################################ def extract_bios(self): self.log.write('\nExtracting ARM7/ARM9 BIOS from NAND...') exe = path.join(sysname, 'twltool') try: proc = Popen([exe, 'boot2', '--in', self.nand_file.get()]) ret_val = proc.wait() if ret_val == 0: # Hash arm7.bin sha1_hash = sha1() with open('arm7.bin', 'rb') as f: sha1_hash.update(f.read()) self.log.write('- arm7.bin SHA1:\n ' + hexlify(sha1_hash.digest()).upper()) # Hash arm9.bin sha1_hash = sha1() with open('arm9.bin', 'rb') as f: sha1_hash.update(f.read()) self.log.write('- arm9.bin SHA1:\n ' + hexlify(sha1_hash.digest()).upper()) self.files.append('arm7.bin') self.files.append('arm9.bin') Thread(target=self.patch_bios).start() else: self.log.write('ERROR: Extractor failed') Thread(target=self.clean, args=(True, )).start() except OSError: self.log.write('ERROR: Could not execute ' + exe) Thread(target=self.clean, args=(True, )).start() ################################################################################################ def patch_bios(self): self.log.write('\nPatching ARM7/ARM9 BIOS...') try: self.patcher( path.join('for PC', 'bootloader files', 'bootloader arm7 patch.ips'), 'arm7.bin') self.patcher( path.join('for PC', 'bootloader files', 'bootloader arm9 patch.ips'), 'arm9.bin') # Hash arm7.bin sha1_hash = sha1() with open('arm7.bin', 'rb') as f: sha1_hash.update(f.read()) self.log.write('- Patched arm7.bin SHA1:\n ' + hexlify(sha1_hash.digest()).upper()) # Hash arm9.bin sha1_hash = sha1() with open('arm9.bin', 'rb') as f: sha1_hash.update(f.read()) self.log.write('- Patched arm9.bin SHA1:\n ' + hexlify(sha1_hash.digest()).upper()) Thread(target=self.arm9_prepend).start() except IOError: self.log.write('ERROR: Could not patch BIOS') Thread(target=self.clean, args=(True, )).start() except Exception: self.log.write('ERROR: Invalid patch header') Thread(target=self.clean, args=(True, )).start() ################################################################################################ def arm9_prepend(self): self.log.write('\nPrepending data to ARM9 BIOS...') try: with open('arm9.bin', 'rb') as f: data = f.read() with open('arm9.bin', 'wb') as f: with open( path.join('for PC', 'bootloader files', 'bootloader arm9 append to start.bin'), 'rb') as pre: f.write(pre.read()) f.write(data) # Hash arm9.bin sha1_hash = sha1() with open('arm9.bin', 'rb') as f: sha1_hash.update(f.read()) self.log.write('- Prepended arm9.bin SHA1:\n ' + hexlify(sha1_hash.digest()).upper()) Thread(target=self.make_bootloader).start() except IOError: self.log.write('ERROR: Could not prepend data to ARM9 BIOS') Thread(target=self.clean, args=(True, )).start() ################################################################################################ def make_bootloader(self): self.log.write('\nGenerating new bootloader...') exe = (path.join('for PC', 'bootloader files', 'ndstool') if sysname == 'Windows' else path.join(sysname, 'ndsblc')) try: proc = Popen([ exe, '-c', 'bootloader.nds', '-9', 'arm9.bin', '-7', 'arm7.bin', '-t', path.join('for PC', 'bootloader files', 'banner.bin'), '-h', path.join('for PC', 'bootloader files', 'header.bin') ]) ret_val = proc.wait() if ret_val == 0: # Hash bootloader.nds sha1_hash = sha1() with open('bootloader.nds', 'rb') as f: sha1_hash.update(f.read()) self.log.write('- bootloader.nds SHA1:\n ' + hexlify(sha1_hash.digest()).upper()) Thread(target=self.decrypt_nand).start() else: self.log.write('ERROR: Generator failed') Thread(target=self.clean, args=(True, )).start() except OSError: self.log.write('ERROR: Could not execute ' + exe) Thread(target=self.clean, args=(True, )).start() ################################################################################################ def decrypt_nand(self): self.log.write('\nDecrypting NAND...') exe = path.join(sysname, 'twltool') try: proc = Popen([ exe, 'nandcrypt', '--in', self.nand_file.get(), '--out', self.console_id.get() + '.img' ]) ret_val = proc.wait() if ret_val == 0: if not self.nand_mode: self.files.append(self.console_id.get() + '.img') Thread(target=self.mount_nand).start() else: self.log.write('ERROR: Decryptor failed') Thread(target=self.clean, args=(True, )).start() except OSError: self.log.write('ERROR: Could not execute ' + exe) Thread(target=self.clean, args=(True, )).start() ################################################################################################ def mount_nand(self): self.log.write('\nMounting decrypted NAND...') try: if sysname == 'Windows': exe = osfmount cmd = [ osfmount, '-a', '-t', 'file', '-f', self.console_id.get() + '.img', '-m', '#:', '-o', 'ro,rem' ] if self.nand_mode: cmd[-1] = 'rw,rem' proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) outs, errs = proc.communicate() if proc.returncode == 0: self.mounted = search(r'[a-zA-Z]:\s', outs).group(0).strip() self.log.write('- Mounted on drive ' + self.mounted) else: self.log.write('ERROR: Mounter failed') Thread(target=self.clean, args=(True, )).start() return elif sysname == 'Darwin': exe = 'hdiutil' cmd = [ exe, 'attach', '-imagekey', 'diskimage-class=CRawDiskImage', '-nomount', self.console_id.get() + '.img' ] if not self.nand_mode: cmd.insert(2, '-readonly') proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) outs, errs = proc.communicate() if proc.returncode == 0: self.raw_disk = search(r'^\/dev\/disk\d+', outs).group(0) self.log.write('- Mounted raw disk on ' + self.raw_disk) cmd = [exe, 'mount', self.raw_disk + 's1'] if not self.nand_mode: cmd.insert(2, '-readonly') proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) outs, errs = proc.communicate() if proc.returncode == 0: self.mounted = search(r'\/Volumes\/.+', outs).group(0) self.log.write('- Mounted volume on ' + self.mounted) else: self.log.write('ERROR: Mounter failed') Thread(target=self.clean, args=(True, )).start() return else: self.log.write('ERROR: Mounter failed') Thread(target=self.clean, args=(True, )).start() return else: # Linux exe = 'losetup' cmd = [ exe, '-P', '-f', '--show', self.console_id.get() + '.img' ] if not self.nand_mode: cmd.insert(2, '-r') proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) outs, errs = proc.communicate() if proc.returncode == 0: self.loop_dev = search(r'\/dev\/loop\d+', outs).group(0) self.log.write('- Mounted loop device on ' + self.loop_dev) exe = 'mount' self.mounted = '/mnt' cmd = [ exe, '-t', 'vfat', self.loop_dev + 'p1', self.mounted ] if not self.nand_mode: cmd.insert(1, '-r') proc = Popen(cmd) ret_val = proc.wait() if ret_val == 0: self.log.write('- Mounted partition on ' + self.mounted) else: self.log.write('ERROR: Mounter failed') Thread(target=self.clean, args=(True, )).start() return else: self.log.write('ERROR: Mounter failed') Thread(target=self.clean, args=(True, )).start() return # Check we are making an unlaunch operation Thread(target=self.unlaunch_proc if self.nand_mode else self. extract_nand).start() except OSError: self.log.write('ERROR: Could not execute ' + exe) Thread(target=self.clean, args=(True, )).start() ################################################################################################ def extract_nand(self): self.log.write('\nExtracting files from NAND...') err = False # Reset copied files cache _path_created.clear() try: copy_tree(self.mounted, self.sd_path, preserve_mode=0, update=1) except: self.log.write('ERROR: Extractor failed') err = True Thread(target=self.unmount_nand, args=(err, )).start() ################################################################################################ def unmount_nand(self, err=False): self.log.write('\nUnmounting NAND...') try: if sysname == 'Windows': exe = osfmount proc = Popen([osfmount, '-D', '-m', self.mounted]) elif sysname == 'Darwin': exe = 'hdiutil' proc = Popen([exe, 'detach', self.raw_disk]) else: # Linux exe = 'umount' proc = Popen([exe, self.mounted]) ret_val = proc.wait() if ret_val == 0: exe = 'losetup' proc = Popen([exe, '-d', self.loop_dev]) else: self.log.write('ERROR: Unmounter failed') Thread(target=self.clean, args=(True, )).start() return ret_val = proc.wait() if ret_val == 0: if err: Thread(target=self.clean, args=(True, )).start() else: Thread(target=self.encrypt_nand if self. nand_mode else self.get_launcher).start() else: self.log.write('ERROR: Unmounter failed') Thread(target=self.clean, args=(True, )).start() except OSError: self.log.write('ERROR: Could not execute ' + exe) Thread(target=self.clean, args=(True, )).start() ################################################################################################ def get_launcher(self): app = self.detect_region() # Stop if no supported region was found if not app: self.files.append('bootloader.nds') Thread(target=self.clean, args=(True, )).start() return # Check if unlaunch was installed on the NAND dump if path.getsize( path.join(self.sd_path, 'title', '00030017', app, 'content', 'title.tmd')) > 520: self.log.write('- WARNING: Unlaunch installed on the NAND dump') # Try to use already downloaded launcher try: if path.isfile(self.launcher_region): self.log.write('\nPreparing ' + self.launcher_region + ' launcher...') else: self.log.write('\nDownloading ' + self.launcher_region + ' launcher...') urlretrieve( 'https://raw.githubusercontent.com/mondul/HiyaCFW-Helper/master/' 'launchers/' + self.launcher_region, self.launcher_region) self.log.write('- Decrypting launcher...') exe = path.join(sysname, '7za') proc = Popen([ exe, 'x', '-bso0', '-y', '-p' + app, self.launcher_region, '00000002.app' ]) ret_val = proc.wait() if ret_val == 0: # Hash 00000002.app sha1_hash = sha1() with open('00000002.app', 'rb') as f: sha1_hash.update(f.read()) self.log.write('- Patched launcher SHA1:\n ' + hexlify(sha1_hash.digest()).upper()) Thread(target=self.install_hiyacfw, args=(path.join(self.sd_path, 'title', '00030017', app, 'content', '00000002.app'), )).start() else: self.log.write('ERROR: Extractor failed') Thread(target=self.clean, args=(True, )).start() except IOError: self.log.write('ERROR: Could not download ' + self.launcher_region + ' launcher') Thread(target=self.clean, args=(True, )).start() except OSError: self.log.write('ERROR: Could not execute ' + exe) Thread(target=self.clean, args=(True, )).start() ################################################################################################ def install_hiyacfw(self, launcher_path): self.log.write('\nCopying HiyaCFW files...') try: self.log.write('- Deleting stock launcher title.tmd...') if self.launcher_region == 'USA': remove( path.join(self.sd_path, 'title', '00030017', '484e4145', 'content', 'title.tmd')) if self.launcher_region == 'JAP': remove( path.join(self.sd_path, 'title', '00030017', '484e414a', 'content', 'title.tmd')) if self.launcher_region == 'EUR': remove( path.join(self.sd_path, 'title', '00030017', '484e4150', 'content', 'title.tmd')) if self.launcher_region == 'AUS': remove( path.join(self.sd_path, 'title', '00030017', '484e4155', 'content', 'title.tmd')) except: pass copy_tree('for SDNAND SD card', self.sd_path, update=1) move('bootloader.nds', path.join(self.sd_path, 'hiya', 'bootloader.nds')) move('00000002.app', launcher_path) Thread(target=self.get_latest_twilight if self.twilight.get() == 1 else self.clean).start() ################################################################################################ def get_latest_twilight(self): filename = False # Release archives names names = ('TWiLightMenu.7z', 'DSiMenuPP.7z', 'DSiMenuPlusPlus.7z', 'SRLoader.7z') for name in names: if (path.isfile(name)): filename = name break try: if filename: self.log.write('\nPreparing custom firmware...') else: self.log.write( '\nDownloading latest TWiLight Menu++ release...') conn = urlopen( 'https://api.github.com/repos/RocketRobz/TWiLightMenu/releases/' 'latest') latest = jsonify(conn) conn.close() filename = names[0] urlretrieve(latest['assets'][0]['browser_download_url'], filename) self.log.write('- Extracting ' + filename[:-3] + ' archive...') exe = path.join(sysname, '7za') proc = Popen([ exe, 'x', '-bso0', '-y', filename, 'Autoboot for HiyaCFW', 'CFW - SDNAND root', 'DSiWare (' + self.launcher_region + ')', '_nds', 'roms', 'BOOT.NDS' ]) ret_val = proc.wait() if ret_val == 0: self.folders.append('Autoboot for HiyaCFW') self.folders.append('CFW - SDNAND root') self.folders.append('DSiWare (' + self.launcher_region + ')') Thread(target=self.install_twilight, args=(filename[:-3], )).start() else: self.log.write('ERROR: Extractor failed') Thread(target=self.clean, args=(True, )).start() except (URLError, IOError) as e: self.log.write('ERROR: Could not get TWiLight Menu++') Thread(target=self.clean, args=(True, )).start() except OSError: self.log.write('ERROR: Could not execute ' + exe) Thread(target=self.clean, args=(True, )).start() ################################################################################################ def install_twilight(self, name): self.log.write('\nCopying ' + name + ' files...') copy_tree('CFW - SDNAND root', self.sd_path, update=1) move('_nds', path.join(self.sd_path, '_nds')) move('roms', path.join(self.sd_path, 'roms')) move('BOOT.NDS', path.join(self.sd_path, 'BOOT.NDS')) copy_tree('DSiWare (' + self.launcher_region + ')', path.join(self.sd_path, 'roms', 'dsiware'), update=1) move(path.join('Autoboot for HiyaCFW', 'autoboot.bin'), path.join(self.sd_path, 'hiya', 'autoboot.bin')) # Set files as read-only twlcfg0 = path.join(self.sd_path, 'shared1', 'TWLCFG0.dat') twlcfg1 = path.join(self.sd_path, 'shared1', 'TWLCFG1.dat') if sysname == 'Darwin': Popen(['chflags', 'uchg', twlcfg0, twlcfg1]).wait() elif sysname == 'Linux': Popen([path.join('Linux', 'fatattr'), '+R', twlcfg0, twlcfg1]).wait() else: chmod(twlcfg0, 292) chmod(twlcfg1, 292) # Generate launchargs for app in listdir(path.join(self.sd_path, 'title', '00030004')): try: for title in listdir( path.join(self.sd_path, 'title', '00030004', app, 'content')): if title.endswith('.app'): with open( path.join(self.sd_path, 'roms', 'dsiware', app + '.launcharg'), 'w') as launcharg: launcharg.write('sd:/title/00030004/' + app + '/') except: pass Thread(target=self.clean).start() ################################################################################################ def clean(self, err=False): self.log.write('\nCleaning...') while len(self.folders) > 0: rmtree(self.folders.pop(), ignore_errors=True) while len(self.files) > 0: try: remove(self.files.pop()) except: pass if err: self.log.write('Done') return # Get logged user in Linux if sysname == 'Linux': from os import getlogin # Workaround for some Linux systems where this function does not work try: ug = getlogin() except OSError: ug = 'root' if (self.nand_mode): file = self.console_id.get() + self.suffix + '.bin' rename(self.console_id.get() + '.img', file) # Change owner of the file in Linux if sysname == 'Linux': Popen(['chown', '-R', ug + ':' + ug, file]).wait() self.log.write('\nDone!\nModified NAND stored as\n' + file) return # Change owner of the out folder in Linux if sysname == 'Linux': Popen(['chown', '-R', ug + ':' + ug, self.sd_path]).wait() self.log.write( 'Done!\nExtract your SD card and insert it into your DSi') ################################################################################################ def patcher(self, patchpath, filepath): patch_size = path.getsize(patchpath) patchfile = open(patchpath, 'rb') if patchfile.read(5) != b'PATCH': patchfile.close() raise Exception() target = open(filepath, 'r+b') # Read First Record r = patchfile.read(3) while patchfile.tell() not in [patch_size, patch_size - 3]: # Unpack 3-byte pointers. offset = self.unpack_int(r) # Read size of data chunk r = patchfile.read(2) size = self.unpack_int(r) if size == 0: # RLE Record r = patchfile.read(2) rle_size = self.unpack_int(r) data = patchfile.read(1) * rle_size else: data = patchfile.read(size) # Write to file target.seek(offset) target.write(data) # Read Next Record r = patchfile.read(3) if patch_size - 3 == patchfile.tell(): trim_size = self.unpack_int(patchfile.read(3)) target.truncate(trim_size) # Cleanup target.close() patchfile.close() ################################################################################################ def unpack_int(self, bstr): # Read an n-byte big-endian integer from a byte string (ret_val, ) = unpack_from('>I', b'\x00' * (4 - len(bstr)) + bstr) return ret_val ################################################################################################ def detect_region(self): REGION_CODES = { '484e4145': 'USA', '484e414a': 'JAP', '484e4150': 'EUR', '484e4155': 'AUS' } # Autodetect console region base = self.mounted if self.nand_mode else self.sd_path try: for app in listdir(path.join(base, 'title', '00030017')): for file in listdir( path.join(base, 'title', '00030017', app, 'content')): if file.endswith('.app'): try: self.log.write('- Detected ' + REGION_CODES[app] + ' console NAND dump') self.launcher_region = REGION_CODES[app] return app except KeyError: self.log.write('ERROR: Unsupported console region') return False self.log.write('ERROR: Could not detect console region') except OSError as e: self.log.write('ERROR: ' + e.strerror + ': ' + e.filename) return False ################################################################################################ def unlaunch_proc(self): self.log.write('\nChecking unlaunch status...') app = self.detect_region() # Stop if no supported region was found if not app: # TODO: Unmount NAND return tmd = path.join(self.mounted, 'title', '00030017', app, 'content', 'title.tmd') tmd_size = path.getsize(tmd) if tmd_size == 520: self.log.write('- Not installed. Downloading v1.4...') try: filename = urlretrieve( 'http://problemkaputt.de/unlau14.zip')[0] exe = path.join(sysname, '7za') proc = Popen( [exe, 'x', '-bso0', '-y', filename, 'UNLAUNCH.DSI']) ret_val = proc.wait() if ret_val == 0: self.files.append(filename) self.files.append('UNLAUNCH.DSI') self.log.write('- Installing unlaunch...') self.suffix = '-unlaunch' with open(tmd, 'ab') as f: with open('UNLAUNCH.DSI', 'rb') as unl: f.write(unl.read()) # Set files as read-only for file in listdir( path.join(self.mounted, 'title', '00030017', app, 'content')): file = path.join(self.mounted, 'title', '00030017', app, 'content', file) if sysname == 'Darwin': Popen(['chflags', 'uchg', file]).wait() elif sysname == 'Linux': Popen([path.join('Linux', 'fatattr'), '+R', file]).wait() else: chmod(file, 292) else: self.log.write('ERROR: Extractor failed') # TODO: Unmount NAND except IOError: self.log.write('ERROR: Could not get unlaunch') # TODO: Unmount NAND except OSError: self.log.write('ERROR: Could not execute ' + exe) # TODO: Unmount NAND else: self.log.write('- Installed. Uninstalling...') self.suffix = '-no-unlaunch' # Set files as read-write for file in listdir( path.join(self.mounted, 'title', '00030017', app, 'content')): file = path.join(self.mounted, 'title', '00030017', app, 'content', file) if sysname == 'Darwin': Popen(['chflags', 'nouchg', file]).wait() elif sysname == 'Linux': Popen([path.join('Linux', 'fatattr'), '-R', file]).wait() else: chmod(file, 438) with open(tmd, 'r+b') as f: f.truncate(520) Thread(target=self.unmount_nand).start() ################################################################################################ def encrypt_nand(self): self.log.write('\nEncrypting back NAND...') exe = path.join(sysname, 'twltool') try: proc = Popen( [exe, 'nandcrypt', '--in', self.console_id.get() + '.img']) ret_val = proc.wait() if ret_val == 0: Thread(target=self.clean).start() else: self.log.write('ERROR: Encryptor failed') except OSError: self.log.write('ERROR: Could not execute ' + exe) ################################################################################################ def remove_footer(self): self.log.write('\nRemoving No$GBA footer...') file = self.console_id.get() + '-no-footer.bin' try: copyfile(self.nand_file.get(), file) # Back-up footer info with open(self.console_id.get() + '-info.txt', 'wb') as f: f.write('eMMC CID: ' + self.cid.get() + '\r\n') f.write('Console ID: ' + self.console_id.get() + '\r\n') with open(file, 'r+b') as f: # Go to the No$GBA footer offset f.seek(-64, 2) # Remove footer f.truncate() # Change owner of the file in Linux if sysname == 'Linux': from os import getlogin ug = getlogin() Popen(['chown', '-R', ug + ':' + ug, file]).wait() self.log.write('\nDone!\nModified NAND stored as\n' + file + '\nStored footer info in ' + self.console_id.get() + '-info.txt') except IOError: self.log.write('ERROR: Could not open the file ' + path.basename(self.nand_file.get())) ################################################################################################ def add_footer(self, cid, console_id): self.log.write('Adding No$GBA footer...') file = self.console_id.get() + '-footer.bin' try: copyfile(self.nand_file.get(), file) with open(file, 'r+b') as f: # Go to the No$GBA footer offset f.seek(-64, 2) # Read the footer's header :-) bstr = f.read(0x10) # Check if it already has a footer if bstr == b'DSi eMMC CID/CPU': self.log.write('ERROR: File already has a No$GBA footer') f.close() remove(file) return # Go to the end of file f.seek(0, 2) # Write footer f.write(b'DSi eMMC CID/CPU') f.write(cid) f.write(console_id) f.write('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') self.log.write('\nDone!\nModified NAND stored as\n' + file) except IOError: self.log.write('ERROR: Could not open the file ' + path.basename(self.nand_file.get()))
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("IAF CALC 0.01") self.pack(fill=BOTH, expand=1) self.configure(background="white") frameTOP = Frame(self) frameTOP.config(bg="white") frameTOP.pack(side=TOP) frameFILES = Frame(frameTOP) frameFILES.pack(side=LEFT, padx=10) # --- BUTTON FOR FILE 1 --- # frameF1 = LabelFrame(frameFILES, text="Eyes open file:", relief=FLAT, borderwidth=1, background="white") frameF1.pack(fill=X, expand=1) self.nameF1 = Entry(frameF1, width=50) self.nameF1.config(bg="lightgray") self.nameF1.pack(side=LEFT) self.nameF1.delete(0, END) self.nameF1.insert(0, "") self.buttonLoadFile1 = Button(frameF1, text="...", command=self.askOpenFile1) self.buttonLoadFile1.pack(side=LEFT, padx=5, pady=5) # ----------------------- # # --- BUTTON FOR FILE 2 --- # frameF2 = LabelFrame(frameFILES, text="Eyes closed file:", relief=FLAT, borderwidth=1, background="white") frameF2.pack(fill=X, expand=1) self.nameF2 = Entry(frameF2, width=50) self.nameF2.config(bg="lightgray") self.nameF2.pack(side=LEFT) self.nameF2.delete(0, END) self.nameF2.insert(0, "") self.buttonLoadFile2 = Button(frameF2, text="...", command=self.askOpenFile2) self.buttonLoadFile2.pack(side=LEFT, padx=5, pady=5) # ----------------------- # # --- BUTTON FOR FILE OUTPUT --- # frameO = LabelFrame(frameFILES, text="Output directory:", relief=FLAT, borderwidth=1, background="white") frameO.pack(fill=X, expand=1) self.nameO = Entry(frameO, width=50) self.nameO.config(bg="lightgray") self.nameO.pack(side=LEFT) self.nameO.delete(0, END) self.nameO.insert(0, "") self.buttonSelectOutput = Button(frameO, text="...", command=self.askOutputDirectory) self.buttonSelectOutput.pack(side=LEFT, padx=5, pady=5) # -------------------------------# # self.pack() # self.pack(fill=Y, expand=1) # ---------- PSD PARAMETER SELECTION ---------- # framePARAM = Frame(frameTOP) framePARAM.config(bg="white") framePARAM.pack(side=LEFT, fill=X) frame = LabelFrame(framePARAM, text="PSD Parameters", relief=RIDGE, borderwidth=1, background="white") frame.pack(fill=BOTH, expand=1, side=TOP) wFs = Label(frame, text="Fs:", bg="white") wFs.pack(side=LEFT) self.inputFs = Entry(frame, width=5) self.inputFs.pack(side=LEFT, padx=5) self.inputFs.delete(0, END) self.inputFs.insert(0, "500") wWS = Label(frame, text="Window size:", bg="white") wWS.pack(side=LEFT) self.inputWinSize = Entry(frame, width=5) self.inputWinSize.pack(side=LEFT, padx=5) self.inputWinSize.delete(0, END) self.inputWinSize.insert(0, "1024") wOL = Label(frame, text="Overlap:", bg="white") wOL.pack(side=LEFT) self.inputOverlap = Entry(frame, width=5) self.inputOverlap.pack(side=LEFT, padx=5) self.inputOverlap.delete(0, END) self.inputOverlap.insert(0, "512") wWT = Label(frame, text="Window function:", bg="white") wWT.pack(side=LEFT) variable = StringVar(frame) variable.set("Hamming") # default value self.inputWinType = OptionMenu(frame, variable, "Hamming", "Bartlett", "Blackman", "Hanning", "None") self.inputWinType.config(bg="white", width=10) self.inputWinType.pack(side=LEFT) buttonRun = Button(frame, text="GO!", command=self.goTime) buttonRun.pack(side=RIGHT) # Channel selector frameCh = LabelFrame(framePARAM, text="Channels", relief=RIDGE, borderwidth=1, background="white") frameCh.pack(fill=BOTH, expand=1, side=TOP) self.EOch1 = IntVar() self.inputEOch1 = Checkbutton(frameCh, text="1", variable=self.EOch1, bg="white") self.inputEOch1.pack(side=LEFT) self.EOch2 = IntVar() self.inputEOch2 = Checkbutton(frameCh, text="2", variable=self.EOch2, bg="white") self.inputEOch2.pack(side=LEFT) self.EOch3 = IntVar() self.inputEOch3 = Checkbutton(frameCh, text="3", variable=self.EOch3, bg="white") self.inputEOch3.pack(side=LEFT) self.EOch4 = IntVar() self.inputEOch4 = Checkbutton(frameCh, text="4", variable=self.EOch4, bg="white") self.inputEOch4.pack(side=LEFT) self.EOch5 = IntVar() self.inputEOch5 = Checkbutton(frameCh, text="5", variable=self.EOch5, bg="white") self.inputEOch5.pack(side=LEFT) self.EOch6 = IntVar() self.inputEOch6 = Checkbutton(frameCh, text="6", variable=self.EOch6, bg="white") self.inputEOch6.pack(side=LEFT) self.EOch7 = IntVar() self.inputEOch7 = Checkbutton(frameCh, text="7", variable=self.EOch7, bg="white") self.inputEOch7.pack(side=LEFT) self.EOch8 = IntVar() self.inputEOch8 = Checkbutton(frameCh, text="8", variable=self.EOch8, bg="white") self.inputEOch8.pack(side=LEFT) # IAF Calculation parameters frameIAF = LabelFrame(framePARAM, text="IAF Search Limits", relief=RIDGE, borderwidth=1, background="white") frameIAF.pack(fill=BOTH, expand=1, side=TOP) labelLowBound = Label(frameIAF, text="Lower limit (Hz):", bg="white") labelLowBound.pack(side=LEFT) self.inputLowBound = Entry(frameIAF, width=5) self.inputLowBound.pack(side=LEFT, padx=5) self.inputLowBound.delete(0, END) self.inputLowBound.insert(0, "7") labelUpBound = Label(frameIAF, text="Upper limit (Hz):", bg="white") labelUpBound.pack(side=LEFT) self.inputUpBound = Entry(frameIAF, width=5) self.inputUpBound.pack(side=LEFT, padx=5) self.inputUpBound.delete(0, END) self.inputUpBound.insert(0, "14") self.GaussVar = IntVar() self.inputGauss = Checkbutton(frameIAF, text="Gauss", variable=self.GaussVar, bg="white") self.inputGauss.pack(side=LEFT) buttonRun = Button(frameIAF, text="IAF!", command=self.calculateIAF) buttonRun.pack(side=RIGHT) self.pack() # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # END OF TOP FRAME # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # my variables self.chSelect = 0 self.chOther = 0 self.P1 = ndarray(1) self.f1 = ndarray(1) self.P2 = ndarray(1) self.f2 = ndarray(1) self.filename1 = "..." self.filename2 = "..." self.IAF = 10 self.doGauss = True # FIGURE STUFF !!! self.Pmax = 0 self.Pmin = 0 self.Dmax = 0 self.Dmin = 0 frameBOTTOM = Frame(self) frameBOTTOM.config(bg="white") frameBOTTOM.pack(side=BOTTOM, pady=10) frameFig = LabelFrame(frameBOTTOM, text="Spectrum", relief=RIDGE, borderwidth=1, background="white") frameFig.pack(fill=X, expand=1, side=LEFT, padx=10) self.fig1 = matplotlib.figure.Figure(figsize=(7, 3), dpi=100) # ,frameon=False) self.fig1.set_facecolor("white") self.fig = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(self.fig1, master=frameFig) self.a1 = self.fig1.add_subplot(121) self.a2 = self.fig1.add_subplot(122) self.fig.show() self.fig.get_tk_widget().pack(side=BOTTOM) frameConfig = LabelFrame( frameBOTTOM, text="Filter configuration", relief=RAISED, borderwidth=1, background="white" ) frameConfig.pack(fill=BOTH, expand=1, side=RIGHT, padx=10) frameIAF = LabelFrame(frameConfig, text="Individual Alpha Frequency (IAF)") frameIAF.config(bg="white") frameIAF.pack(expand=1, side=TOP, padx=10) self.inputIAF = Entry(frameIAF, width=5) self.inputIAF.pack(side=LEFT, padx=5) self.inputIAF.delete(0, END) self.inputIAF.insert(0, "0") self.buttonWriteDefault = Button(frameIAF, text="Update Filters", command=self.updateFilters) self.buttonWriteDefault.pack(side=LEFT, padx=5, pady=5) frameFilters = LabelFrame(frameConfig, text="Filters", relief=RAISED, borderwidth=1, background="white") frameFilters.pack(fill=X, expand=1, side=TOP) # THETA FRAME frameTheta = LabelFrame(frameFilters, text="Theta", relief=RAISED, borderwidth=1, background="white") frameTheta.pack(expand=1, side=TOP, pady=5, padx=5) self.inputThetaLow = Entry(frameTheta, width=8) self.inputThetaLow.pack(side=LEFT, padx=5, pady=5) self.inputThetaLow.delete(0, END) self.inputThetaLow.insert(0, "0") self.inputThetaHigh = Entry(frameTheta, width=8) self.inputThetaHigh.pack(side=LEFT, padx=5, pady=5) self.inputThetaHigh.delete(0, END) self.inputThetaHigh.insert(0, "0") # BETA FRAME frameBeta = LabelFrame(frameFilters, text="Beta", relief=RAISED, borderwidth=1, background="white") frameBeta.pack(expand=1, side=TOP, pady=5, padx=5) self.inputBetaLow = Entry(frameBeta, width=8) self.inputBetaLow.pack(side=LEFT, padx=5, pady=5) self.inputBetaLow.delete(0, END) self.inputBetaLow.insert(0, "0") self.inputBetaHigh = Entry(frameBeta, width=8) self.inputBetaHigh.pack(side=LEFT, padx=5, pady=5) self.inputBetaHigh.delete(0, END) self.inputBetaHigh.insert(0, "0") # SMR FRAME frameSMR = LabelFrame(frameFilters, text="SMR", relief=RAISED, borderwidth=1, background="white") frameSMR.pack(expand=1, side=TOP, pady=5, padx=5) self.inputSMRLow = Entry(frameSMR, width=8) self.inputSMRLow.pack(side=LEFT, padx=5, pady=5) self.inputSMRLow.delete(0, END) self.inputSMRLow.insert(0, "0") self.inputSMRHigh = Entry(frameSMR, width=8) self.inputSMRHigh.pack(side=LEFT, padx=5, pady=5) self.inputSMRHigh.delete(0, END) self.inputSMRHigh.insert(0, "0") frameButtons = LabelFrame(frameConfig, text="Commands", relief=RAISED, borderwidth=1, background="white") frameButtons.pack(expand=1, side=BOTTOM) self.buttonWriteConfig = Button(frameButtons, text="Write Filters", command=self.writeFilters) self.buttonWriteConfig.pack(side=LEFT, padx=5, pady=5) self.buttonWriteDefault = Button(frameButtons, text="Reset to Defaults", command=self.resetIAFtoDefault) self.buttonWriteDefault.pack(side=LEFT, padx=5, pady=5) # self.buttonVisualize = Button(frameButtons, text="VIS",command=self.resetIAFtoDefault) # self.buttonVisualize.pack(side=LEFT,padx=5,pady=5) self.buttonPrintFig = Button(frameButtons, text="Print Figure", command=self.printFigureToFile) self.buttonPrintFig.pack(side=LEFT, padx=5, pady=5) def getChannelList(self): # Initialize self.chSelect = asarray([]) self.chOther = asarray([]) if self.EOch1.get(): self.chSelect = append(self.chSelect, 0) else: self.chOther = append(self.chOther, 0) if self.EOch2.get(): self.chSelect = append(self.chSelect, 1) else: self.chOther = append(self.chOther, 1) if self.EOch3.get(): self.chSelect = append(self.chSelect, 2) else: self.chOther = append(self.chOther, 2) if self.EOch4.get(): self.chSelect = append(self.chSelect, 3) else: self.chOther = append(self.chOther, 3) if self.EOch5.get(): self.chSelect = append(self.chSelect, 4) else: self.chOther = append(self.chOther, 4) if self.EOch6.get(): self.chSelect = append(self.chSelect, 5) else: self.chOther = append(self.chOther, 5) if self.EOch7.get(): self.chSelect = append(self.chSelect, 6) else: self.chOther = append(self.chOther, 6) if self.EOch8.get(): self.chSelect = append(self.chSelect, 7) else: self.chOther = append(self.chOther, 7) def updateFilters(self): # SET THETA self.inputThetaLow.delete(0, END) self.inputThetaLow.insert(0, "%.2f" % (float(self.inputIAF.get()) * 0.4)) self.inputThetaHigh.delete(0, END) self.inputThetaHigh.insert(0, "%.2f" % (float(self.inputIAF.get()) * 0.6)) # SET BETA self.inputBetaLow.delete(0, END) self.inputBetaLow.insert(0, "%.2f" % (float(self.inputIAF.get()) * 1.2)) self.inputBetaHigh.delete(0, END) self.inputBetaHigh.insert(0, 25) # SET SMR self.inputSMRLow.delete(0, END) self.inputSMRLow.insert(0, "%.2f" % (float(self.inputIAF.get()) * 1.2)) self.inputSMRHigh.delete(0, END) self.inputSMRHigh.insert(0, "%.2f" % (float(self.inputIAF.get()) * 1.5)) def resetIAFtoDefault(self): self.inputIAF.delete(0, END) self.inputIAF.insert(0, "10") self.updateFilters() def calculateIAF(self): self.getChannelList() print "LOLOL calculating IAF" m1 = 20 * log10(mean(self.P1[self.chSelect.astype(int), :], axis=0)) m2 = 20 * log10(mean(self.P2[self.chSelect.astype(int), :], axis=0)) d = m2 - m1 if self.GaussVar.get(): # print d.shape # print gauss_signal.shape d_gauss = d[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] gauss_signal = signal.gaussian(d_gauss.shape[0], 1) d_gauss = d_gauss * gauss_signal d[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] = d_gauss self.a2 = plotIAF(self.f1, d, "purple", self.a2, "IAF") # Get dat IAF val d_search = d[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] f_search = self.f1[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] f_idx = argmax(d_search) print f_search[f_idx] self.inputIAF.delete(0, END) self.inputIAF.insert(0, "%.2f" % (f_search[f_idx])) # Autoscale self.Dmin = amin(d_search) - 2 self.Dmax = amax(d_search) + 2 self.a2.set_ylim(self.Dmin, self.Dmax) # little modifier to differentiate the peak # IAF position self.a2.vlines(f_search[f_idx], self.Dmin, self.Dmax, color="Cyan") # Search limits self.a2.vlines(int(self.inputLowBound.get()), self.Dmin, self.Dmax, linestyles=":", linewidth=0.25) self.a2.vlines(int(self.inputUpBound.get()), self.Dmin, self.Dmax, linestyles=":", linewidth=0.25) self.fig.show() # Set filter configs def goTime(self): print "ITS GO TIME!" print self.filename1 print self.filename2 self.getChannelList() print self.chSelect print self.chOther self.f1, self.P1 = computeSpectrum( self.filename1, int(self.inputFs.get()), int(self.inputWinSize.get()), int(self.inputOverlap.get()) ) self.f2, self.P2 = computeSpectrum( self.filename2, int(self.inputFs.get()), int(self.inputWinSize.get()), int(self.inputOverlap.get()) ) # Plotting time self.a1.cla() self.a1 = plotSpectrum(self.f1, self.P1, "blue", self.a1, "Power spectrum", self.chSelect, self.chOther) self.a1 = plotSpectrum(self.f2, self.P2, "red", self.a1, "Power spectrum", self.chSelect, self.chOther) # Trying to autoscale P1_ROI = 20 * log10(self.P1[:, bitwise_and(self.f1 > 1, self.f1 < 20)]) P2_ROI = 20 * log10(self.P2[:, bitwise_and(self.f2 > 1, self.f2 < 20)]) self.Pmax = amax([amax(P1_ROI), amax(P2_ROI)]) self.Pmin = amin([(amin(P1_ROI)), amin(P2_ROI)]) self.a1.set_ylim(self.Pmin, self.Pmax) # Autoscale success :> self.fig.show() def writeFilters(self): f_theta = open(self.nameO.get() + "/theta.f", "w") f_theta.write( "<OpenViBE-SettingsOverride>\n\t<SettingValue>Butterworth</SettingValue>\n\t<SettingValue>Band pass</SettingValue>\n\t<SettingValue>4</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>0.5</SettingValue>\n</OpenViBE-SettingsOverride>".format( float(self.inputThetaLow.get()), float(self.inputThetaHigh.get()) ) ) f_theta.close() f_beta = open(self.nameO.get() + "/beta.f", "w") f_beta.write( "<OpenViBE-SettingsOverride>\n\t<SettingValue>Butterworth</SettingValue>\n\t<SettingValue>Band pass</SettingValue>\n\t<SettingValue>4</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>0.5</SettingValue>\n</OpenViBE-SettingsOverride>".format( float(self.inputBetaLow.get()), float(self.inputBetaHigh.get()) ) ) f_beta.close() f_smr = open(self.nameO.get() + "/smr.f", "w") f_smr.write( "<OpenViBE-SettingsOverride>\n\t<SettingValue>Butterworth</SettingValue>\n\t<SettingValue>Band pass</SettingValue>\n\t<SettingValue>4</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>0.5</SettingValue>\n</OpenViBE-SettingsOverride>".format( float(self.inputSMRLow.get()), float(self.inputSMRHigh.get()) ) ) f_smr.close() def printFigureToFile(self): self.fig1.savefig(self.nameO.get() + "/IAF_spectrum.png") def askOpenFile1(self): ftypes = [("asdadfh", "*.txt"), ("All files", "*")] dlg = tkFileDialog.Open(self, filetypes=ftypes) self.filename1 = dlg.show() self.nameF1.delete(0, END) self.nameF1.insert(0, self.filename1) def askOpenFile2(self): ftypes = [("asdadfh", "*.txt"), ("All files", "*")] dlg = tkFileDialog.Open(self, filetypes=ftypes) self.filename2 = dlg.show() self.nameF2.delete(0, END) self.nameF2.insert(0, self.filename2) def askOutputDirectory(self): dlg = tkFileDialog.askdirectory() # self.outputdir = dlg.show() self.outputdir = dlg self.nameO.delete(0, END) self.nameO.insert(0, self.outputdir)
class sideWindow(AppShell): ################################################################# # sideWindow(AppShell) # This class will open a side window wich contains a scene graph and # a world setting page. ################################################################# appversion = '1.0' appname = 'Navigation Window' frameWidth = 325 frameHeight = 580 frameIniPosX = 0 frameIniPosY = 110 padx = 0 pady = 0 lightEnable = 0 ParticleEnable = 0 basedriveEnable = 0 collision = 0 backface = 0 texture = 1 wireframe = 0 enableBaseUseDrive = 0 def __init__(self, worldColor, lightEnable, ParticleEnable, basedriveEnable, collision, backface, texture, wireframe, grid, widgetVis, enableAutoCamera, parent=None, nodePath=render, **kw): self.worldColor = worldColor self.lightEnable = lightEnable self.ParticleEnable = ParticleEnable self.basedriveEnable = basedriveEnable self.collision = collision self.backface = backface self.texture = texture self.wireframe = wireframe self.grid = grid self.enableAutoCamera = enableAutoCamera self.widgetVis = widgetVis # Define the megawidget options. optiondefs = (('title', self.appname, None), ) self.defineoptions(kw, optiondefs) if parent == None: self.parent = Toplevel() else: self.parent = parent AppShell.__init__(self, self.parent) self.parent.geometry('%dx%d+%d+%d' % (self.frameWidth, self.frameHeight, self.frameIniPosX, self.frameIniPosY)) self.parent.resizable( False, False) ## Disable the ability to resize for this Window. def appInit(self): print '----SideWindow is Initialized!!' def createInterface(self): # The interior of the toplevel panel interior = self.interior() mainFrame = Frame(interior) ## Creat NoteBook self.notebookFrame = Pmw.NoteBook(mainFrame) self.notebookFrame.pack(fill=Tkinter.BOTH, expand=1) sgePage = self.notebookFrame.add('Tree Graph') envPage = self.notebookFrame.add('World Setting') self.notebookFrame['raisecommand'] = self.updateInfo ## Tree Grapgh Page self.SGE = seSceneGraphExplorer.seSceneGraphExplorer( sgePage, nodePath=render, scrolledCanvas_hull_width=270, scrolledCanvas_hull_height=570) self.SGE.pack(fill=Tkinter.BOTH, expand=0) ## World Setting Page envPage = Frame(envPage) pageFrame = Frame(envPage) self.LightingVar = IntVar() self.LightingVar.set(self.lightEnable) self.LightingButton = Checkbutton(pageFrame, text='Enable Lighting', variable=self.LightingVar, command=self.toggleLights) self.LightingButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.CollisionVar = IntVar() self.CollisionVar.set(self.collision) self.CollisionButton = Checkbutton(pageFrame, text='Show Collision Object', variable=self.CollisionVar, command=self.showCollision) self.CollisionButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.ParticleVar = IntVar() self.ParticleVar.set(self.ParticleEnable) self.ParticleButton = Checkbutton(pageFrame, text='Show Particle Dummy', variable=self.ParticleVar, command=self.enableParticle) self.ParticleButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.baseUseDriveVar = IntVar() self.baseUseDriveVar.set(self.basedriveEnable) self.baseUseDriveButton = Checkbutton(pageFrame, text='Enable base.usedrive', variable=self.baseUseDriveVar, command=self.enablebaseUseDrive) self.baseUseDriveButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.backfaceVar = IntVar() self.backfaceVar.set(self.backface) self.backfaceButton = Checkbutton(pageFrame, text='Enable BackFace', variable=self.backfaceVar, command=self.toggleBackface) self.backfaceButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.textureVar = IntVar() self.textureVar.set(self.texture) self.textureButton = Checkbutton(pageFrame, text='Enable Texture', variable=self.textureVar, command=self.toggleTexture) self.textureButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.wireframeVar = IntVar() self.wireframeVar.set(self.wireframe) self.wireframeButton = Checkbutton(pageFrame, text='Enable Wireframe', variable=self.wireframeVar, command=self.toggleWireframe) self.wireframeButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.gridVar = IntVar() self.gridVar.set(self.grid) self.gridButton = Checkbutton(pageFrame, text='Enable Grid', variable=self.gridVar, command=self.toggleGrid) self.gridButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.widgetVisVar = IntVar() self.widgetVisVar.set(self.widgetVis) self.widgetVisButton = Checkbutton(pageFrame, text='Enable WidgetVisible', variable=self.widgetVisVar, command=self.togglewidgetVis) self.widgetVisButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.enableAutoCameraVar = IntVar() self.enableAutoCameraVar.set(self.enableAutoCamera) self.enableAutoCameraButton = Checkbutton( pageFrame, text='Enable Auto Camera Movement for Loading Objects', variable=self.enableAutoCameraVar, command=self.toggleAutoCamera) self.enableAutoCameraButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.backgroundColor = ColorEntry(pageFrame, text='BG Color', value=self.worldColor) self.backgroundColor['command'] = self.setBackgroundColorVec self.backgroundColor['resetValue'] = [0, 0, 0, 0] self.backgroundColor.pack(side=Tkinter.LEFT, expand=False) self.bind(self.backgroundColor, 'Set background color') pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) envPage.pack(expand=False) ## Set all stuff done self.notebookFrame.setnaturalsize() mainFrame.pack(fill='both', expand=1) def createMenuBar(self): # We don't need menu bar here. self.menuBar.destroy() def onDestroy(self, event): ################################################################# # onDestroy(self, event) # This function will be called when user closed the side window. # Here we will send out a message with whole data set we will need # for the next time user open the side window. ################################################################# messenger.send('SW_close', [ self.worldColor, self.lightEnable, self.ParticleEnable, self.basedriveEnable, self.collision, self.backface, self.texture, self.wireframe, self.grid, self.widgetVis, self.enableAutoCamera ]) ''' If you have open any thing, please rewrite here! ''' pass ############################### def updateInfo(self, page='Tree Graph'): ################################################################# # updateInfo(self, page = 'Tree Graph') # This function will be called when each time user change the main # page of the window. # What it dose is to call right function to restore the data for current selected page. ################################################################# if page == 'Tree Graph': self.updateTreeGraph() elif page == 'World Setting': self.updateWorldSetting() def updateTreeGraph(self): ################################################################# # updateTreeGraph(self) # When scene graoh page has been opend, call sceneGraphExplorer to # updata the tree. ################################################################# self.SGE.update() pass def updateWorldSetting(self): ################################################################# # updateWorldSetting(self) # When world setting page has been selected, this function will # reset those check box in the page to reflect the current world setting. ################################################################# self.LightingVar.set(self.lightEnable) self.CollisionVar.set(self.collision) self.ParticleVar.set(self.ParticleEnable) self.baseUseDriveVar.set(self.basedriveEnable) self.backgroundColor.set(value=self.worldColor) pass def toggleLights(self): ################################################################# # toggleLights(self) # send out a message to let sceneEditor know we need to toggle the light. # Then, sceneEditor will pass the message to dataHolder to disable/enable # the lights. (lightManager is inside the dataHolder) ################################################################# self.lightEnable = (self.lightEnable + 1) % 2 messenger.send('SW_lightToggle') pass def showCollision(self): ################################################################# # showCollision(self) # This function will send out a message to sceneEditor to toggle # the visibility of collision objects. ################################################################# self.collision = (self.collision + 1) % 2 messenger.send('SW_collisionToggle', [self.collision]) pass def enableParticle(self): ################################################################# # enableParticle(self) # This function will send out a message to sceneEditor to toggle # the visibility of particle objects. ################################################################# self.ParticleEnable = (self.ParticleEnable + 1) % 2 messenger.send('SW_particleToggle', [self.ParticleEnable]) pass def enablebaseUseDrive(self): ################################################################# # enablebaseUseDrive(self) # This function will toggle the usage of base.useDrive. # Well, it may not usefull at all. # # We won't send out any message in this time to notice # the sceneEditor this event happend. # In the other hand, we will restore it back when # the side window has been closed. # ################################################################# if self.enableBaseUseDrive == 0: print 'Enabled' base.useDrive() self.enableBaseUseDrive = 1 else: print 'disabled' #base.useTrackball() base.disableMouse() self.enableBaseUseDrive = 0 self.basedriveEnable = (self.basedriveEnable + 1) % 2 pass def toggleBackface(self): ################################################################# # toggleBackface(self) # This function will toggle the back face setting. so it will # render the polygon with two sides. ################################################################# base.toggleBackface() self.backface = (self.backface + 1) % 2 return def toggleBackfaceFromMainW(self): ################################################################# # toggleBackfaceFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the back face setting in the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.backface = (self.backface + 1) % 2 self.backfaceButton.toggle() return def toggleTexture(self): ################################################################# # toggleTexture(self) # This function will toggle the txture using option for the whole scene. ################################################################# base.toggleTexture() self.texture = (self.texture + 1) % 2 return def toggleTextureFromMainW(self): ################################################################# # toggleTextureFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the texture usage from the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.texture = (self.texture + 1) % 2 self.textureButton.toggle() return def toggleWireframe(self): ################################################################# # toggleWireframe(self) # This function will toggle the wire frame mode. ################################################################# base.toggleWireframe() self.wireframe = (self.wireframe + 1) % 2 return def toggleWireframeFromMainW(self): ################################################################# # toggleWireframeFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the wire frame mode in the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.wireframe = (self.wireframe + 1) % 2 self.wireframeButton.toggle() return def toggleGrid(self): ################################################################# # toggleGrid(self) # This function will toggle the usage of the grid. ################################################################# self.grid = (self.grid + 1) % 2 if self.grid == 1: SEditor.grid.enable() else: SEditor.grid.disable() def togglewidgetVis(self): ################################################################# # togglewidgetVis(self) # This function will toggle the visibility of the widget of the grid. ################################################################# self.widgetVis = (self.widgetVis + 1) % 2 SEditor.toggleWidgetVis() if SEditor.widget.fActive: messenger.send('shift-f') return def toggleWidgetVisFromMainW(self): ################################################################# # toggleWidgetVisFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the visibility of widgets ('v') from the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.widgetVis = (self.widgetVis + 1) % 2 self.widgetVisButton.toggle() return def setBackgroundColorVec(self, color): ################################################################# # setBackgroundColorVec(self,color) # Call back function # This will be called from the colorEntry on the world setting page. # The "color" here is a list containing three integer data, R, G and B. ################################################################# base.setBackgroundColor(color[0] / 255.0, color[1] / 255.0, color[2] / 255.0) self.worldColor = [color[0], color[1], color[2], 0] def toggleAutoCamera(self): ################################################################# # toggleAutoCamera(self) # This function will toggle the usage of the auto-camera movement # when user loaded model or actor into the scene. ################################################################# self.enableAutoCamera = (self.enableAutoCamera + 1) % 2 SEditor.toggleAutoCamera() return def selectPage(self, page='Tree Graph'): ################################################################# ################################################################# self.notebookFrame.selectpage(page)
class BoardConfigAdvance(Frame): def __init__(self, master=None, main=None): Frame.__init__(self, master) self.parent = master self.main = main self.parent.geometry("280x174") self.parent.title(os.getenv("NAME") + " - Advance Board Config") self.master.configure(padx=10, pady=10) self.HEAPSIZE = {"512 byte": 512, "1024 byte": 1024,} self.OPTIMIZATION = "-O2 -O3 -Os".split() self.mips16_var = IntVar() self.checkBox_mips16 = Checkbutton(self.parent, text="Mips16", anchor="w", variable=self.mips16_var) self.checkBox_mips16.pack(expand=True, fill=BOTH, side=TOP) frame_heap = Frame(self.parent) Label(frame_heap, text="Heap size:", anchor="w", width=12).pack(side=LEFT, fill=X, expand=True) self.comboBox_heapsize = Combobox(frame_heap, values=self.HEAPSIZE.keys()) self.comboBox_heapsize.pack(fill=X, expand=True, side=RIGHT) frame_heap.pack(fill=X, expand=True, side=TOP) frame_opt = Frame(self.parent) Label(frame_opt, text="Optimization:", anchor="w", width=12).pack(side=LEFT, fill=X, expand=True) self.comboBox_optimization = Combobox(frame_opt, values=self.OPTIMIZATION) self.comboBox_optimization.pack(fill=X, expand=True, side=RIGHT) frame_opt.pack(fill=X, expand=True, side=TOP) frame_buttons = Frame(self.parent) Button(frame_buttons, text="Accept", command=self.accept_config).pack(fill=X, expand=True, side=LEFT) Button(frame_buttons, text="Restore Default", command=self.restore_default).pack(fill=X, expand=True, side=RIGHT) frame_buttons.pack(fill=X, expand=True, side=BOTTOM) self.load_config() #---------------------------------------------------------------------- def quit(self): self.master.destroy() #---------------------------------------------------------------------- def load_config(self): #Called in the parent frame #self.main.configIDE.load_config() if self.main.configIDE.config("Board", "mips16", True): self.checkBox_mips16.select() else: self.checkBox_mips16.deselect() heapsize = self.main.configIDE.config("Board", "heapsize", 512) for key in self.HEAPSIZE.keys(): if self.HEAPSIZE[key] == heapsize: self.comboBox_heapsize.set(key) break optimization = self.main.configIDE.config("Board", "optimization", "-O3") self.comboBox_optimization.set(optimization) #---------------------------------------------------------------------- def restore_default(self): self.checkBox_mips16.select() self.comboBox_heapsize.set(self.HEAPSIZE.keys()[1]) self.comboBox_optimization.set(self.OPTIMIZATION[1]) #---------------------------------------------------------------------- def accept_config(self): self.save_config() self.main.configIDE.save_config() self.quit() #---------------------------------------------------------------------- def save_config(self): self.main.configIDE.set("Board", "mips16", self.mips16_var.get()==1) heapsize = self.HEAPSIZE[self.comboBox_heapsize.get()] self.main.configIDE.set("Board", "heapsize", heapsize) self.main.configIDE.set("Board", "optimization", self.comboBox_optimization.get())
class ColmaUI: def getClipboardData(self): p = subprocess.Popen(['pbpaste'], stdout=subprocess.PIPE) retcode = p.wait() data = p.stdout.read().decode("utf-8") return data def setClipboardData(self, data): p = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE) p.stdin.write(data) p.stdin.close() retcode = p.wait() def refreshClipboardVar(self, obj): obj.set(self.getClipboardData()) root.update_idletasks() def flattenAndJoin(self, source_text, add_spaces, use_quotes, preserve_lines, reverse, unique_only, order_alpha, skip_header): # Init character variables print "Processing Requested" print 'source_text: ', source_text.get() print 'add_spaces: ', add_spaces.get() print 'use_quotes: ', use_quotes.get() print 'preserve_lines: ', preserve_lines.get() print 'reverse: ', reverse.get() print 'unique_only: ', unique_only.get() print 'order_alpha: ', order_alpha.get() print 'skip_header: ', skip_header.get() output = '' space = ' ' if add_spaces.get() else '' quote = '\'' if use_quotes.get() else '' separator = '\n' if preserve_lines.get() else ',' split_on = ',' if reverse.get() else '\n' separator = '\n' if reverse.get() else separator input = source_text.get().split(split_on) input = filter(None, input) input = list(set(input)) if unique_only.get() else input input = sorted(input) if order_alpha.get() else input inputlines = len(input) headerLineCount = 1 if skip_header.get() else 0 for i in range(headerLineCount, inputlines): # print input[i] if i == headerLineCount: output = quote + input[i].strip() + quote elif input[i] != '': output = output + separator + space + quote + input[i].strip( ) + quote return output def __init__(self, master): # Master Window self.master = master master.title("colmaUI") source_text = StringVar() source_text.set(self.getClipboardData()) output_text = StringVar() output_text.set('') self.refresh_button = Button( master, text="Paste", command=lambda: source_text.set(self.getClipboardData()), anchor='w') self.refresh_button.pack() self.refresh_button = Button( master, text="Reset", command=lambda: source_text.set(output_text.get())) self.refresh_button.pack() self.label = Label(master, textvar=source_text, justify='left', width=10, height=10, relief='groove') self.label.pack(expand='yes', fill='both') # Spaces between Elements add_spaces = BooleanVar() add_spaces.set(1) self.space_check = Checkbutton(master, text="Add spaces between each value", variable=add_spaces, anchor='w') self.space_check.pack() # Quoting use_quotes = BooleanVar() use_quotes.set(0) self.quote_check = Checkbutton( master, text="Surround each element with quotes", variable=use_quotes) self.quote_check.pack() # One line output preserve_lines = BooleanVar() preserve_lines.set(False) self.line_check = Checkbutton(master, text="Don't strip new lines", variable=preserve_lines) self.line_check.pack() # Split on comma instead of newline reverse = BooleanVar() reverse.set(0) self.rev_check = Checkbutton(master, text="Reverse From CSV to Column", variable=reverse) self.rev_check.pack() order_alpha = BooleanVar() order_alpha.set(0) self.order_check = Checkbutton(master, text="Sort alphabetically", variable=order_alpha) self.order_check.pack() unique_only = BooleanVar() unique_only.set(0) self.unique_check = Checkbutton(master, text="Unique Values", variable=unique_only) self.unique_check.pack() skip_header = BooleanVar() skip_header.set(0) self.header_check = Checkbutton(master, text="Skip Header", variable=skip_header) self.header_check.pack() self.label = Label(master, textvar=output_text, justify='left', width=10, height=10, relief='groove') self.label.pack(expand='yes', fill='both') self.go_button = Button( master, text="Process", command=lambda: output_text.set( self.flattenAndJoin(source_text, add_spaces, use_quotes, preserve_lines, reverse, unique_only, order_alpha, skip_header))) self.go_button.pack() self.copy_button = Button( master, text="Copy", command=lambda: self.setClipboardData(output_text.get())) self.copy_button.pack() self.close_button = Button(master, text="Quit", command=master.quit) self.close_button.pack()
class Controller(Observer): def __init__(self,parent,view,lissajou,subjectSig,subjects): self.cursorFrame = Frame(parent) self.selectionFrame = Frame(self.cursorFrame) self.view = view self.lissajou = lissajou self.subjects = subjects self.subjectSig=subjectSig self.amp=IntVar() self.scale_amp=Scale(self.cursorFrame,variable=self.amp, label="Amplitude", orient="horizontal",length=250,from_=0,to=10, sliderlength=50,tickinterval=1,showvalue=0, command=self.update) self.freq=IntVar() self.scale_freq=Scale(self.cursorFrame,variable=self.freq, label="Frequence", orient="horizontal",length=250,from_=0,to=10, sliderlength=50,tickinterval=0,showvalue=0, command=self.update) self.offset=DoubleVar() self.scale_offset=Scale(self.cursorFrame,variable=self.offset, label="Offset", orient="horizontal",length=250,from_=-10.0,to=10.0, sliderlength=50,tickinterval=5,showvalue=0, command=self.update) self.phase=IntVar() self.scale_phase=Scale(self.cursorFrame,variable=self.phase, label="Phase", orient="horizontal",length=250,from_=-90,to=90, sliderlength=10,tickinterval=45,showvalue=0, command=self.update) self.voltVar = DoubleVar() self.voltVar.set(1) self.button1 = Radiobutton(self.selectionFrame, text="1V", variable=self.voltVar, value=1.0*5.0,command =lambda:self.update(None)) self.button1.select() self.button2 = Radiobutton(self.selectionFrame, text="2V", variable=self.voltVar, value=2.0*5.0, command =lambda:self.update(None)) self.button5 = Radiobutton(self.selectionFrame, text="5V", variable=self.voltVar, value=5.0*5.0, command =lambda:self.update(None)) self.isOffsetVar= IntVar() self.isOffset = Checkbutton(self.selectionFrame,text = "Offset",variable = self.isOffsetVar, command =lambda:self.update(None)) def update(self,event): self.update_amplitude(event) self.update_offset(event) self.update_frequency(event) self.update_phase(event) self.view.update() if self.lissajou!=None: self.lissajou.update() def update_amplitude(self,event): print("update_amplitude(self,event)",self.amp.get()) self.subjectSig.set_magnitude(self.amp.get()/self.voltVar.get()) self.subjects.generate_XYCurve() def update_frequency(self,event): print("update_frequency(self,event)",self.freq.get()) self.subjectSig.set_frequency(self.freq.get()) self.subjects.generate_XYCurve() def update_phase(self,event): print("update_phase(self,event)",self.phase.get()) self.subjectSig.set_phase(self.phase.get()) self.subjects.generate_XYCurve() def update_offset(self,event): if self.isOffsetVar.get(): print("update_offset(self,event)",self.isOffsetVar.get()) self.subjectSig.set_offset(self.offset.get()/self.voltVar.get()) self.subjects.generate_XYCurve() else: self.subjectSig.set_offset(0.0) self.subjects.generate_XYCurve() def setLissajou(self,lissajou): self.lissajou = lissajou def packing(self) : self.selectionFrame.pack(side='top') self.button1.pack(side='left') self.button2.pack(side='left') self.button5.pack(side='left') self.isOffset.pack(side='left') self.cursorFrame.pack(side='left',expand=1, fill='both') self.scale_amp.pack() self.scale_freq.pack() self.scale_offset.pack() self.scale_phase.pack()
def init_gui(self): """init helper""" #setting up frames top_frame = Frame(self.root) mid_frame = Frame(self.root) radio_frame = Frame(self.root) res_frame = Frame(self.root) msg_frame = Frame(self.root) check_frame = Frame(self.root) history_frame = Frame(self.root) btn_frame = Frame(self.root) rating_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) mid_frame.pack(side=TOP, fill=X) history_frame.pack(side=TOP, fill=BOTH, expand=True) radio_frame.pack(side=TOP, fill=BOTH, expand=True) rating_frame.pack(side=TOP, fill=BOTH, expand=True) res_frame.pack(side=TOP, fill=BOTH, expand=True) check_frame.pack(side=TOP, fill=BOTH, expand=True) msg_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) #Message ListBox rightscrollbar = Scrollbar(msg_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.lbMessages = Listbox(msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white") self.lbMessages.pack(expand=True, fill=BOTH) rightscrollbar.config(command=self.lbMessages.yview) bottomscrollbar.config(command=self.lbMessages.xview) #History ListBoxes rightscrollbar2 = Scrollbar(history_frame) rightscrollbar2.pack(side=RIGHT, fill=Y) bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL) bottomscrollbar2.pack(side=BOTTOM, fill=X) self.showhistory = Listbox(history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white") self.showhistory.pack(expand=True, fill=BOTH) rightscrollbar2.config(command=self.showhistory.yview) bottomscrollbar2.config(command=self.showhistory.xview) self.showhistory.bind('<Double-Button-1>', self.select_recent_file) self.set_history_window() #status bar self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) #labels self.lblRatingLabel = Label(rating_frame, text='Rating:') self.lblRatingLabel.pack(side=LEFT) self.lblRating = Label(rating_frame, textvariable=self.rating) self.lblRating.pack(side=LEFT) Label(mid_frame, text='Recently Used:').pack(side=LEFT) Label(top_frame, text='Module or package').pack(side=LEFT) #file textbox self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) #results box rightscrollbar = Scrollbar(res_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.results = Listbox(res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier") self.results.pack(expand=True, fill=BOTH, side=BOTTOM) rightscrollbar.config(command=self.results.yview) bottomscrollbar.config(command=self.results.xview) #buttons Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT) Button(top_frame, text='Open Package', command=(lambda : self.file_open(package=True))).pack(side=LEFT) self.btnRun = Button(top_frame, text='Run', command=self.run_lint) self.btnRun.pack(side=LEFT) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #radio buttons self.information_box = IntVar() self.convention_box = IntVar() self.refactor_box = IntVar() self.warning_box = IntVar() self.error_box = IntVar() self.fatal_box = IntVar() i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window) c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window) r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window) w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window) e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window) f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window) i.select() c.select() r.select() w.select() e.select() f.select() i.pack(side=LEFT) c.pack(side=LEFT) r.pack(side=LEFT) w.pack(side=LEFT) e.pack(side=LEFT) f.pack(side=LEFT) #check boxes self.box = StringVar() # XXX should be generated report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window) rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window) dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window) ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window) stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window) msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window) msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window) report.select() report.grid(column=0, row=0, sticky=W) rawMet.grid(column=1, row=0, sticky=W) dup.grid(column=2, row=0, sticky=W) msg.grid(column=3, row=0, sticky=E) stat.grid(column=0, row=1, sticky=W) msgCat.grid(column=1, row=1, sticky=W) ext.grid(column=2, row=1, columnspan=2, sticky=W) #dictionary for check boxes and associated error term self.msg_type_dict = { 'I' : lambda : self.information_box.get() == 1, 'C' : lambda : self.convention_box.get() == 1, 'R' : lambda : self.refactor_box.get() == 1, 'E' : lambda : self.error_box.get() == 1, 'W' : lambda : self.warning_box.get() == 1, 'F' : lambda : self.fatal_box.get() == 1 } self.txtModule.focus_set()
from Tkinter import IntVar, Checkbutton, Label, Entry, LEFT, RIGHT import tkMessageBox top = Tkinter.Tk() # Code to add widgets will go here... def helloCallBack(): tkMessageBox.showinfo("Hello Python", "Hello World") B = Tkinter.Button(top, text = "Hello", fg="blue", command = helloCallBack) B.pack() C = Tkinter.Canvas(top, bg="blue", height=250, width=300) coord = 10, 50, 240, 210 arc = C.create_arc(coord, start=0, extent=150, fill="red") C.pack() CheckVar1 = Tkinter.IntVar() CheckVar2 = IntVar() C1 = Checkbutton(top, text = "Music", variable = CheckVar1, onvalue = 1, offvalue = 0, height=5, width = 20) C2 = Checkbutton(top, text = "Video", variable = CheckVar2, onvalue = 1, offvalue = 0, height=5, width = 20) C1.pack() C2.pack() L1 = Label(top, text="User Name") L1.pack( side = LEFT) E1 = Entry(top, bd =5) E1.pack(side = RIGHT) top.mainloop()
class Screen(Observer): def __init__(self, parent, bg="white"): self.menu_bar = MenuBar(parent) self.canvas = Canvas(parent, bg=bg, name="screen") self.frameControl = Frame(parent) self.frameLabelSignals = LabelFrame(self.frameControl, text="Signaux", padx=20, pady=20) self.frameLabelMode = LabelFrame(self.frameControl, text="Mode", padx=20, pady=20) self.panelControl = ttk.Notebook(self.frameLabelSignals) self.checkbox_signalX = Checkbutton(self.frameLabelMode, text="Signal X") self.checkbox_signalY = Checkbutton(self.frameLabelMode, text="Signal Y") self.checkbox_XY = Checkbutton(self.frameLabelMode, text="XY") self.panel_control_page = [] # contient les références de mes curseurs for p in parent.get_models(): self.addPage(p.get_name()) def addPage(self, name): page = ttk.Frame(self.panelControl) self.panelControl.add(page, text='signal ' + name) visible_checkbox = Checkbutton(page, text="Afficher") magnitude = Scale(page, length=250, orient="horizontal", label="Amplitude", sliderlength=20, showvalue=0, from_=0, to=5, tickinterval=1, name="magnitudeScale") frequency = Scale(page, length=250, orient="horizontal", label="Frequency", sliderlength=20, showvalue=0, from_=0, to=25, tickinterval=5, name="frequencyScale") phase = Scale(page, length=250, orient="horizontal", label="Phase", sliderlength=20, showvalue=0, from_=0, to=20, tickinterval=5, name="phaseScale") visible_checkbox.pack(fill="x", pady=6) magnitude.pack(expand=1, fill="both", pady=6) frequency.pack(expand=1, fill="both", pady=6) phase.pack(expand=1, fill="both", pady=6) self.panel_control_page.append({ 'visible': visible_checkbox, 'magnitude': magnitude, 'frequency': frequency, 'phase': phase }) def update(self, model): if type(model) == list: for i, m in enumerate(model): signal = m.get_signal() #self.plot_signal(signal, m.get_color()) self.plot_signal(m) else: signal = model.get_signal() self.plot_signal(model) self.grid(6, 8) def get_panel_control_index(self): return self.panelControl.index('current') def get_canvas(self): return self.canvas def get_panel_control_page(self): return self.panel_control_page def get_magnitude(self, index): return self.panel_control_page[index]['magnitude'] def get_frequency(self, index): return self.panel_control_page[index]['frequency'] def get_phase(self, index): return self.panel_control_page[index]['phase'] def get_visible(self, index): return self.panel_control_page[index]['visible'] def get_checkbox_signalX(self): return self.checkbox_signalX def get_checkbox_signalY(self): return self.checkbox_signalY def get_checkbox_XY(self): return self.checkbox_XY def plot_signal(self, model): w, h = self.canvas.winfo_width(), self.canvas.winfo_height() width, height = int(w), int(h) signal = model.get_signal() name = model.get_name() color = model.get_color() if self.canvas.find_withtag("signal" + name): self.canvas.delete("signal" + name) if signal and len(signal) > 1 and model.is_visible(): plot = [(x * width, height / 2.0 * (y + 1)) for (x, y) in signal] self.canvas.create_line(plot, fill=color, smooth=1, width=3, tags="signal" + name) self.canvas.scale("signal" + name, width / 2, height / 2, 1.0, 0.25) def grid(self, row, col): w, h = self.canvas.winfo_width(), self.canvas.winfo_height() width, height = int(w), int(h) if self.canvas.find_withtag("grid"): self.canvas.delete("grid") # dessin des axes X et Y self.canvas.create_line(5, height / 2, width, height / 2, arrow="last", tags=('grid', 'axe-x')) self.canvas.create_line(width / 2, height - 5, width / 2, 5, arrow="last", tags=('grid', 'axe-y')) # dessin des lignes verticales for c in range(1, int(row / 2) + 1): stepW = width / row xd = width / 2 + c * stepW xg = width / 2 - c * stepW #Creation des lignes verticales self.canvas.create_line(xd, height - 5, xd, 5, dash=1, tags=('grid', 'vertical-line'), fill='grey') #cote droit self.canvas.create_line(xg, height - 5, xg, 5, dash=1, tags=('grid', 'vertical-line'), fill='grey') #cote gauche #Creation des tirets sur x self.canvas.create_line(xd, height / 2 - 4, xd, height / 2 + 4, tags=('grid', 'horizontal-line'), fill='grey') self.canvas.create_line(xg, height / 2 - 4, xg, height / 2 + 4, tags=('grid', 'horizontal-line'), fill='grey') # dessin des lignes horizontales for r in range(1, int(col / 2) + 1): stepH = height / col yB = height / 2 + r * stepH yH = height / 2 - r * stepH #Creation des lignes horizontales self.canvas.create_line(5, yB, width, yB, dash=1, tags=('grid', 'horizontal-line'), fill='grey') self.canvas.create_line(5, yH, width, yH, dash=1, tags=('grid', 'horizontal-line'), fill='grey') #Creation des tirets sur y self.canvas.create_line(width / 2 - 4, yB, width / 2 + 4, yB, tags=('grid', 'vertical-line'), fill='grey') self.canvas.create_line(width / 2 - 4, yH, width / 2 + 4, yH, tags=('grid', 'vertical-line'), fill='grey') def packing(self): self.menu_bar.pack(fill='x') self.canvas.pack(side=LEFT, expand=1, fill="both", padx=6, pady=6) self.panelControl.pack(side=RIGHT, expand=1, fill="both", pady=6) self.frameLabelSignals.pack(expand=1, fill="both") self.frameLabelMode.pack(expand=1, fill="both") self.checkbox_signalX.pack(side=LEFT) self.checkbox_signalY.pack(side=LEFT) self.checkbox_XY.pack(side=RIGHT) self.frameControl.pack(side=RIGHT, expand=1, fill="both", pady=6)
class MainWindow: def __init__(self): self.root = Tk() self.input_type = Tkinter.IntVar() self.input_type.set(1) self.normalize_data = Tkinter.IntVar() self.normalize_data.set(1) self.root.title("Code energy calculator") self.left_frame = LabelFrame(self.root, text="Input and output") self.left_frame.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH, expand=True, padx=(10, 5), pady=10) self.right_frame = LabelFrame(self.root, text="Code") self.right_frame.pack(side=Tkinter.RIGHT, fill=Tkinter.BOTH, expand=True, padx=(5, 10), pady=10) code_hscroll = Scrollbar(self.right_frame, orient=Tkinter.HORIZONTAL) code_hscroll.pack(side=Tkinter.BOTTOM, fill=Tkinter.X) code_vscroll = Scrollbar(self.right_frame) code_vscroll.pack(side=Tkinter.RIGHT, fill=Tkinter.Y) self.code_text = Text(self.right_frame, wrap=Tkinter.NONE, xscrollcommand=code_hscroll.set, yscrollcommand=code_vscroll.set) self.code_text.pack() self.code_text.insert(Tkinter.INSERT, DEFAULT_CODE) code_hscroll.config(command=self.code_text.xview) code_vscroll.config(command=self.code_text.yview) self.input_file_entry =\ self.create_and_add_file_field(self.left_frame, "Input file", 5, False) self.spherical_coord_option =\ Radiobutton(self.left_frame, text="Spherical coordinates", variable=self.input_type, value=1) self.spherical_coord_option.pack(anchor=Tkinter.W) self.cartesian_coord_option =\ Radiobutton(self.left_frame, text="Cartesian coordinates", variable=self.input_type, value=2) self.cartesian_coord_option.pack(anchor=Tkinter.W) self.spherical_coord_option.select() self.output_file_entry =\ self.create_and_add_file_field(self.left_frame, "Output file", 5, True) self.normalize_check = Checkbutton(self.left_frame, text="Normalize data", variable=self.normalize_data, offvalue=0, onvalue=1) self.normalize_check.pack() self.normalize_check.deselect() self.do_button = Button(self.left_frame, text="Run", command=self.run) self.do_button.pack(side=Tkinter.BOTTOM, pady=(0, 10)) def create_and_add_file_field(self, parent, title, pad, is_save): title_label = Label(parent, text=title) title_label.pack(side=Tkinter.TOP, padx=pad) container_frame = Frame(parent) container_frame.pack(side=Tkinter.TOP, padx=pad, pady=(0, pad)) filename_entry = Entry(container_frame) filename_entry.pack(side=Tkinter.LEFT) browse_button = \ Button(container_frame, text="Browse...", command=lambda: self.select_file(filename_entry, is_save)) browse_button.pack(side=Tkinter.RIGHT) return filename_entry @staticmethod def select_file(text_field, is_save): text_field.delete(0, Tkinter.END) if is_save: filename = asksaveasfilename() else: filename = askopenfilename() text_field.insert(0, filename) def run(self): input_fname = self.input_file_entry.get() output_fname = self.output_file_entry.get() code = self.code_text.get(1.0, Tkinter.END) do_work(input_fname, output_fname, code, self.input_type.get(), self.normalize_data.get()) def show(self): self.root.mainloop()
class FilePickEdit(Frame): def __init__(self, master, file_mask, default_file, edit_height = None, user_onChange = None, rename_on_edit=0, font = None, coloring=True, allowNone=False, highlighter=None, directory='.'): ''' file_mask: file mask (e.g. "*.foo") or list of file masks (e.g. ["*.foo", "*.abl"]) ''' self.master = master self.directory = directory self.user_onChange = user_onChange Frame.__init__(self, master) row = 0 self.unmodified = True self.allowNone = allowNone self.file_extension = "" if type(file_mask) != list: file_mask = [file_mask] if "." in file_mask[0]: self.file_extension = file_mask[0][file_mask[0].rfind('.'):] # read filenames self.file_mask = file_mask self.updateList() # filename frame self.list_frame = Frame(self) self.list_frame.grid(row=row, column=0, sticky="WE") self.list_frame.columnconfigure(0, weight=1) # create list self.picked_name = StringVar(self) self.makelist() # refresh button self.refresh_button = Button(self.list_frame, text='<- refresh', command=self.refresh, height=1) self.refresh_button.grid(row=0, column=1, sticky='E') # save button self.save_button = Button(self.list_frame, text="save", command=self.save, height=1) self.save_button.grid(row=0, column=2, sticky="E") # editor row += 1 if coloring: self.editor = SyntaxHighlightingText(self, self.onEdit, highlighter=highlighter) else: self.editor = ScrolledText2(self, self.onEdit) if font != None: self.editor.configure(font=font) if edit_height is not None: self.editor.configure(height=edit_height) self.editor.grid(row=row, column=0, sticky="NEWS") self.rowconfigure(row, weight=1) self.columnconfigure(0, weight=1) # option to change filename on edit row += 1 self.options_frame = Frame(self) self.options_frame.grid(row=row, column=0, sticky=W) self.rename_on_edit = IntVar() self.cb = Checkbutton(self.options_frame, text="rename on edit", variable=self.rename_on_edit) self.cb.pack(side=LEFT) self.cb.configure(command=self.onChangeRename) self.rename_on_edit.set(rename_on_edit) # filename frame row += 1 self.filename_frame = Frame(self) self.filename_frame.grid(row=row, column=0, sticky="WE") self.filename_frame.columnconfigure(0, weight=1) # save as filename self.save_name = StringVar(self) self.save_edit = Entry(self.filename_frame, textvariable = self.save_name) self.save_edit.grid(row=0, column=0, sticky="WE") self.save_name.trace("w", self.onSaveChange) # pick default if applicableButton self.select(default_file) self.row = row def setDirectory(self, directory, keep=False): self.directory = directory self.updateList() self.makelist() # menu = self.list["menu"] scrolledlist # menu = self.list.listbox#["scrolledlist"] # menu.delete(0, 'end') # add the new ones # for filename in self.files: # menu.add_command(label=filename, command=_setit(self.picked_name, filename, None)) # if keep is true, only the files list will be updated but the content of the # text area will not be altered/removed if not keep: self.select("") def refresh(self): sel = self.get() self.updateList() self.select(sel, notify=False) def reloadFile(self): self.editor.delete("1.0", END) filename = self.picked_name.get() if os.path.exists(os.path.join(self.directory, filename)): new_text = file(os.path.join(self.directory, filename)).read() if new_text.strip() == "": new_text = "// %s is empty\n" % filename; new_text = new_text.replace("\r", "") else: new_text = "" self.editor.insert(INSERT, new_text) def setText(self, txt): ''' Replaces the text in the edit field as by typing into it. ''' self.select("") if txt.strip() == "": txt = "// empty database\n"; self.editor.insert(INSERT, txt) self.onEdit() def onSelChange(self, name, index=0, mode=0): self.reloadFile() filename = self.picked_name.get() self.save_name.set(filename) self.save_edit.configure(state=DISABLED) self.unmodified = True if self.user_onChange != None: self.user_onChange(filename) def onSaveChange(self, name, index, mode): pass # if self.user_onChange != None: # self.user_onChange(self.save_name.get()) def autoRename(self): # modify "save as" name filename = self.picked_name.get() if filename == "": filename = "new" + self.file_extension # if no file selected, create new filename ext = "" extpos = filename.rfind(".") if extpos != -1: ext = filename[extpos:] base = filename[:extpos] hpos = base.rfind("-") num = 0 if hpos != -1: try: num = int(base[hpos+1:]) base = base[:hpos] except: pass while True: num += 1 filename = "%s-%d%s" % (base, num, ext) if not os.path.exists(filename): break self.save_name.set(filename) # user callback if self.user_onChange != None: self.user_onChange(filename) def onEdit(self): if self.unmodified == True: self.unmodified = False # do auto rename if it's enabled or there is no file selected (editing new file) if self.rename_on_edit.get() == 1 or self.picked_name.get() == "": self.autoRename() # enable editing of save as name self.save_edit.configure(state=NORMAL) def onChangeRename(self): # called when clicking on "rename on edit" checkbox if self.rename_on_edit.get() == 1: if (not self.unmodified) and self.save_name.get() == self.picked_name.get(): self.autoRename() else: self.save_name.set(self.picked_name.get()) def updateList(self): self.files = [] if self.allowNone: self.files.append("") if os.path.exists(self.directory): for filename in os.listdir(self.directory): for fm in self.file_mask: if fnmatch(filename, fm): self.files.append(filename) self.files.sort() if len(self.files) == 0 and not self.allowNone: self.files.append("(no %s files found)" % str(self.file_mask )) def select(self, filename, notify=True): ''' selects the item given by filename ''' if filename in self.files: if not havePMW: self.picked_name.set(filename) else: self.list.selectitem(self.files.index(filename)) if notify: self.onSelChange(filename) else: self.editor.delete("1.0", END) def makelist(self): if havePMW: self.list = Pmw.ComboBox(self.list_frame, selectioncommand = self.onSelChange, scrolledlist_items = self.files, ) self.list.grid(row=0, column=0, padx=0, pady=0, sticky="NEWS") self.list.component('entryfield').component('entry').configure(state = 'readonly', relief = 'raised') self.picked_name = self.list else: self.list = apply(OptionMenu, (self.list_frame, self.picked_name) + tuple(self.files)) self.list.grid(row=0, column=0, sticky="NEW") self.picked_name.trace("w", self.onSelChange) def save(self): self.get() def set(self, selected_item): self.select(selected_item) def get(self): ''' gets the name of the currently selected file, saving it first if necessary ''' filename = self.save_name.get() if self.unmodified == False: self.unmodified = True # save the file f = file(os.path.join(self.directory, filename), "w") f.write(self.editor.get("1.0", END).encode('utf-8')) f.close() # add it to the list of files # if not filename in self.files: # self.files.append(filename) # self.files.sort() # self.list.destroy() # self.makelist() # set it as the new pick #if havePMW: # self.picked_name.selectitem(self.files.index(filename), 1) #else: # self.picked_name.set(filename) # self.select(filename) self.refresh() self.select(filename, notify=False) self.save_edit.configure(state=DISABLED) return filename def get_text(self): return self.editor.get("1.0", END) def get_filename(self): return self.save_name.get() def set_enabled(self, state): self.editor.configure(state=state) if havePMW: self.list.component('entryfield_entry').configure(state=state) # self.list.component('arrowbutton').configure(state=state) self.list.component('arrowbutton').bind('<1>', (lambda a: 'break') if state==DISABLED else self.list._postList) else: self.list.configure(state=state) self.save_button.configure(state=state) self.cb.configure(state=state) self.save_edit.configure(state=state)
class Cockpit(ttkFrame): ''' Remote device GUI ''' #TODO: 20160415 DPM - Set these values from configuration file #--- config THROTTLE_BY_USER = True THROTTLE_RESOLUTION = 0.1 # Joystick enabled or not, if any JOYSTICK_ENABLED = True DEFAULT_DRONE_IP = "192.168.1.130" DEFAULT_DRONE_PORT = 2121 #--- end config KEY_ANG_SPEED = "ang-speed" KEY_ANGLES = "angles" KEY_ACCEL = "accel" PID_KEYS = ["P", "I", "D"] DIR_NONE = 0 DIR_VERTICAL = 1 DIR_HORIZONTAL = 2 def __init__(self, parent, isDummy = False, droneIp = DEFAULT_DRONE_IP, dronePort = DEFAULT_DRONE_PORT): ''' Constructor ''' ttkFrame.__init__(self, parent) self._target = [0.0] * 4 self._selectedPidConstats = "--" self._pidConstants = { Cockpit.KEY_ANG_SPEED:{ "X":{ "P": 0.0, "I": 0.0, "D": 0.0 }, "Y":{ "P": 0.0, "I": 0.0, "D": 0.0 }, "Z":{ "P": 0.0, "I": 0.0, "D": 0.0 } }, Cockpit.KEY_ANGLES: { "X":{ "P": 0.0, "I": 0.0, "D": 0.0 }, "Y":{ "P": 0.0, "I": 0.0, "D": 0.0 } }, Cockpit.KEY_ACCEL:{ "X":{ "P": 0.0, "I": 0.0, "D": 0.0 }, "Y":{ "P": 0.0, "I": 0.0, "D": 0.0 }, "Z":{ "P": 0.0, "I": 0.0, "D": 0.0 } } } self.parent = parent self.initUI() self._controlKeysLocked = False if not isDummy: self._link = INetLink(droneIp, dronePort) else: self._link = ConsoleLink() self._link.open() self._updateInfoThread = Thread(target=self._updateInfo) self._updateInfoThreadRunning = False self._readingState = False self._start() def initUI(self): self.parent.title("Drone control") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.parent.bind_all("<Key>", self._keyDown) self.parent.bind_all("<KeyRelease>", self._keyUp) if system() == "Linux": self.parent.bind_all("<Button-4>", self._onMouseWheelUp) self.parent.bind_all("<Button-5>", self._onMouseWheelDown) else: #case of Windows self.parent.bind_all("<MouseWheel>", self._onMouseWheel) #Commands commandsFrame = tkFrame(self) commandsFrame.grid(column=0, row=0, sticky="WE") self._started = IntVar() self._startedCB = Checkbutton(commandsFrame, text="On", variable=self._started, command=self._startedCBChanged) self._startedCB.pack(side=LEFT, padx=4) # self._integralsCB = Checkbutton(commandsFrame, text="Int.", variable=self._integralsEnabled, \ # command=self._integralsCBChanged, state=DISABLED) # self._integralsCB.pack(side=LEFT, padx=4) self._quitButton = Button(commandsFrame, text="Quit", command=self.exit) self._quitButton.pack(side=LEFT, padx=2, pady=2) # self._angleLbl = Label(commandsFrame, text="Angle") # self._angleLbl.pack(side=LEFT, padx=4) # # self._angleEntry = Entry(commandsFrame, state=DISABLED) # self._angleEntry.pack(side=LEFT) #Info infoFrame = tkFrame(self) infoFrame.grid(column=1, row=1, sticky="NE", padx=4) #Throttle Label(infoFrame, text="Throttle").grid(column=0, row=0, sticky="WE") self._throttleTexts = [StringVar(),StringVar(),StringVar(),StringVar()] Entry(infoFrame, textvariable=self._throttleTexts[3], state=DISABLED, width=5).grid(column=0, row=1) Entry(infoFrame, textvariable=self._throttleTexts[0], state=DISABLED, width=5).grid(column=1, row=1) Entry(infoFrame, textvariable=self._throttleTexts[2], state=DISABLED, width=5).grid(column=0, row=2) Entry(infoFrame, textvariable=self._throttleTexts[1], state=DISABLED, width=5).grid(column=1, row=2) #Angles Label(infoFrame, text="Angles").grid(column=0, row=3, sticky="WE") self._angleTexts = [StringVar(),StringVar(),StringVar()] for index in range(3): Entry(infoFrame, textvariable=self._angleTexts[index], state=DISABLED, width=5).grid(column=index, row=4) #Accels Label(infoFrame, text="Accels").grid(column=0, row=5, sticky="WE") self._accelTexts = [StringVar(),StringVar(),StringVar()] for index in range(3): Entry(infoFrame, textvariable=self._accelTexts[index], state=DISABLED, width=5).grid(column=index, row=6) #Speeds Label(infoFrame, text="Speeds").grid(column=0, row=7, sticky="WE") self._speedTexts = [StringVar(),StringVar(),StringVar()] for index in range(3): Entry(infoFrame, textvariable=self._speedTexts[index], state=DISABLED, width=5).grid(column=index, row=8) #Height Label(infoFrame, text="Height").grid(column=0, row=9, sticky="E") self._heightText = StringVar() Entry(infoFrame, textvariable=self._heightText, state=DISABLED, width=5).grid(column=1, row=9) #Loop rate Label(infoFrame, text="Loop @").grid(column=0, row=10, sticky="E") self._loopRateText = StringVar() Entry(infoFrame, textvariable=self._loopRateText, state=DISABLED, width=5).grid(column=1, row=10) Label(infoFrame, text="Hz").grid(column=2, row=10, sticky="W") #control controlFrame = tkFrame(self) controlFrame.grid(column=0, row=1, sticky="W") self._throttle = DoubleVar() if Cockpit.THROTTLE_BY_USER: self._thrustScale = Scale(controlFrame, orient=VERTICAL, from_=100.0, to=0.0, \ tickinterval=0, variable=self._throttle, resolution=Cockpit.THROTTLE_RESOLUTION, \ length=200, showvalue=1, \ state=DISABLED, command=self._onThrustScaleChanged) else: self._thrustScale = Scale(controlFrame, orient=VERTICAL, from_=100.0, to=-100.0, \ tickinterval=0, variable=self._throttle, \ length=200, showvalue=1, \ state=DISABLED, command=self._onThrustScaleChanged) self._thrustScale.bind("<Double-Button-1>", self._onThrustScaleDoubleButton1, "+") self._thrustScale.grid(column=0) self._shiftCanvas = Canvas(controlFrame, bg="white", height=400, width=400, \ relief=SUNKEN) self._shiftCanvas.bind("<Button-1>", self._onMouseButton1) #self._shiftCanvas.bind("<ButtonRelease-1>", self._onMouseButtonRelease1) self._shiftCanvas.bind("<B1-Motion>", self._onMouseButton1Motion) self._shiftCanvas.bind("<Double-Button-1>", self._onMouseDoubleButton1) self._shiftCanvas.bind("<Button-3>", self._onMouseButton3) #self._shiftCanvas.bind("<ButtonRelease-3>", self._onMouseButtonRelease3) self._shiftCanvas.bind("<B3-Motion>", self._onMouseButton3Motion) self._shiftCanvas.grid(row=0,column=1, padx=2, pady=2) self._shiftCanvas.create_oval(1, 1, 400, 400, outline="#ff0000") self._shiftCanvas.create_line(200, 2, 200, 400, fill="#ff0000") self._shiftCanvas.create_line(2, 200, 400, 200, fill="#ff0000") self._shiftMarker = self._shiftCanvas.create_oval(196, 196, 204, 204, outline="#0000ff", fill="#0000ff") self._yaw = DoubleVar() self._yawScale = Scale(controlFrame, orient=HORIZONTAL, from_=-100.0, to=100.0, \ tickinterval=0, variable=self._yaw, \ length=200, showvalue=1, \ command=self._onYawScaleChanged) self._yawScale.bind("<Double-Button-1>", self._onYawScaleDoubleButton1, "+") self._yawScale.grid(row=1, column=1) self._controlKeyActive = False #PID calibration pidCalibrationFrame = tkFrame(self) pidCalibrationFrame.grid(column=0, row=2, sticky="WE"); self._pidSelected = StringVar() self._pidSelected.set("--") self._pidListBox = OptionMenu(pidCalibrationFrame, self._pidSelected, "--", \ Cockpit.KEY_ANG_SPEED, Cockpit.KEY_ANGLES, Cockpit.KEY_ACCEL, \ command=self._onPidListBoxChanged) self._pidListBox.pack(side=LEFT, padx=2) self._pidListBox.config(width=10) self._axisSelected = StringVar() self._axisSelected.set("--") self._axisListBox = OptionMenu(pidCalibrationFrame, self._axisSelected, "--", "X", "Y", "Z", \ command=self._onAxisListBoxChanged) self._axisListBox.pack(side=LEFT, padx=2) self._axisListBox.config(state=DISABLED) Label(pidCalibrationFrame, text="P").pack(side=LEFT, padx=(14, 2)) self._pidPString = StringVar() self._pidPString.set("0.00") self._pidPSpinbox = Spinbox(pidCalibrationFrame, width=5, from_=0.0, to=10000.0, increment=0.01, state=DISABLED, \ textvariable=self._pidPString, command=self._onPidSpinboxChanged) self._pidPSpinbox.pack(side=LEFT, padx=2) Label(pidCalibrationFrame, text="I").pack(side=LEFT, padx=(14, 2)) self._pidIString = StringVar() self._pidIString.set("0.00") self._pidISpinbox = Spinbox(pidCalibrationFrame, width=5, from_=0.0, to=10000.0, increment=0.01, state=DISABLED, \ textvariable=self._pidIString, command=self._onPidSpinboxChanged) self._pidISpinbox.pack(side=LEFT, padx=2) Label(pidCalibrationFrame, text="D").pack(side=LEFT, padx=(14, 2)) self._pidDString = StringVar() self._pidDString.set("0.00") self._pidDSpinbox = Spinbox(pidCalibrationFrame, width=5, from_=0.0, to=10000.0, increment=0.01, state=DISABLED, \ textvariable=self._pidDString, command=self._onPidSpinboxChanged) self._pidDSpinbox.pack(side=LEFT, padx=2) #debug debugFrame = tkFrame(self) debugFrame.grid(column=0, row=3, sticky="WE") self._debugMsg = Message(debugFrame, anchor="nw", justify=LEFT, relief=SUNKEN, width=300) self._debugMsg.pack(fill=BOTH, expand=1) def _start(self): self._readDroneConfig() if Cockpit.JOYSTICK_ENABLED: self._joystickManager = JoystickManager.getInstance() self._joystickManager.start() joysticks = self._joystickManager.getJoysticks() if len(joysticks) != 0: self._joystick = joysticks[0] self._joystick.onAxisChanged += self._onJoystickAxisChanged self._joystick.onButtonPressed += self._onJoystickButtonPressed else: self._joystick = None def _onJoystickAxisChanged(self, sender, index): if self._started.get() and sender == self._joystick: axisValue = self._joystick.getAxisValue(index) if index == 0: self._yaw.set(axisValue) self._updateTarget() elif index == 1 and not Cockpit.THROTTLE_BY_USER: thrust = -axisValue self._throttle.set(thrust) self._updateTarget() elif index == 2 and Cockpit.THROTTLE_BY_USER: rowThrottle = (axisValue + 100.0)/2.0 if rowThrottle < 10.0: throttle = rowThrottle * 6.0 elif rowThrottle < 90.0: throttle = 60.0 + ((rowThrottle - 10.0) / 8.0) else: throttle = 70.0 + (rowThrottle - 90.0) * 3.0 self._throttle.set(throttle) self._sendThrottle() elif index == 3: x = 196 + axisValue * 2 lastCoords = self._shiftCanvas.coords(self._shiftMarker) coords = (x, lastCoords[1]) self._plotShiftCanvasMarker(coords) elif index == 4: y = 196 + axisValue * 2 lastCoords = self._shiftCanvas.coords(self._shiftMarker) coords = (lastCoords[0], y) self._plotShiftCanvasMarker(coords) def _onJoystickButtonPressed(self, sender, index): if sender == self._joystick and index == 7: if self._started.get() == 0: self._startedCB.select() else: self._startedCB.deselect() # Tkinter's widgets seem not to be calling the event-handler # when they are changed programmatically. Therefore, the # even-handler is called explicitly here. self._startedCBChanged() def exit(self): self._link.send({"key": "close", "data": None}) self._stopUpdateInfoThread() self._link.close() if Cockpit.JOYSTICK_ENABLED: self._joystickManager.stop() self.quit() def _updateTarget(self): markerCoords = self._shiftCanvas.coords(self._shiftMarker) coords = ((markerCoords[0] + markerCoords[2]) / 2, (markerCoords[1] + markerCoords[3]) / 2) self._target[0] = float(coords[1] - 200) / 2.0 # X-axis angle / X-axis acceleration self._target[1] = float(coords[0] - 200) / 2.0 # Y-axis angle / Y-axis acceleration #Remote control uses clockwise angle, but the drone's referece system uses counter-clockwise angle self._target[2] = -self._yaw.get() # Z-axis angular speed # Z-axis acceleration (thrust). Only when the motor throttle is not controlled by user directly if Cockpit.THROTTLE_BY_USER: self._target[3] = 0.0 else: self._target[3] = self._throttle.get() self._sendTarget() def _keyDown(self, event): if event.keysym == "Escape": self._throttle.set(0) self._started.set(0) self._thrustScale.config(state=DISABLED) self._stopUpdateInfoThread() self._sendIsStarted() elif event.keysym.startswith("Control"): self._controlKeyActive = True elif not self._controlKeysLocked and self._controlKeyActive: if event.keysym == "Up": self._thrustScaleUp() elif event.keysym == "Down": self._thrustScaleDown() elif event.keysym == "Left": self._yawLeft() elif event.keysym == "Right": self._yawRight() elif event.keysym == "space": self._yawReset() if not Cockpit.THROTTLE_BY_USER: self._thrustReset() elif not self._controlKeysLocked and not self._controlKeyActive: if event.keysym == "Up": self._moveShiftCanvasMarker((0,-5)) elif event.keysym == "Down": self._moveShiftCanvasMarker((0,5)) elif event.keysym == "Left": self._moveShiftCanvasMarker((-5,0)) elif event.keysym == "Right": self._moveShiftCanvasMarker((5,0)) elif event.keysym == "space": self._resetShiftCanvasMarker() def _keyUp(self, eventArgs): if eventArgs.keysym.startswith("Control"): self._controlKeyActive = False def _onMouseButton1(self, eventArgs): self._lastMouseCoords = (eventArgs.x, eventArgs.y) def _onMouseButtonRelease1(self, eventArgs): self._shiftCanvas.coords(self._shiftMarker, 196, 196, 204, 204) def _limitCoordsToSize(self, coords, size, width): maxSize = size-(width/2.0) minSize = -(width/2.0) if coords[0] > maxSize: x = maxSize elif coords[0] < minSize: x = minSize else: x = coords[0] if coords[1] > maxSize: y = maxSize elif coords[1] < minSize: y = minSize else: y = coords[1] return (x,y) def _plotShiftCanvasMarker(self, coords): coords = self._limitCoordsToSize(coords, 400, 8) self._shiftCanvas.coords(self._shiftMarker, coords[0], coords[1], coords[0] + 8, coords[1] + 8) self._updateTarget() def _moveShiftCanvasMarker(self, shift): lastCoords = self._shiftCanvas.coords(self._shiftMarker) newCoords = (lastCoords[0] + shift[0], lastCoords[1] + shift[1]) self._plotShiftCanvasMarker(newCoords) def _resetShiftCanvasMarker(self): self._shiftCanvas.coords(self._shiftMarker, 196, 196, 204, 204) self._updateTarget() def _onMouseButton1Motion(self, eventArgs): deltaCoords = (eventArgs.x - self._lastMouseCoords[0], eventArgs.y - self._lastMouseCoords[1]) self._moveShiftCanvasMarker(deltaCoords) self._lastMouseCoords = (eventArgs.x, eventArgs.y) def _onMouseDoubleButton1(self, eventArgs): self._resetShiftCanvasMarker() def _onMouseButton3(self, eventArgs): self._lastMouseCoords = (eventArgs.x, eventArgs.y) self._mouseDirection = Cockpit.DIR_NONE def _onMouseButtonRelease3(self, eventArgs): self._shiftCanvas.coords(self._shiftMarker, 196, 196, 204, 204) def _onMouseButton3Motion(self, eventArgs): deltaCoords = (eventArgs.x - self._lastMouseCoords[0], eventArgs.y - self._lastMouseCoords[1]) if self._mouseDirection == Cockpit.DIR_NONE: if abs(deltaCoords[0]) > abs(deltaCoords[1]): self._mouseDirection = Cockpit.DIR_HORIZONTAL else: self._mouseDirection = Cockpit.DIR_VERTICAL if self._mouseDirection == Cockpit.DIR_HORIZONTAL: deltaCoords = (deltaCoords[0], 0) else: deltaCoords = (0, deltaCoords[1]) self._moveShiftCanvasMarker(deltaCoords) self._lastMouseCoords = (eventArgs.x, eventArgs.y) def _thrustScaleUp(self): #TODO: 20160526 DPM: El valor de incremento de aceleración (1.0) puede ser muy alto if self._started.get(): newValue = self._thrustScale.get() \ + (Cockpit.THROTTLE_RESOLUTION if Cockpit.THROTTLE_BY_USER else 1.0) self._thrustScale.set(newValue) self._updateTarget() def _thrustScaleDown(self): #TODO: 20160526 DPM: El valor de decremento de aceleración (1.0) puede ser muy alto if self._started.get(): newValue = self._thrustScale.get() \ - (Cockpit.THROTTLE_RESOLUTION if Cockpit.THROTTLE_BY_USER else 1.0) self._thrustScale.set(newValue) self._updateTarget() def _thrustReset(self): if self._started.get(): self._thrustScale.set(0.0) self._updateTarget() def _onThrustScaleDoubleButton1(self, eventArgs): self._thrustReset() return "break" def _yawRight(self): newValue = self._yaw.get() + 1 self._yaw.set(newValue) self._updateTarget() def _yawLeft(self): newValue = self._yaw.get() - 1 self._yaw.set(newValue) self._updateTarget() def _yawReset(self): self._yaw.set(0) self._updateTarget() def _onMouseWheelUp(self, eventArgs): if not self._controlKeyActive: self._thrustScaleUp() else: self._yawRight() def _onMouseWheelDown(self, eventArgs): if not self._controlKeyActive: self._thrustScaleDown() else: self._yawLeft() def _onMouseWheel(self, eventArgs): factor = eventArgs.delta/(1200.0 if Cockpit.THROTTLE_BY_USER and not self._controlKeyActive else 120.0) if not self._controlKeyActive: if self._started.get(): newValue = self._thrustScale.get() + factor self._thrustScale.set(newValue) self._updateTarget() else: newValue = self._yaw.get() + factor self._yaw.set(newValue) self._updateTarget() def _onYawScaleChanged(self, eventArgs): self._updateTarget() def _onYawScaleDoubleButton1(self, eventArgs): self._yawReset() return "break" def _startedCBChanged(self): if not self._started.get(): self._throttle.set(0) self._thrustScale.config(state=DISABLED) #self._integralsCB.config(state=DISABLED) self._stopUpdateInfoThread() else: self._thrustScale.config(state="normal") #self._integralsCB.config(state="normal") self._startUpdateInfoThread() self._sendIsStarted() # def _integralsCBChanged(self): # # self._link.send({"key": "integrals", "data":self._integralsEnabled.get() != 0}) # def _onThrustScaleChanged(self, eventArgs): if Cockpit.THROTTLE_BY_USER: self._sendThrottle() else: self._updateTarget() def _sendThrottle(self): self._link.send({"key": "throttle", "data": self._throttle.get()}) def _sendTarget(self): self._link.send({"key": "target", "data": self._target}) def _sendIsStarted(self): isStarted = self._started.get() != 0 self._link.send({"key": "is-started", "data": isStarted}) def _sendPidCalibrationData(self): if self._pidSelected.get() != "--" and self._axisSelected.get() != "--": pidData = { "pid": self._pidSelected.get(), "axis": self._axisSelected.get(), "p": float(self._pidPSpinbox.get()), "i": float(self._pidISpinbox.get()), "d": float(self._pidDSpinbox.get())} self._link.send({"key": "pid-calibration", "data": pidData}) def _updatePidCalibrationData(self): pid = self._pidSelected.get() axis = self._axisSelected.get() if pid != "--" and axis != "--": self._pidConstants[pid][axis]["P"] = float(self._pidPSpinbox.get()) self._pidConstants[pid][axis]["I"] = float(self._pidISpinbox.get()) self._pidConstants[pid][axis]["D"] = float(self._pidDSpinbox.get()) def _readDroneConfig(self): self._link.send({"key": "read-drone-config", "data": None}, self._onDroneConfigRead) def _readDroneState(self): if not self._readingState: self._readingState = True self._link.send({"key": "read-drone-state", "data": None}, self._onDroneStateRead) def _readPidConfigItem(self, message, cockpitKey, axises, configKeys): for i in range(len(axises)): for j in range(len(Cockpit.PID_KEYS)): self._pidConstants[cockpitKey][axises[i]][Cockpit.PID_KEYS[j]] = message[configKeys[j]][i] def _onDroneConfigRead(self, message): #TODO Show current configuration within the GUI (at least relevant settings) if message: #Angle-speeds self._readPidConfigItem(message, Cockpit.KEY_ANG_SPEED, ["X", "Y", "Z"], \ [Configuration.PID_ANGLES_SPEED_KP, \ Configuration.PID_ANGLES_SPEED_KI, \ Configuration.PID_ANGLES_SPEED_KD]) #Angles self._readPidConfigItem(message, Cockpit.KEY_ANGLES, ["X", "Y"], \ [Configuration.PID_ANGLES_KP, \ Configuration.PID_ANGLES_KI, \ Configuration.PID_ANGLES_KD]) #Accels self._readPidConfigItem(message, Cockpit.KEY_ACCEL, ["X", "Y", "Z"], \ [Configuration.PID_ACCEL_KP, \ Configuration.PID_ACCEL_KI, \ Configuration.PID_ACCEL_KD]) def _onDroneStateRead(self, state): if state: for index in range(4): self._throttleTexts[index].set("{0:.3f}".format(state["_throttles"][index])) for index in range(3): self._accelTexts[index].set("{0:.3f}".format(state["_accels"][index])) self._angleTexts[index].set("{0:.3f}".format(state["_angles"][index])) currentPeriod = state["_currentPeriod"] if currentPeriod > 0.0: freq = 1.0/currentPeriod self._loopRateText.set("{0:.3f}".format(freq)) else: self._loopRateText.set("--") else: self._stopUpdateInfoThread() self._readingState = False def _onPidSpinboxChanged(self): self._updatePidCalibrationData() self._sendPidCalibrationData() def _onPidListBoxChanged(self, pid): self._axisSelected.set("--") self._pidPString.set("--") self._pidIString.set("--") self._pidDString.set("--") self._pidPSpinbox.config(state=DISABLED) self._pidISpinbox.config(state=DISABLED) self._pidDSpinbox.config(state=DISABLED) self._selectedPidConstats = pid if pid == "--": self._axisListBox.config(state=DISABLED) self._controlKeysLocked = False else: self._axisListBox.config(state="normal") self._controlKeysLocked = True def _onAxisListBoxChanged(self, axis): if axis == "--" or (self._selectedPidConstats == Cockpit.KEY_ANGLES and axis == "Z"): self._pidPString.set("--") self._pidIString.set("--") self._pidDString.set("--") self._pidPSpinbox.config(state=DISABLED) self._pidISpinbox.config(state=DISABLED) self._pidDSpinbox.config(state=DISABLED) self._controlKeysLocked = axis != "--" else: self._pidPString.set("{:.2f}".format(self._pidConstants[self._selectedPidConstats][axis]["P"])) self._pidIString.set("{:.2f}".format(self._pidConstants[self._selectedPidConstats][axis]["I"])) self._pidDString.set("{:.2f}".format(self._pidConstants[self._selectedPidConstats][axis]["D"])) self._pidPSpinbox.config(state="normal") self._pidISpinbox.config(state="normal") self._pidDSpinbox.config(state="normal") self._controlKeysLocked = True def _updateInfo(self): while self._updateInfoThreadRunning: self._readDroneState() time.sleep(1.0) def _startUpdateInfoThread(self): self._updateInfoThreadRunning = True if not self._updateInfoThread.isAlive(): self._updateInfoThread.start() def _stopUpdateInfoThread(self): self._updateInfoThreadRunning = False if self._updateInfoThread.isAlive(): self._updateInfoThread.join()
configRowCol(box,1) #Generic function for combining functions def combine_funcs(*funcs): def combine_func(*args,**kwargs): for f in funcs: f(*args,**kwargs) return combine_func validateAgainstsample=IntVar() def get_sInputCheck(): return validateAgainstsample.get() #Add a button inside the tab sampleAutomataChk=Checkbutton(frmInsideTab1,text="Validate against sample",variable=validateAgainstsample,command=get_sInputCheck) sampleAutomataChk.pack(side=tk.TOP) btnGenerate=ttk.Button(frmInsideTab1,text="Generate Automata",width=15,command=generateAutomata) btnGenerate.pack(side=tk.TOP,fill=X,padx=2,pady=2) acceptrejectStatusvalue=Label(frmInsideTab1,text=sampleStatus,width=10,bg='blue') acceptrejectStatusvalue.pack(anchor='w',side=tk.TOP,fill=X,padx=2,pady=2) def displayFromBrowser(Canvas,flag): try: import webbrowser if flag=='ktail': if len(Canvas.find_all())==0: tkMessageBox.showinfo("FSM", 'Nothing to show.Please generate an FSM first') return webbrowser.open('../graph/ktail.png') elif flag=='sample':
def FileInfo(): top = tk.Tk() top.title("File and Device Info") checkCmd1 = IntVar() checkCmd2 = IntVar() checkCmd3 = IntVar() checkCmd4 = IntVar() checkCmd5 = IntVar() checkCmd6 = IntVar() checkCmd7 = IntVar() checkCmd8 = IntVar() checkCmd9 = IntVar() w = 1050 h = 320 x = 10 y = 50 def cbcommand1(): checkCmd1.set(not checkCmd1.get()) def cbcommand2(): checkCmd2.set(not checkCmd2.get()) def cbcommand3(): checkCmd3.set(not checkCmd3.get()) def cbcommand4(): checkCmd4.set(not checkCmd4.get()) def cbcommand5(): checkCmd5.set(not checkCmd5.get()) def cbcommand6(): checkCmd6.set(not checkCmd6.get()) def cbcommand7(): checkCmd7.set(not checkCmd7.get()) def cbcommand8(): checkCmd8.set(not checkCmd8.get()) def cbcommand9(): checkCmd9.set(not checkCmd9.get()) def ADD_PDOCallBack(): if ((TPDO.get() == '') or (RPDO.get() == '')): tkMessageBox.showinfo("Info", "Invalid PDO information !!") elif ((int(TPDO.get()) < 4) or (int(RPDO.get()) < 4)): tkMessageBox.showinfo("Info", "Minimum of 4 PDOs should be added") elif ((int(TPDO.get()) > 15) or (int(RPDO.get()) > 15)): tkMessageBox.showinfo( "Info", "Maximum of 15 PDOs only supported by this tool") else: for i in range(0, int(TPDO.get())): selected_index.append('180' + str(hex(i).split('x')[1]).upper()) lb1.insert( "end", '180' + str(hex(i).split('x')[1]).upper() + ' Transmit PDO Communication Parameter ' + str(i)) for i in range(0, int(TPDO.get())): selected_index.append('1A0' + str(hex(i).split('x')[1]).upper()) lb1.insert( "end", '1A0' + str(hex(i).split('x')[1]).upper() + ' Transmit PDO Mapping Parameter ' + str(i)) for i in range(0, int(RPDO.get())): selected_index.append('140' + str(hex(i).split('x')[1]).upper()) lb1.insert( "end", '140' + str(hex(i).split('x')[1]).upper() + ' Receive PDO Communication Parameter ' + str(i)) for i in range(0, int(RPDO.get())): selected_index.append('160' + str(hex(i).split('x')[1]).upper()) lb1.insert( "end", '160' + str(hex(i).split('x')[1]).upper() + ' Receive PDO Mapping Parameter ' + str(i)) tkMessageBox.showinfo("Info", "PDOs Added") top.geometry("%dx%d+%d+%d" % (w, h, x, y)) group1 = tk.LabelFrame(top, text="File Information").grid(row=0, columnspan=7, sticky='W', padx=5, pady=5, ipadx=140, ipady=120) Label(top, text="File Name : ").place(x=20, y=70) FileName = tk.Entry(top, width=25) FileName.pack() FileName.place(x=110, y=70) FileName.insert(0, "CANopen.eds") Label(top, text="File Version : ").place(x=20, y=100) FileVersion = tk.Entry(top, width=25) FileVersion.pack() FileVersion.place(x=110, y=100) Label(top, text="File Revision : ").place(x=20, y=130) FileRevision = tk.Entry(top, width=25) FileRevision.pack() FileRevision.place(x=110, y=130) Label(top, text="Description : ").place(x=20, y=160) Description = tk.Entry(top, width=25) Description.pack() Description.place(x=110, y=160) Label(top, text="Author : ").place(x=20, y=190) Author = tk.Entry(top, width=25) Author.pack() Author.place(x=110, y=190) group2 = tk.LabelFrame(top, text="Device Information").grid(row=0, columnspan=7, sticky='W', padx=305, pady=5, ipadx=150, ipady=120) Label(top, text="Vendor Name : ").place(x=320, y=70) VendorName = tk.Entry(top, width=25) VendorName.pack() VendorName.place(x=430, y=70) Label(top, text="Vendor Number : ").place(x=320, y=100) VendorNumber = tk.Entry(top, width=25) VendorNumber.pack() VendorNumber.place(x=430, y=100) Label(top, text="Product Name : ").place(x=320, y=130) ProductName = tk.Entry(top, width=25) ProductName.pack() ProductName.place(x=430, y=130) Label(top, text="Product Number : ").place(x=320, y=160) ProductNumber = tk.Entry(top, width=25) ProductNumber.pack() ProductNumber.place(x=430, y=160) Label(top, text="Revision Number : ").place(x=320, y=190) RevisionNumber = tk.Entry(top, width=25) RevisionNumber.pack() RevisionNumber.place(x=430, y=190) Label(top, text="Order Code : ").place(x=320, y=220) OrderCode = tk.Entry(top, width=25) OrderCode.pack() OrderCode.place(x=430, y=220) group3 = tk.LabelFrame(top, text="Supported Bit Rate").grid(row=0, columnspan=7, sticky='W', padx=650, pady=5, ipadx=80, ipady=150) checkBox1 = Checkbutton(top, variable=checkCmd1, text="10k Bit/Sec", command=cbcommand1) checkBox1.pack() checkBox1.place(x=700, y=20) checkBox2 = Checkbutton(top, variable=checkCmd2, text="20k Bit/Sec", command=cbcommand2) checkBox2.pack() checkBox2.place(x=700, y=50) checkBox3 = Checkbutton(top, variable=checkCmd3, text="50k Bit/Sec", command=cbcommand3) checkBox3.pack() checkBox3.place(x=700, y=80) checkBox4 = Checkbutton(top, variable=checkCmd4, text="100k Bit/Sec", command=cbcommand4) checkBox4.pack() checkBox4.place(x=700, y=110) checkBox5 = Checkbutton(top, variable=checkCmd5, text="125k Bit/Sec", command=cbcommand5) checkBox5.pack() checkBox5.place(x=700, y=140) checkBox6 = Checkbutton(top, variable=checkCmd6, text="250k Bit/Sec", command=cbcommand6) checkBox6.pack() checkBox6.place(x=700, y=170) checkBox7 = Checkbutton(top, variable=checkCmd7, text="500k Bit/Sec", command=cbcommand7) checkBox7.pack() checkBox7.place(x=700, y=200) checkBox8 = Checkbutton(top, variable=checkCmd8, text="800k Bit/Sec", command=cbcommand8) checkBox8.pack() checkBox8.place(x=700, y=230) checkBox9 = Checkbutton(top, variable=checkCmd9, text="1000k Bit/Sec", command=cbcommand9) checkBox9.pack() checkBox9.place(x=700, y=260) group4 = tk.LabelFrame(top, text="Number of PDOs").grid(row=0, columnspan=7, sticky='W', padx=850, pady=5, ipadx=80, ipady=80) Label(top, text="Transmit PDOs").place(x=890, y=100) TPDO = tk.Entry(top, width=10) TPDO.pack() TPDO.place(x=900, y=120) Label(top, text="Receive PDOs").place(x=890, y=170) RPDO = tk.Entry(top, width=10) RPDO.pack() RPDO.place(x=900, y=190) ADD = tk.Button(top, text="Add PDOs", command=ADD_PDOCallBack) ADD.pack() ADD.place(x=900, y=250) def SaveClose(): FILE_info[0] = (FileName.get()) FILE_info[1] = (FileVersion.get()) FILE_info[2] = (FileRevision.get()) FILE_info[3] = (Description.get()) FILE_info[4] = (Author.get()) DEVICE_info[0] = (VendorName.get()) DEVICE_info[1] = (VendorNumber.get()) DEVICE_info[2] = (ProductName.get()) DEVICE_info[3] = (ProductNumber.get()) DEVICE_info[4] = (RevisionNumber.get()) DEVICE_info[5] = (OrderCode.get()) PDO_info[0] = TPDO.get() PDO_info[1] = RPDO.get() BAUD_info[0] = str(checkCmd1.get()) BAUD_info[1] = str(checkCmd2.get()) BAUD_info[2] = str(checkCmd3.get()) BAUD_info[3] = str(checkCmd4.get()) BAUD_info[4] = str(checkCmd5.get()) BAUD_info[5] = str(checkCmd6.get()) BAUD_info[6] = str(checkCmd7.get()) BAUD_info[7] = str(checkCmd8.get()) BAUD_info[8] = str(checkCmd9.get()) tkMessageBox.showinfo("Info", "Closing File and Device Info Window") top.destroy() SaveButton = tk.Button(top, text="Save & Close", command=SaveClose) SaveButton.place(x=330, y=280) top.mainloop()
class tkLicenseGen: def __init__(self, master): master.title('Univention Lizenz Generator') self.master = master self.logoframe = Frame(self.master, bg='red') self.logoframe.pack(side=TOP, fill=X, expand=YES) self.lftopframes = LabelFrame(self.master) self.lftopframes.pack(side=TOP, fill=X, expand=YES) self.lframe = Frame(self.lftopframes) self.rframe = Frame(self.lftopframes) self.lframe.pack(side=LEFT, fill=X, expand=YES) self.rframe.pack(side=RIGHT, fill=X, expand=YES) self.bframe = Frame(self.master) self.bframe.pack(fill=X) self.kname = StringVar() self.kname.set('test') self.chkevar = IntVar() self.chkevar.set('1') self.chkivar = IntVar() self.chkovar = IntVar() self.chkdvar = IntVar() self.exday = StringVar() self.exmonth = StringVar() self.exyear = StringVar() self.getdate() # set date to localdate (month+3) try: self.logo = PhotoImage(file='/var/www/head_logo.gif') except TclError: # fall back to 64x64 white self.logo = PhotoImage(data='R0lGODdhQABAAIAAAP///wAAACwAAAAAQABAAAACRYSPqcvtD6OctNqLs968+w+G4kiW5omm6sq27gvH8kzX9o3n+s73/g8MCofEovGITCqXzKbzCY1Kp9Sq9YrNarfcrhdQAAA7') # self.logo.pack() #muss man nicht packen??!! self.logolabel = Label(self.logoframe, image=self.logo, bg='#CC3300') self.logolabel.pack(side=LEFT, fill=X, expand=YES) self.lfname = LabelFrame(self.lframe, font=("Helvetica", 11), text='Kundenname:') self.lfname.pack(fill=X) self.ekname = Entry(self.lfname, textvariable=self.kname, width=30) self.ekname.pack(side=LEFT) self.lfdate = LabelFrame(self.lframe, font=("Helvetica", 11), text='Ablaufdatum (TT/MM/JJ):') self.lfdate.pack(fill=X) self.eexd = Entry(self.lfdate, textvariable=self.exday, width=2) self.eexd.pack(side=LEFT) self.eexm = Entry(self.lfdate, textvariable=self.exmonth, width=2) self.eexm.pack(side=LEFT) self.eexy = Entry(self.lfdate, textvariable=self.exyear, width=2) self.eexy.pack(side=LEFT) self.chkdate = Checkbutton(self.lfdate, text='Unbeschränkt', variable=self.chkdvar) self.chkdate.pack(side=RIGHT) self.lfchke = LabelFrame(self.lframe, font=("Helvetica", 11), text='Evaluationslizenz:') self.lfchke.pack(fill=X) self.chke = Checkbutton(self.lfchke, variable=self.chkevar) self.chke.pack(side=LEFT) self.lfchki = LabelFrame(self.lframe, font=("Helvetica", 11), text='Interne Lizenz:') self.lfchki.pack(fill=X) self.chki = Checkbutton(self.lfchki, variable=self.chkivar) self.chki.pack(side=LEFT) self.lfchko = LabelFrame(self.lframe, font=("Helvetica", 11), text='Altes Lizenzformat (vor 1.2-3):') self.lfchko.pack(fill=X) self.chko = Checkbutton(self.lfchko, variable=self.chkovar, command=self.makegrey) self.chko.pack(side=LEFT) self.kdn = StringVar() self.kdn.set('dc=univention,dc=de') self.lfdn = LabelFrame(self.rframe, font=("Helvetica", 11), text='Kunde DN:') self.lfdn.pack(fill=X) self.ekdn = Entry(self.lfdn, textvariable=self.kdn, width=30) self.ekdn.pack(side=LEFT) self.kmaxacc = IntVar() self.kmaxacc.set('999') self.kmaxgacc = IntVar() self.kmaxgacc.set('999') self.kmaxcli = IntVar() self.kmaxcli.set('999') self.kmaxdesk = IntVar() self.kmaxdesk.set('999') self.chkmaxaccvar = IntVar() self.chkmaxaccvar.set('0') self.chkmaxgaccvar = IntVar() self.chkmaxgaccvar.set('0') self.chkmaxclivar = IntVar() self.chkmaxclivar.set('0') self.chkmaxdeskvar = IntVar() self.chkmaxdeskvar.set('0') self.lfmaxacc = LabelFrame(self.rframe, font=("Helvetica", 11), text='Max. Accounts:') self.lfmaxacc.pack(fill=X) self.lfmaxgacc = LabelFrame(self.rframe, font=("Helvetica", 11), text='Max. Groupware Accounts:') self.lfmaxgacc.pack(fill=X) self.lfmaxcli = LabelFrame(self.rframe, font=("Helvetica", 11), text='Max. Clients:') self.lfmaxcli.pack(fill=X) self.lfmaxdesk = LabelFrame(self.rframe, font=("Helvetica", 11), text='Max. Univention Desktops:') self.lfmaxdesk.pack(fill=X) self.emaxacc = Entry(self.lfmaxacc, textvariable=self.kmaxacc) self.emaxacc.pack(side=LEFT) self.chkmaxacc = Checkbutton(self.lfmaxacc, text='Unbeschränkt', variable=self.chkmaxaccvar) self.chkmaxacc.pack(side=LEFT) self.emaxgacc = Entry(self.lfmaxgacc, textvariable=self.kmaxgacc) self.emaxgacc.pack(side=LEFT) self.chkmaxgacc = Checkbutton(self.lfmaxgacc, text='Unbeschränkt', variable=self.chkmaxgaccvar) self.chkmaxgacc.pack(side=LEFT) self.emaxcli = Entry(self.lfmaxcli, textvariable=self.kmaxcli) self.emaxcli.pack(side=LEFT) self.chkmaxcli = Checkbutton(self.lfmaxcli, text='Unbeschränkt', variable=self.chkmaxclivar) self.chkmaxcli.pack(side=LEFT) self.emaxdesk = Entry(self.lfmaxdesk, textvariable=self.kmaxdesk) self.emaxdesk.pack(side=LEFT) self.chkmaxdesk = Checkbutton(self.lfmaxdesk, text='Unbeschränkt', variable=self.chkmaxdeskvar) self.chkmaxdesk.pack(side=LEFT) self.bexit = Button(self.bframe, text='Beenden', command=self.quit) self.bexit.pack(side=RIGHT) self.bsave = Button(self.bframe, text='Lizenz erzeugen', command=self.generate) self.bsave.pack(side=RIGHT) def generate(self): makelicense = ['univention_make_license'] path = tkFileDialog.asksaveasfilename(initialdir='~', initialfile=self.kname.get() + '-license', defaultextension='.ldif') # print path if path: if self.chkevar.get(): makelicense.append('-e') if self.chkivar.get(): makelicense.append('-i') makelicense.append('-f') makelicense.append(path) if not self.chkdvar.get(): makelicense.append('-d') makelicense.append("%s/%s/%s" % (self.exmonth.get(), self.exday.get(), self.exyear.get())) if not self.chkovar.get(): if not self.chkmaxaccvar.get(): makelicense.append('-a') makelicense.append('%d' % self.kmaxacc.get()) else: makelicense.append('-a') makelicense.append('unlimited') if not self.chkmaxgaccvar.get(): makelicense.append('-g') makelicense.append('%d' % self.kmaxgacc.get()) else: makelicense.append('-g') makelicense.append('unlimited') if not self.chkmaxclivar.get(): makelicense.append('-c') makelicense.append('%d' % self.kmaxcli.get()) else: makelicense.append('-c') makelicense.append('unlimited') if not self.chkmaxdeskvar.get(): makelicense.append('-u') makelicense.append('%d' % self.kmaxdesk.get()) else: makelicense.append('-u') makelicense.append('unlimited') else: makelicense.append('-o') makelicense.append(self.kname.get()) makelicense.append(self.kdn.get()) os.chdir('/home/groups/99_license/') p = subprocess.Popen(makelicense, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = p.communicate() if p.returncode == 0: showinfo('Lizenz Erstellt!', 'Die Lizenz für %s wurde erfolgreich erstellt!' % self.kname.get()) elif p.returncode == 257: showerror('Fehler', 'Errorcode: "%s"\nEvtl. sind Sie nicht in dem Sudoers File!' % p.returncode) elif p.returncode == 8704: showerror('Fehler', 'Errorcode: "%s"\nmake_license.sh meldet: "invalid DN"!' % p.returncode) else: print >>sys.stderr, '%r\n%s' % (makelicense, stdout) showerror('Fehler', 'Errorcode: "%s"\nEin unbekannter Fehler ist aufgetreten!\nBitte senden Sie eine komplette Fehlerbeschreibung an "*****@*****.**"' % p.returncode) # print makelicense # print '-->ErrorCode: %d'%i[0] # print i[1] def getdate(self): localtime = time.strftime('%d %m %y') split = localtime.split(' ') day = int(split[0]) month = int(split[1]) year = int(split[2]) month += 3 if month > 12: month = month - 12 year += 1 if day < 10: day = '0' + str(day) if month < 10: month = '0' + str(month) if year < 10: year = '0' + str(year) self.exday.set(day) self.exmonth.set(month) self.exyear.set(year) def makegrey(self): pass def quit(self, event=None): self.master.quit()
def init_gui(self): """init helper""" #setting up frames top_frame = Frame(self.root) mid_frame = Frame(self.root) radio_frame = Frame(self.root) res_frame = Frame(self.root) msg_frame = Frame(self.root) check_frame = Frame(self.root) history_frame = Frame(self.root) btn_frame = Frame(self.root) rating_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) mid_frame.pack(side=TOP, fill=X) history_frame.pack(side=TOP, fill=BOTH, expand=True) radio_frame.pack(side=TOP, fill=BOTH, expand=True) rating_frame.pack(side=TOP, fill=BOTH, expand=True) res_frame.pack(side=TOP, fill=BOTH, expand=True) check_frame.pack(side=TOP, fill=BOTH, expand=True) msg_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) # Binding F5 application-wide to run lint self.root.bind('<F5>', self.run_lint) #Message ListBox rightscrollbar = Scrollbar(msg_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.lbMessages = Listbox(msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white") self.lbMessages.bind("<Double-Button-1>", self.show_sourcefile) self.lbMessages.pack(expand=True, fill=BOTH) rightscrollbar.config(command=self.lbMessages.yview) bottomscrollbar.config(command=self.lbMessages.xview) #Message context menu self.mnMessages = Menu(self.lbMessages, tearoff=0) self.mnMessages.add_command(label="View in sourcefile", command=self.show_sourcefile) self.mnMessages.add_command(label="Add to ignore patchfile", command=self.add_to_ignore_patchfile) self.lbMessages.bind("<Button-3>", self.show_messages_context) #History ListBoxes rightscrollbar2 = Scrollbar(history_frame) rightscrollbar2.pack(side=RIGHT, fill=Y) bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL) bottomscrollbar2.pack(side=BOTTOM, fill=X) self.showhistory = Listbox(history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white") self.showhistory.pack(expand=True, fill=BOTH) rightscrollbar2.config(command=self.showhistory.yview) bottomscrollbar2.config(command=self.showhistory.xview) self.showhistory.bind('<Double-Button-1>', self.select_recent_file) self.set_history_window() #status bar self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) #labels self.lblRatingLabel = Label(rating_frame, text='Rating:') self.lblRatingLabel.pack(side=LEFT) self.lblRating = Label(rating_frame, textvariable=self.rating) self.lblRating.pack(side=LEFT) Label(mid_frame, text='Recently Used:').pack(side=LEFT) Label(top_frame, text='Module or package').pack(side=LEFT) #file textbox self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) #results box rightscrollbar = Scrollbar(res_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.results = Listbox(res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier") self.results.pack(expand=True, fill=BOTH, side=BOTTOM) rightscrollbar.config(command=self.results.yview) bottomscrollbar.config(command=self.results.xview) #buttons Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT) Button(top_frame, text='Open Package', command=(lambda: self.file_open(package=True))).pack(side=LEFT) self.btnRun = Button(top_frame, text='Run', command=self.run_lint) self.btnRun.pack(side=LEFT) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #radio buttons self.information_box = IntVar() self.convention_box = IntVar() self.refactor_box = IntVar() self.warning_box = IntVar() self.error_box = IntVar() self.fatal_box = IntVar() i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window) c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window) r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window) w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window) e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window) f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window) i.select() c.select() r.select() w.select() e.select() f.select() i.pack(side=LEFT) c.pack(side=LEFT) r.pack(side=LEFT) w.pack(side=LEFT) e.pack(side=LEFT) f.pack(side=LEFT) #check boxes self.box = StringVar() # XXX should be generated report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window) rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window) dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window) ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window) stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window) msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window) msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window) sourceFile = Radiobutton(radio_frame, text="Source File", variable=self.box, value="Source File", command=self.refresh_results_window) report.select() report.grid(column=0, row=0, sticky=W) rawMet.grid(column=1, row=0, sticky=W) dup.grid(column=2, row=0, sticky=W) msg.grid(column=3, row=0, sticky=W) stat.grid(column=0, row=1, sticky=W) msgCat.grid(column=1, row=1, sticky=W) ext.grid(column=2, row=1, sticky=W) sourceFile.grid(column=3, row=1, sticky=W) #dictionary for check boxes and associated error term self.msg_type_dict = { 'I': lambda: self.information_box.get() == 1, 'C': lambda: self.convention_box.get() == 1, 'R': lambda: self.refactor_box.get() == 1, 'E': lambda: self.error_box.get() == 1, 'W': lambda: self.warning_box.get() == 1, 'F': lambda: self.fatal_box.get() == 1 } self.txtModule.focus_set()
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())
#start program with dialog box, which will lead to either just terminating #or making a game box if __name__ == "__main__": player_dlg = Tk(); player_dlg.geometry("%dx%d+%d+%d" % (INIT_WINDOW_WIDTH, INIT_WINDOW_HEIGHT, X_POS, Y_POS)) # TODO: make dialog box show up in the middle of the screen based on # screen resolution player_dlg.title("How many players?") msg = Message(player_dlg, text="How many players will be playing this time?"); msg.pack() player_count = Entry(player_dlg) player_count.pack() ethan_eyes_var = IntVar() ethan_eyes_check = Checkbutton(player_dlg, \ text="enable Ethan Eyes", \ var=ethan_eyes_var) ethan_eyes_check.pack() confirm_button = Button(player_dlg, text="OK", \ command=lambda: generate_main(player_dlg, \ player_count, \ ethan_eyes_var) ); confirm_button.pack(); cancle_button = Button(player_dlg, text="Cancel", \ command=lambda: player_dlg.quit() ); cancle_button.pack(); player_dlg.mainloop();
form.hidden_input["hidden_var2"] = "value2" Label(form, text="Entry:").grid(row=0,column=0, sticky=E, pady=(8,0)) # The fieldname attribute is necessary to provide data to action entry = Entry(form) entry.fieldname = "entry" entry.grid(row=1,column=1, sticky =E+W) Label(form, text="Checkbuttons:").grid(row=2,column=0, sticky=E, pady=(8,0)) column = Frame(form) column.grid(row=3,column=1, sticky =E+W) checkbutton0 = Checkbutton(column, text="Option 0") checkbutton0.fieldname = "checkbutton0" checkbutton0.pack(side=LEFT) checkbutton1 = Checkbutton(column, text="Option 1") checkbutton1.fieldname = "checkbutton1" checkbutton1.pack(side=LEFT) checkbutton2 = Checkbutton(column, text="Option 2") checkbutton2.fieldname = "checkbutton2" checkbutton2.pack(side=LEFT) Label(form, text="Radiobuttons:").grid(row=4,column=0, sticky=E, pady=(8,0)) column = Frame(form) column.grid(row=5,column=1, sticky =E+W) # All radiobuttons require a variable variable = StringVar()