def initUI(self): self.parent.title("Buttons") self.style = Style() self.style.theme_use("default") frame = Frame(self, relief=GROOVE, borderwidth=5) frame.pack(fill=BOTH, expand=1) self.pack(fill = BOTH, expand = 1) self.imageLabel = Label(frame, image = "") self.imageLabel.pack(fill=BOTH, expand=1) closeButton = Button(self, text="Close") closeButton.pack(side=RIGHT) okButton = Button(self, text="OK") okButton.pack(side=RIGHT) options = [item for item in dir(cv2.cv) if item.startswith("CV_CAP_PROP")] option = OptionMenu(self, self.key, *options) self.key.set(options[0]) option.pack(side="left") spin = Spinbox(self, from_=0, to=1, increment=0.05) self.val = spin.get() spin.pack(side="left")
class StarterWindow(Tk): def __init__(self): Tk.__init__(self) self.wm_title("FRCA QBase Reader - Start Menu") self.exambtn = Button(self, text="start an exam", command=self.startExam) self.exambtn.pack() self.maxquestvar = IntVar() self.maxquest = Spinbox(self, from_=1, to=1667, width=4, textvariable=self.maxquestvar) self.maxquest.pack() self.questbtn = Button(self, text="start single questions", command=self.startQuestions) self.questbtn.pack() self.um = """User manual:\n Start either an exam or single questions\n Go to next question either with mouse or the <right arrow>\n Toggle checkboxes either with mouse or <keyboard buttons 1-5>\n In single question mode, show answer either with mouse or <return>\n In exam mode, results will display after the set question number\n Text can be made bigger/smaller with <Up> or <Down> keyboard arrows""" self.usermanual = Label(self, text=self.um, justify=LEFT) self.usermanual.pack() def startExam(self): call(["python", "exam.py", str(self.maxquestvar.get())]) def startQuestions(self): call(["python", "quest_by_quest.py"])
def __init__(self): # TTT related self.ttt = Board(ply=9) self.human_first = True # UI related self.root = Tk() self.root.resizable(0, 0) self.root.title("3D TTT") # TTT frames self.ttt_frames = [Frame(self.root) for x in range(3)] for i in range(3): self.ttt_frames[i].grid(row=0, column=i) self.button_pos = dict() self._init_board() # control frame self.control_frame = Frame(self.root, padx=5, pady=5) self.control_frame.grid(row=1, column=1) self.new_game_btn = Button(self.control_frame, text='New Game', \ command=lambda: self.reset()) self.new_game_btn.pack(side=LEFT, fill=BOTH, expand=True) self.toggle_human_first_btn = Button(self.control_frame, \ text='Human First', command=lambda: self.toggle_human_first()) self.toggle_human_first_btn.pack(side=RIGHT, fill=BOTH, expand=True) self.ply_box = Spinbox(self.control_frame, from_=1, to=20, \ textvariable=self.ttt.difficulty, command=lambda: self.reset()) self.ply_box.pack(side=RIGHT, fill=BOTH, expand=True) # start UI self.update_pieces() self.start() self.root.mainloop()
def __init__(self, root, prtr, settings, log, *arg): LabelFrame.__init__(self, root, *arg, text="Extruder") self.app = root self.printer = prtr self.settings = settings self.log = log self.bExtrude = Button(self, text="Extrude", width=10, command=self.doExtrude) self.bExtrude.grid(row=1, column=1, padx=2) self.spDistance = Spinbox(self, from_=1, to=MAXDIST, width=6, justify=RIGHT) self.spDistance.grid(row=1, column=2) self.spDistance.delete(0, END) self.spDistance.insert(0, STARTDIST) self.spDistance.bind("<FocusOut>", self.valDistance) self.spDistance.bind("<Leave>", self.valDistance) l = Label(self, text="mm", justify=LEFT) l.grid(row=1, column=3, sticky=W) self.bReverse = Button(self, text="Reverse", width=10, command=self.doReverse) self.bReverse.grid(row=2, column=1, padx=2) self.spSpeed = Spinbox(self, from_=1, to=MAXFEED, width=6, justify=RIGHT) self.spSpeed.grid(row=2, column=2) self.spSpeed.delete(0, END) self.spSpeed.insert(0, self.settings.efeed) self.spSpeed.bind("<FocusOut>", self.valSpeed) self.spSpeed.bind("<Leave>", self.valSpeed) l = Label(self, text="mm/min", justify=LEFT) l.grid(row=2, column=3, sticky=W)
def create_btc_balance_picker(self, master, previous_row=-1, previous_column=-1): self.btc_balance_str = StringVar() btc_balance_lbl = Label(master, textvar=self.btc_balance_str) btc_balance_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=2, sticky=W + E, padx=(3, 0)) btc_balance_lbl.config(bg=background_colour, fg=label_font_colour) self.set_available_btc_balance(Decimal(0)) btc_to_use_label = Label(master, text="BTC to spend:", bg=background_colour, fg=label_font_colour) btc_to_use_label.grid(row=previous_row + 2, column=previous_column + 1, sticky=E, padx=(3, 0)) self.btc_to_use_spinbox = Spinbox( master, from_=minimum_trade, to=minimum_trade, increment=btc_to_use_increment, highlightbackground=background_colour) self.btc_to_use_spinbox.config(borderwidth=2, relief=default_relief) self.btc_to_use_spinbox.grid(row=previous_row + 2, column=previous_column + 2)
def initUI(self): self.frame_top = Frame(self) self.frame_graph = MplCanvas(self) self.frame_bottom = Frame(self) Label(self.frame_top, text='Z = ').pack(side=LEFT) self.spin_z = Spinbox(self.frame_top, from_=0, to=self.shape[2] - 1, increment=1, command=self.change_z) self.spin_z.pack(side=LEFT) self.make_checkbox(self.frame_bottom, width=4) Label(self.frame_top, text=' CSV').pack(side=LEFT) self.txt_filename_csv = Entry(self.frame_top) self.txt_filename_csv.pack(side=LEFT) self.button_read = Button(self.frame_top, text='Read', command=self.run_read) self.button_read.pack(side=LEFT) self.button_save = Button(self.frame_top, text='Save', command=self.run_save) self.button_save.pack(side=LEFT) Label(self.frame_top, text=' ').pack(side=LEFT) button_reset = Button(self.frame_top, text='Reset', command=self.reset).pack(side=LEFT) self.frame_top.pack(side=TOP) self.frame_graph.get_tk_widget().pack(fill=BOTH, expand=TRUE) self.frame_bottom.pack(fill=BOTH, expand=TRUE) self.pack(fill=BOTH, expand=True)
def createSnakeSpinBoxes(self): frame = Frame(self.menuFrame, width=300) from_ = 0 to = 255 vcmd = (self.register(self.validateSpinBox),'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') label1 = Label(frame, text="Parametr 1") self.snakeValue1 = StringVar() self.snakeSpinBox = Spinbox(frame, textvariable=self.snakeValue1, width=4, from_=from_, to=to, validate="key", validatecommand=vcmd) label2 = Label(frame, text="Parametr 2") self.snakeValue2 = StringVar() self.snakeSpinBox2 = Spinbox(frame, textvariable=self.snakeValue2, width=4, from_=from_, to=to, validate="key", validatecommand=vcmd) label3 = Label(frame, text="Parametr 3") self.snakeValue3 = StringVar() self.snakeSpinBox3 = Spinbox(frame, textvariable=self.snakeValue3, width=4, from_=from_, to=to, validate="key", validatecommand=vcmd) label1.grid(row=0, column=0, padx=(0,10), stick=N+W) label2.grid(row=1, column=0, padx=(0,10), stick=N+W) label3.grid(row=2, column=0, padx=(0,10), stick=N+W) self.snakeSpinBox.grid(row=0, column=1, stick=N+W) self.snakeSpinBox2.grid(row=1, column=1, stick=N+W) self.snakeSpinBox3.grid(row=2, column=1, stick=N+W) return frame
def _add_count(self, frame, index, name, default, option) : self.function[-1] = lambda v : [option]*int(v) self.variables[-1] = StringVar() self.variables[-1].set(default) label = Label(frame, text=name) label.grid(row=index, column=0, sticky='W', padx=10) field = Spinbox(frame, from_=0, to=100, textvariable=self.variables[-1]) field.grid(row=index, column=1, sticky='WE')
def __init__(self, frame, k): Spinbox.__init__(self, frame, from_=0, to=100000, increment=50, width=8) self.k = k
def __init__(self, **kwargs): master = None if 'master' not in kwargs else kwargs['master'] title = '' if 'title' not in kwargs else kwargs['title'] Frame.__init__(self, master) self.val = IntVar() self.lbl = Label(text=title) self.lbl.grid(row=0, column=0, sticky=W, in_=self) self.Spin = Spinbox(textvariable=self.val) self.Spin.grid(row=0, column=1, sticky=W, in_=self)
class LabeledSpin(Frame): def __init__(self, **kwargs): master = None if 'master' not in kwargs else kwargs['master'] title = '' if 'title' not in kwargs else kwargs['title'] Frame.__init__(self, master) self.val = IntVar() self.lbl = Label(text=title) self.lbl.grid(row=0, column=0, sticky=W, in_=self) self.Spin = Spinbox(textvariable=self.val) self.Spin.grid(row=0, column=1, sticky=W, in_=self)
def create_entry(self, cadence=None): if cadence is None: if len(self.cadences) > 0: cadence = int(self.cadences[-1].get()) + 10 else: cadence = 40 cadenceent = Spinbox(from_=10, to=180, width=3, master=self) cadenceent.delete(0, END) cadenceent.insert(0, cadence) self.cadences.append(cadenceent)
def ventanaImprimir(self): t = Toplevel(self) t.wm_title("Imprimir") Label(t, text="Numero de Copias por etiqueta").pack() w = Spinbox(t, from_=1, to=10) w.pack() buttonImprimir = Button(t, text="Imprimir", command=lambda:self.imprimir(int(w.get()),t)) buttonImprimir.pack()
def initUI(self): # Main Window self.parent.title("gBot") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) # Debug Window Toplevel1 = Toplevel(self) Toplevel1.title("gBot Debug Console") self.pack(fill=BOTH, expand=1) TL_T1 = Text(Toplevel1, width=50) TL_T1.pack() Toplevel1.state("withdrawn") Toplevel1.protocol('WM_DELETE_WINDOW', lambda:Toplevel1.state("withdrawn")) Toplevel1.attributes("-topmost", True) # Username Input L1 = Label(self, text="G+ User Name") L1.grid(row=0, column=0, sticky=E, ipady=1) E1 = Entry(self, width=30) E1.grid(row=0, column=1, ipady=1, sticky=E) # Password Input L2 = Label(self, text="G+ Password") L2.grid(row=1, column=0, sticky=E, ipady=1) E2 = Entry(self, width=30) E2.grid(row=1, column=1, ipady=1, sticky=E) # Output Path Input L3 = Label(self, text="Output Path") L3.grid(row=2, column=0, sticky=E, pady=1) E3 = Entry(self, width=30) E3.grid(row=2, column=1, ipady=1, sticky=E) E3.insert(0, "%s\links.txt" % (os.getcwd())) # Num Posts L4 = Label(self, text="# Of Posts") L4.grid(row=3, column=0, sticky=E, pady=1) S1 = Spinbox(self, from_=1, to=9999999, width=28) S1.grid(row=3, column=1, ipady=1, sticky=E) # Post Input T1 = Text(self, width=30) T1.grid(row=5, columnspan=2, sticky=W+E, pady=1) # Start button B1 = Button(self, text="Start Posting", command=lambda:self.doPosting(B1,TL_T1,E1.get(),E2.get(),T1.get(1.0,END),E3.get(),S1.get())) B1.grid(row=6,columnspan=2, sticky=W+E) # Debug button B2 = Button(self, text="Debug log", command=lambda:Toplevel1.state("normal")) B2.grid(row=7, columnspan=2, sticky=W+E) self.addDebug(TL_T1,"Started successfully")
def buscar(): root = Tkinter.Toplevel() jorn = Spinbox(root, from_=0, to=50) def boton(): listar(jorn.get()) but = Tkinter.Button(root, text="Buscar", command=boton) jorn.pack(side=LEFT) but.pack(side=RIGHT) root.mainloop()
def create_widgets(self): self.count = StringVar() self.count.set('0') self.lbCount = ttk.Label(self.frame, text='Number of constraints:') self.sbCount = Spinbox(self.frame, from_=0, to=1000, textvariable=self.count, width=10) self.lbType = ttk.Label(self.frame, text='Type') self.lbPrm1 = ttk.Label(self.frame, text='Parameter#1') self.lbPrm2 = ttk.Label(self.frame, text='Parameter#2') self.cbTypes = [] self.cbPrm1s = [] self.cbPrm2s = [] self.btOk = ttk.Button(self.frame, text='Ok', command=self.hide_window) self.btHelp = ttk.Button(self.frame, text='Help', command=self.show_help)
def __init__(self, root, prtr, settings, log, *arg): fn = os.path.join(settings.cmdFolder, "images", "control_xyz.png") self.image = Image.open(fn) self.photo = ImageTk.PhotoImage(self.image) LabelFrame.__init__(self, root, *arg, text="Movement") self.app = root self.hilite = None self.hilitemask = None self.settings = settings self.printer = prtr self.log = log l = Label(self, text="mm/min") l.grid(row=1, column=2) l = Label(self, text="X/Y Feed Rate:") l.grid(row=2, column=1, sticky=E) self.xyfeed = Spinbox(self, width=10, justify=RIGHT, from_=0, to=MAXFEED) self.xyfeed.grid(row=2, column=2) self.xyfeed.delete(0, END) self.xyfeed.insert(0, settings.xyfeed) self.xyfeed.bind("<FocusOut>", self.valxyFeed) self.xyfeed.bind("<Leave>", self.valxyFeed) l = Label(self, text="Z Feed Rate:") l.grid(row=3, column=1, sticky=E) self.zfeed = Spinbox(self, width=10, justify=RIGHT, from_=0, to=MAXFEED) self.zfeed.grid(row=3, column=2) self.zfeed.delete(0, END) self.zfeed.insert(0, settings.zfeed) self.zfeed.bind("<FocusOut>", self.valzFeed) self.zfeed.bind("<Leave>", self.valzFeed) self.canvas = Canvas(self, width=self.image.size[0], height=self.image.size[1], *arg) self.canvas.create_image((0, 0), image=self.photo, anchor=N+W) self.canvas.grid(row=4, column=1, columnspan=2) for m in imageMasks: self.canvas.create_oval((m[0][0]-mask_rad, m[0][1]-mask_rad, m[0][0]+mask_rad, m[0][1]+mask_rad), outline="#FF0000", width=4, tags=m[1], state=HIDDEN) self.canvas.bind("<Button-1>", self.OnLeftDown) self.canvas.bind("<Motion>", self.OnMotion) self.canvas.bind("<Enter>", self.OnEnter) self.canvas.bind("<Leave>", self.OnLeave) self.bAllOff = Button(self, text="Release Motors", command=self.allMotorsOff) self.bAllOff.grid(row=5, column=1, columnspan=2)
def __init__(self, parent): self.colorNegative = [] self.colorNeutral = [] self.colorPositive = [] self.scaleNegative = 0.0 self.scalePositive = 0.0 self.cNegative = '#ff0000' self.cNeutral = '#000000' self.cPositive = '#0000ff' self.minNegativeLbl = Label(rootC, text='Min Found: -') self.maxPositiveLbl = Label(rootC, text='Max Found: -') self.scaleLbl = Label(rootC, text='Scale: - to -') self.sclSelectPositive = Spinbox(rootC) self.sclSelectPositive.insert(0, 0.0) self.sclSelectNegative = Spinbox(rootC) self.sclSelectNegative.insert(0, 0.0) self.buttonNegativeCharge = Button( rootC, text='Negative Charge Color', command=self.chooseNegativeCharge) self.buttonNeutralCharge = Button( rootC, text='Neutral Charge Color', command=self.chooseNeutralCharge) self.buttonPositiveCharge = Button( rootC, text='Positive Charge Color', command=self.choosePositiveCharge) self.buttonBG = Button( rootC, text='Background Color', command=self.chooseBackground) self.buttonUpdateColor = Button( rootC, text='Update', command=self.updateColor) self.title = Label(rootC, text="Select your colors") self.buttonClose = Button(rootC, text="Close", command=rootC.destroy) self.buttonBG.pack() self.title.pack() self.buttonNegativeCharge.pack() self.buttonNeutralCharge.pack() self.buttonPositiveCharge.pack() self.minNegativeLbl.pack() self.maxPositiveLbl.pack() self.scaleLbl.pack() self.sclSelectNegative.pack() self.sclSelectPositive.pack() self.buttonUpdateColor.pack() self.buttonClose.pack()
def printTurn(self): frameS = PanedWindow(self.FrameInfo, orient=HORIZONTAL) turns = Label(frameS, text="Tour :") self.var.set(str(self.selectTurn)) self.Spin_T = Spinbox(frameS, values=self.turns.keys(), command=self.updateSpin_turn, textvariable=self.var) self.Spin_T.bind('<Return>', self.validateTurn) turns.pack() self.Spin_T.pack() frameS.add(turns) frameS.add(self.Spin_T) frameS.pack() self.frameT = frameS
def __init__(self, parent=None, text='Year:', min_value=1950, max_value=2100, **kwargs): # NOTE: This class used to be a subclass of Frame, but it did not grid properly #Frame.__init__(self, parent) self.label = Label(parent, text=text) self.year = StringVar() self.year_selector = Spinbox(parent, from_=min_value, to=max_value, textvariable=self.year, command=self.on_change, width=5) self.set_args()
def __createWidgets(self): self.__params = Frame(padx=5, pady=5) Label(text='Letters: ', anchor=E).grid(row=0, column=0, sticky=E, in_=self.__params) self.__char_entry = Entry(width=10) self.__chk1st = Checkbutton(variable=self.MANDATORY1stCHAR, command=self.__CB) Label(text='First letter appears in every result ', anchor=W).grid( row=0, column=4, sticky=E, in_=self.__params) self.__char_entry.grid(row=0, column=1, columnspan=2, sticky=W, in_=self.__params) self.__chk1st.grid(row=0, column=3, sticky=W, in_=self.__params) Label(text='Minimum length of result words: ', anchor=E).grid( row=1, column=0, sticky=E, in_=self.__params) self.__word_length_ctrl = Spinbox(from_=1, to=Application.MAXWORDLEN, width=2) self.__word_length_ctrl.delete(0, END) self.__word_length_ctrl.insert(0, Application. DEFAULTWORDLEN) self.__word_length_ctrl.grid(row=1, column=1, in_=self.__params, sticky=W) self.__go_button = Button(text='Go', command=self.__findWords) self.__go_button.grid(row=1, column=2, sticky=E, in_=self.__params) self.__Options = Menu() self.__Options.add_command(label='Choose dictionary', command=self.__choosedict) self.__File = Menu() self.__File.add_command(label='Export as ODT (Open document text)', command=self.__export) self.__char_entry.focus_set() self.__char_entry.bind("<Return>", self.__keyPressEnter)
class YearSelector(): def __init__(self, parent=None, text='Year:', min_value=1950, max_value=2100, **kwargs): # NOTE: This class used to be a subclass of Frame, but it did not grid properly #Frame.__init__(self, parent) self.label = Label(parent, text=text) self.year = StringVar() self.year_selector = Spinbox(parent, from_=min_value, to=max_value, textvariable=self.year, command=self.on_change, width=5) self.set_args() def set_args(self, **kwargs): self.check_other_func = kwargs['check_other_func'] if 'check_other_func' in kwargs else None def get_value(self): value = int(self.year.get()) return value def set_value(self, value): self.year.set(value) def set_grid(self, row=0, padx=0, pady=0): #self.grid(row=row) self.label.grid(row=row, column=0, sticky='e') self.year_selector.grid(row=row, column=1, padx=padx, pady=pady, sticky='w') def on_change(self): if self.check_other_func != None: value = int(self.year.get()) new_value = self.check_other_func(value) if value != new_value: self.set_value(new_value) else: pass def get_less_than(self, compare_value): value = int(self.year.get()) compare_value = int(compare_value) if value <= compare_value: return value return compare_value def get_greater_than(self, compare_value): value = int(self.year.get()) compare_value = int(compare_value) if value >= compare_value: return value return compare_value
def listar(n): conn = sqlite3.connect('marca.db') root = Tkinter.Toplevel() frame = Frame(root) frame2 = Frame(root) cursor = conn.execute("SELECT PARTIDO from CRONICAS WHERE JORNADA LIKE '" + n + "'") partidos = [] for c in cursor: partidos.append(c[0]) def cambio(): cursor = conn.execute( "SELECT CRONICA FROM CRONICAS WHERE PARTIDO LIKE '" + partido.get() + "'") for row in cursor: sql = "SELECT * FROM GOLES WHERE CRONICA LIKE '%" + row[0] + "%'" cursor = conn.execute(sql) lista.delete(0, END) i = 0 for row in cursor: i += 1 lista.insert( i, "EQUIPO: " + row[0] + " JUGADOR: " + row[1] + " MINUTO: " + row[2]) partido = Spinbox(frame, values=partidos, command=cambio) etiq = Label(frame, text="Elija Partido:") barra = Scrollbar(frame2) lista = Listbox(frame2, width=80, height=8) frame.pack(side=LEFT) frame2.pack(side=LEFT) lista.pack(side=LEFT, fill=BOTH) barra.pack(side=RIGHT, fill=Y) barra.config(command=lista.yview) etiq.pack(side=TOP) partido.pack(side=RIGHT) root.mainloop() conn.close()
def create_stop_loss(self, master, previous_row=-1, previous_column=-1): stop_loss_lbl = Label(master, text="Stop Loss (%):") stop_loss_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0)) stop_loss_lbl.config(bg=background_colour, fg=label_font_colour) self.stop_loss_spinbox = Spinbox(master, from_=-100.0, to=-10.0, increment=1.0, highlightbackground=background_colour) self.stop_loss_spinbox.config(borderwidth=2, relief=default_relief) self.stop_loss_spinbox.grid(row=previous_row + 1, column=previous_column + 2) self.stop_loss_spinbox.delete(0, "end") self.stop_loss_spinbox.insert(0, -10)
def create_auto_sell(self, master, previous_row=-1, previous_column=-1): auto_sell_lbl = Label(master, text="Auto Sell (%):") auto_sell_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0)) auto_sell_lbl.config(bg=background_colour, fg=label_font_colour) self.auto_sell_spinbox = Spinbox(master, from_=1.0, to=300.0, increment=1.0, highlightbackground=background_colour) self.auto_sell_spinbox.config(borderwidth=2, relief=default_relief) self.auto_sell_spinbox.grid(row=previous_row + 1, column=previous_column + 2) self.auto_sell_spinbox.delete(0, "end") self.auto_sell_spinbox.insert(0, 50)
def init_slow_time(root): slow_time_frame = Frame(root) slow_time_frame.pack(fill=X) slow_time_label = Label(slow_time_frame, text='Slowing time [0; 10] sec:') slow_time_label.pack(side='left') slow_time = Spinbox(slow_time_frame, from_=0, to=10, width=4) slow_time.delete(0, 1) slow_time.insert(0, 5) slow_time.pack(side='right') return slow_time_frame, slow_time_label, slow_time
def createCogSpinBoxes(self): frame = Frame(self.menuFrame, width=300) from_ = 0 to = 100 vcmd = (self.register(self.validateSpinBox),'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') label1 = Label(frame, text="Wsp. kary za rzadkość") self.densityCoefficient = StringVar(value="10") self.cogSpinBox = Spinbox(frame, textvariable=self.densityCoefficient, width=4, from_=from_, to=to, validate="key", validatecommand=vcmd) label2 = Label(frame, text="Wsp. kary za odległość") self.distanceFromCenterCoefficient = StringVar(value="60") self.cogSpinBox2 = Spinbox(frame, textvariable=self.distanceFromCenterCoefficient, width=4, from_=from_, to=to, validate="key", validatecommand=vcmd) label1.grid(row=0, column=0, padx=(0,10), stick=N+W) label2.grid(row=1, column=0, padx=(0,10), stick=N+W) self.cogSpinBox.grid(row=0, column=1, stick=N+W) self.cogSpinBox2.grid(row=1, column=1, stick=N+W) return frame
def init_speed_sup(root): speed_sup_frame = Frame(root) speed_sup_frame.pack(fill=X) speed_sup_label = Label(speed_sup_frame, text='Max initial speed [0; 200]:') speed_sup_label.pack(side='left') speed_sup = Spinbox(speed_sup_frame, from_=0, to=200, width=4) speed_sup.delete(0, 1) speed_sup.insert(0, 60) speed_sup.pack(side='right') return speed_sup_frame, speed_sup_label, speed_sup
def init_spawn_sup(root): spawn_sup_frame = Frame(root) spawn_sup_frame.pack(fill=X) spawn_sup_label = Label(spawn_sup_frame, text='Max spawn interval [0; 10] sec:') spawn_sup_label.pack(side='left') spawn_sup = Spinbox(spawn_sup_frame, from_=0, to=10, width=4) spawn_sup.delete(0, 1) spawn_sup.insert(0, 5) spawn_sup.pack(side='right') return spawn_sup_frame, spawn_sup_label, spawn_sup
def init_range_of_vision(root): range_of_vision_frame = Frame(root) range_of_vision_frame.pack(fill=X) range_of_vision_label = Label(range_of_vision_frame, text='Range of vision [1; 10] (in cars):') range_of_vision_label.pack(side='left') range_of_vision = Spinbox(range_of_vision_frame, from_=1, to=10, width=4) range_of_vision.delete(0, 1) range_of_vision.insert(0, 3) range_of_vision.pack(side='right') return range_of_vision_frame, range_of_vision_label, range_of_vision
def init_speed_inf(root): speed_inf_frame = Frame(root) speed_inf_frame.pack(fill=X) speed_inf_label = Label(speed_inf_frame, text='Min initial speed [0; 200]:') speed_inf_label.pack(side='left') speed_inf = Spinbox(speed_inf_frame, from_=0, to=200, width=4) speed_inf.delete(0, 1) speed_inf.insert(0, 30) speed_inf.pack(side='right') return speed_inf_frame, speed_inf_label, speed_inf
def printTurn(self): frameS = PanedWindow(self.FrameInfo, orient=HORIZONTAL) turns = Label(frameS, text="Tour :") self.var.set(str(self.selectTurn)) self.Spin_T = Spinbox(frameS, values=self.turns.keys(), command = self.updateSpin_turn ,textvariable=self.var) self.Spin_T.bind('<Return>', self.validateTurn) turns.pack() self.Spin_T.pack() frameS.add(turns) frameS.add(self.Spin_T) frameS.pack() self.frameT = frameS
def createPreprocessBoxes(self): frame = Frame(self.menuFrame, width=300) from_ = 0 to = 100 vcmd = (self.register(self.validateSpinBox),'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') label1 = Label(frame, text="Erozja - ilosc przebiegow") self.erosion = StringVar(value="2") self.erosionSpinBox = Spinbox(frame, textvariable=self.erosion, width=4, from_=from_, to=to, validate="key", validatecommand=vcmd) label1.grid(row=0, column=0, padx=(0,10), stick=N+W) self.erosionSpinBox.grid(row=0, column=1, stick=N+W) return frame
def createBinarySpinBoxes(self): frame = Frame(self.menuFrame, width=300) from_ = 0 to = 255 vcmd = (self.register(self.validateSpinBox),'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') label1 = Label(frame, text="THRESHOLD (0,255)") self.binaryThreshold = StringVar(value="40") self.binarySpinBox = Spinbox(frame, textvariable=self.binaryThreshold, width=4, from_=from_, to=to, validate="key", validatecommand=vcmd) label1.grid(row=0, column=0, padx=(0,10), stick=N+W) self.binarySpinBox.grid(row=0, column=1, stick=N+W) return frame
def init_slow_factor(root): slow_factor_frame = Frame(root) slow_factor_frame.pack(fill=X) slow_factor_label = Label(slow_factor_frame, text='Slowing factor [0; 1]:') slow_factor_label.pack(side='left') slow_factor = Spinbox(slow_factor_frame, from_=0, to=1, width=4, increment=0.1) slow_factor.delete(0, 3) slow_factor.insert(0, 0.5) slow_factor.pack(side='right') return slow_factor_frame, slow_factor_label, slow_factor
def __init__(self, parent=None, **kwargs): Toplevel.__init__(self, parent) self.title('Job Parameters') self.parent = parent self.main_frame = Frame(self) self.input_directory_gui = DirectorySelector(self.main_frame, 'Input Directory:') self.output_directory_gui = DirectorySelector(self.main_frame, 'Output Directory:', get_default=lambda: self.input_directory_gui.get_directory() + '/output/') self.input_directory_gui.set_notify(self.notify) self.beginning_year = kwargs['beginning_year'] if 'beginning_year' in kwargs else 1950 self.ending_year = kwargs['ending_year'] if 'ending_year' in kwargs else 2100 self.beginning_year_selector = YearSelector(self.main_frame, text="Beginning Year:", min_value=self.beginning_year, max_value=self.ending_year) self.ending_year_selector = YearSelector(self.main_frame, text="Ending Year:", min_value=self.beginning_year, max_value=self.ending_year) self.one_decade_range_var = IntVar() self.one_decade_range = Checkbutton(self.main_frame, text='Calculate 10 Year Range', variable=self.one_decade_range_var, command=self.on_change) self.two_decade_range_var = IntVar() self.two_decade_range = Checkbutton(self.main_frame, text='Calculate 20 Year Range', variable=self.two_decade_range_var, command=self.on_change) self.custom_range_var = IntVar() self.custom_range = Checkbutton(self.main_frame, text='Calculate Custom Year Range', variable=self.custom_range_var, command=self.on_change) self.custom_range_val = StringVar() self.custom_range_input = Spinbox(self.main_frame, from_=30, to=100, textvariable=self.custom_range_val, command=self.on_change, width=5) # Initialize widget values self.beginning_year_selector.set_value(self.beginning_year) self.beginning_year_selector.set_args(check_other_func=self.ending_year_selector.get_less_than) self.ending_year_selector.set_value(self.ending_year) self.ending_year_selector.set_args(check_other_func=self.beginning_year_selector.get_greater_than) self.one_decade_range_var.set(1) self.two_decade_range_var.set(1) self.custom_range_var.set(0) self.custom_range_input.config(state=Tkinter.DISABLED) self.button_frame = Frame(self.main_frame) self.ok_button = Button(self.button_frame, text='OK', command=self.on_submit) self.cancel_button = Button(self.button_frame, text='Cancel', command=self.on_close) self.job_id = kwargs['job_id'] if 'job_id' in kwargs else None self.entry = kwargs['entry'] if 'entry' in kwargs else None self.grab_set() self.resizable(width=False, height=False)
def __init__(self, x, y, master=None): Frame.__init__(self, master) self.photo = None self.resolution = (x, y) #The center of the Canvas is 0, 0. Find the center so #we can draw the image properly. self.center = ( x/2, y/2) #Setup the canvas self.picture = Canvas(self, width=x, height=y) #Place the canvas in the Grid. self.picture.grid(row=0,column=0,columnspan=2) #Camera check button control. self.checkButton = Checkbutton(self, text='Camera?',\ command=self.toggleCamera) #Place it on the grid. self.checkButton.grid(row=1,column=0) #Spinbox to set FPS self.fpsSpin = Spinbox(self, text="FPS", from_=2, to=30,\ command=self.fpsSpinCallback) self.fpsSpin.grid(row=1, column=1) #Set framerate self.fpsSpinCallback() #To determine if the camera is running self.capturing = False
qlep.bind("<Enter>", on_enterlep) qlep.bind("<Leave>", on_leavelep) #Everything concerning jets: minnjet_val = IntVar() minnjet_val.set(0) # initialize integer for min number of jets maxnjet_val = IntVar() maxnjet_val.set(9) # initialize integer for max number of jets labelminjet = Label(frame1, text="Minimum:") labelmaxjet = Label(frame1, text="Maximum:") #Some labels for the entries minjet_entry = Spinbox(frame1, textvariable=minnjet_val, from_=0, to=9, width=4) #Entry for min number of jets maxjet_entry = Spinbox(frame1, textvariable=maxnjet_val, from_=0, to=9, width=4) #Entry for max number of jets btagmin_val = IntVar() btagmin_val.set(0) #Initialise minimum b-jets btagmax_val = IntVar() btagmax_val.set(9) #Initialise maximum b-jets labelminbjet = Label(frame1, text="Minimum:") labelmaxbjet = Label(frame1, text="Maximum:") #Labels for b-jets entries
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)
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()
def initUI(self): self.parent.title("LINEARITY TEST FOR PMT BASES") self.pack(fill=BOTH, expand=True) self.columnconfigure(0, weight=1) #self.rowconfigure(0, weight=1) # weight attibute is used to make them growable # self.graph_cb = BooleanVar() self.init_point = IntVar() self.base_path = StringVar() self.end_point = IntVar() self.step = IntVar() self.n_meas = IntVar() self.inc_point = IntVar() self.coef = DoubleVar() self.noise = DoubleVar() self.thr_sigma = DoubleVar() self.SPE_DAQ = DoubleVar() search = Image.open("next_logo.jpg") search_temp = search.resize((170, 200), Image.ANTIALIAS) search_aux = ImageTk.PhotoImage(search_temp) label1 = Label(self, image=search_aux) label1.image = search_aux label1.grid(row=0, column=0, columnspan=10, rowspan=10, sticky=E+W+S+N) #Text Box self.base_path.set("F:/DATOS_DAC/2052/pmt_0_trace_evt_") e1 = Entry(self, textvariable=self.base_path, width=40) e1.grid(row=1,column=2, sticky=W, columnspan=5, pady=5) e1_label = Label(self, text="DataSet path (including name file)") e1_label.grid(row=0,column=2,sticky=W, columnspan=5, pady=5) #Spin Boxes self.n_meas.set("20") sb1 = Spinbox(self, from_=1, to=1000, width=6, textvariable=self.n_meas) sb1.grid(row=3,column=3, sticky=W) sb1_label = Label(self, text="Measurements") sb1_label.grid(row=2,column=3, padx=0, sticky=W) self.step.set("10") sb2 = Spinbox(self, from_=10, to=200, width=6, textvariable=self.step) sb2.grid(row=3,column=4, sticky=W) sb2_label = Label(self, text="Pulse Width Step") sb2_label.grid(row=2,column=4, padx=0, sticky=W) # INTEGRATION LIMITS Integration_label = Label(self, text="INTEGRATION LIMITS", font = "Verdana 12 bold") Integration_label.grid(row=4,column=3, padx=5, columnspan = 3, pady=10) self.init_point.set("30") sb3 = Spinbox(self, from_=1, to=10000, width=6, textvariable=self.init_point) sb3.grid(row=7,column=3, sticky=W) sb3_label = Label(self, text="Start (usec)") sb3_label.grid(row=6,column=3, padx=0, sticky=W) self.end_point.set("160") sb4 = Spinbox(self, from_=1, to=10000, width=6, textvariable=self.end_point) sb4.grid(row=7,column=4, sticky=W) sb4_label = Label(self, text="End (usec)") sb4_label.grid(row=6,column=4, padx=0, sticky=W) # PARAMETERS Integration_label = Label(self, text="PARAMETERS", font = "Verdana 12 bold") Integration_label.grid(row=8,column=3, padx=5, columnspan = 3, pady=10) self.inc_point.set("3") sb5 = Spinbox(self, from_=1, to=100, width=6, textvariable=self.inc_point) sb5.grid(row=11,column=3, sticky=W) sb5_label = Label(self, text="First point") sb5_label.grid(row=10,column=3, padx=0, sticky=W) self.coef.set("1.636E-3") e6 = Entry(self, width=10, textvariable=self.coef) e6.grid(row=11,column=4, sticky=W) e6_label = Label(self, text="DBLR Coef") e6_label.grid(row=10,column=4, sticky=W) self.noise.set("0.75") e7 = Entry(self, width=10, textvariable=self.noise) e7.grid(row=11,column=5, sticky=W) e7_label = Label(self, text="Noise (LSB)") e7_label.grid(row=10,column=5, sticky=W) self.thr_sigma.set("40") e8 = Entry(self, width=10, textvariable=self.thr_sigma) e8.grid(row=13,column=3, sticky=W) e8_label = Label(self, text="Threshold") e8_label.grid(row=12,column=3, sticky=W) self.SPE_DAQ.set("20.5") e9 = Entry(self, width=10, textvariable=self.SPE_DAQ) e9.grid(row=13,column=4, sticky=W) e9_label = Label(self, text="SPE (LSB)") e9_label.grid(row=12,column=4, sticky=W) # #Check buttons # cb1 = Checkbutton(self, text="MultiGraph Output", variable=self.graph_cb ) # cb1.select() # cb1.grid(row=7,column=6, sticky=W) # Main buttons obtn = Button(self, text="GO!!", command=self.linearity_f) obtn.grid(row=14, column=4, sticky=E, pady=10) cbtn = Button(self, text="Quit", command=self.quit) cbtn.grid(row=14, column=5, sticky=E, pady=10) hbtn = Button(self, text="Help") hbtn.grid(row=14, column=0, sticky=W, pady=10)
class PeakFinder: def __init__(self, master): self.master = master master.title(u"Weiterreißwiderstand") self.big_font = tkFont.Font(family='Helvetica', size=36, weight='bold') self.normal_font = tkFont.Font(family='Helvetica', size=20, weight='normal') self.X = None self.Y = None self.maxima = None self.maxima_x = None self.number_max = 0 self.number_max_string = StringVar() self.max_max = 0.0 self.max_max_string = StringVar() self.min_max = 0.0 self.min_max_string = StringVar() self.median = 0.0 self.median_string = StringVar() self.w_string = StringVar() self.distance_string = StringVar() self.method_string = StringVar() self.sample_file = '' self.project_file = '' self.w = 0.0 self.distance = 0.0 ######################################################################### ''' Optionen für Dateidialoge ''' self.file_opt = options = {} options['defaultextension'] = '.txt' options['filetypes'] = [('text files', '.txt')] options['initialfile'] = '' options['parent'] = master options['title'] = 'Messung importieren' self.file_opt2 = options = {} options['defaultextension'] = '.txt' options['filetypes'] = [('text files', '.txt')] options['initialfile'] = '' options['parent'] = master options['title'] = 'Neues Projekt erstellen.' self.file_opt3 = options = {} options['defaultextension'] = '.txt' options['filetypes'] = [('text files', '.txt')] options['initialfile'] = '' options['parent'] = master options['title'] = 'Vorhandenes Projekt öffnen.' ##################################################################################################### ''' GUI ''' ''' MenueLeiste ''' ############################################################################################### self.menubar = Menu(master) # create a pulldown menu, and add it to the menu bar self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label="Neu", command=self.new_file, font = self.normal_font) self.filemenu.add_command(label=u"Öffnen...", command=self.open_file, font = self.normal_font) self.filemenu.add_separator() self.filemenu.add_command(label="Messung importieren", command=self.get_filepath, font = self.normal_font) self.filemenu.add_separator() self.filemenu.add_command(label="Beenden", command=root.quit, font = self.normal_font) self.menubar.add_cascade(label="Datei", menu=self.filemenu, font = self.normal_font) self.helpmenu = Menu(self.menubar, tearoff=0) self.helpmenu.add_command(label="Hilfe", command=self.help, font = self.normal_font) self.helpmenu.add_command(label=u"Über", command=self.info, font = self.normal_font) self.menubar.add_cascade(label="Hilfe", menu=self.helpmenu, font = self.normal_font) master.config(menu=self.menubar) ############################################################################################## ''' Parameter ''' self.option_label = ttk.Label(master, text = "Parameter", font = self.big_font) self.option_label.grid(row = 0, rowspan = 2, columnspan = 4, sticky=W) self.delta_x_label = ttk.Label(master, text = "Delta X", font = self.normal_font) self.delta_x_label.grid(row = 3, sticky=W) self.delta_x_spinbox = Spinbox(master, from_=10, to=500, increment = 10, font = self.normal_font, width = 4, command = self.plot) self.delta_x_spinbox.grid(row = 3, column = 1) self.delta_y_label = ttk.Label(master, text = "Delta Y", font = self.normal_font) self.delta_y_label.grid(row = 4, column = 0, sticky=W) self.delta_y_spinbox = Spinbox(master, from_=0, to=2, increment = 0.05, font = self.normal_font, width = 4, command = self.plot) self.delta_y_spinbox.grid(row = 4, column = 1) # self.plot_button = Button(master, text = "Plotten", font = self.normal_font, command = self.plot, width = 10) # self.plot_button.grid(row = 3, column = 2, columnspan = 1) self.sample_thickness_label = ttk.Label(master, text = "Probendicke [mm]", font = self.normal_font) self.sample_thickness_label.grid(row = 5, column = 0, sticky=W) self.sample_thickness_entry = ttk.Entry(master, font = self.normal_font, width = 5) self.sample_thickness_entry.grid(row = 5, column = 1) self.calculate_button = Button(master, text = "Berechnen", font = self.normal_font, command = self.calculate, width = 10) self.calculate_button.grid(row = 6, column = 1, columnspan = 1) ########################################################################################################## ''' Speichern ''' self.save_label = ttk.Label(master, text = "Auswertung Speichern", font = self.big_font) self.save_label.grid(row = 7, rowspan = 2, columnspan = 4, sticky=W) self.sample_name_label = ttk.Label(master, text = "Probenname", font = self.normal_font) self.sample_name_label.grid(row = 9, sticky=W) self.sample_name_entry = ttk.Entry(master, font = self.normal_font) self.sample_name_entry.grid(row = 9, column = 1, columnspan = 3) self.comment_label = ttk.Label(master, text = "Kommentar", font = self.normal_font) self.comment_label.grid(row = 10, sticky=W) self.comment_entry = ttk.Entry(master, font = self.normal_font) self.comment_entry.grid(row = 10, column = 1, columnspan = 3) self.save_button = Button(master, text = "Speichern", font = self.normal_font, command = self.save, width = 10) self.save_button.grid(row = 12, column = 1, columnspan = 2, sticky=W) ############################################################################################################## ''' Analyse ''' self.number_max_label = ttk.Label(master, text = "Anzahl Maxima:", font = self.normal_font) self.number_max_label.grid(row = 9, column = 6, sticky=W) self.number_max_int_label = ttk.Label(master, textvariable = self.number_max_string, font = self.normal_font) self.number_max_int_label.grid(row = 9, column = 7) self.max_max_label = ttk.Label(master, text = "Median [N]:", font = self.normal_font) self.max_max_label.grid(row = 10, column = 6, sticky=W) self.max_max_int_label = ttk.Label(master, textvariable = self.median_string, font = self.normal_font) self.max_max_int_label.grid(row = 10, column = 7) self.min_max_label = ttk.Label(master, text = u"Weiterreißwiderstand [N/mm]:", font = self.normal_font) self.min_max_label.grid(row = 11, column = 6, sticky=W) self.min_max_int_label = ttk.Label(master, textvariable = self.w_string, font = self.normal_font) self.min_max_int_label.grid(row = 11, column = 7) self.min_max_label = ttk.Label(master, text = u"Spannweite [mm]:", font = self.normal_font) self.min_max_label.grid(row = 12, column = 6, sticky=W) self.min_max_int_label = ttk.Label(master, textvariable = self.distance_string, font = self.normal_font) self.min_max_int_label.grid(row = 12, column = 7) self.method_label = ttk.Label(master, text="Methode:", font = self.normal_font) self.method_label.grid(row = 13, column = 6, sticky=W) self.method_method_label = ttk.Label(master, textvariable = self.method_string, font = self.normal_font) self.method_method_label.grid(row = 13, column = 7) ########################################################################################################## ''' Canvas ''' # Create a canvas self.w, self.h = 800, 500 self.canvas = Canvas(master, width=self.w, height=self.h) self.canvas.grid(row = 0, column = 5, columnspan = 5, rowspan = 9) ''' Funktionen ''' def plot(self): try: #Maxima finden self._max, self._min = self.peakdetect(self.Y, self.X, float(self.delta_x_spinbox.get()), float(self.delta_y_spinbox.get())) #Maxima in Array schreiben self.xm = [p[0] for p in self._max] self.ym = [p[1] for p in self._max] #Maxima verarbeiten self.maxima = self.ym self.maxima_x = self.xm self.number_max = len(self._max) self.number_max_string.set(str(self.number_max)) self.max_max = max(self.ym) self.max_max_string.set(str(self.max_max)) self.min_max = min(self.ym) self.min_max_string.set(str(self.min_max)) #Graph Plotten self.fig = plt.Figure(figsize=(8, 5), dpi=100) self.ax = self.fig.add_subplot(111) self.ax.plot(self.X, self.Y) self.ax.plot(self.xm, self.ym, 'ro', markersize = 10) #self.ax.axvline(x=10, ymin = 0, ymax = 1, linewidth = 2, color = 'g') self.ax.axis('auto') self.ax.set_xlabel('Weg [mm]') self.ax.set_ylabel('Kraft [N]') self.fig_photo = self.draw_figure(self.canvas, self.fig, loc=(0, 0)) #Methode Anzeigen if 1 < self.number_max <= 5 : self.method_string.set('Median') elif self.number_max < 2: self.method_string.set('Maximum') else: self.method_string.set('80% Median') except: tkMessageBox.showwarning('Fehler bei der Berechnung!', 'Bitte Eingaben prüfen.') def calculate(self): if self.sample_thickness_entry.get() == '': tkMessageBox.showwarning('Keine Probendicke eingetragen!', 'Bitte Probendicke zur Berechnung eintragen.') else: if self.number_max <= 5: self.median_calculation() else: self.percent_calculation() def percent_calculation(self): #Berechnung 80 Prozent von #Maxima n = int(round(self.number_max*0.8)) delta = self.number_max - n #Entfernen der ersten und zweiten 10 Prozent del self.maxima[0:int(round(delta/2))] del self.maxima[len(self.maxima)-int(round(delta-int(round(delta/2)))):len(self.maxima)] del self.maxima_x[0:int(round(delta/2))] del self.maxima_x[len(self.maxima_x)-int(round(delta-int(round(delta/2)))):len(self.maxima_x)] #Berechnung des Weiterreisswiderstands try: d = float(self.sample_thickness_entry.get()) #Auslesen der Probendicke self.median = np.median(self.maxima) #Berechnung des Medians self.w = self.median/d self.median_string.set(str(self.median)) self.w_string.set(str(self.w)) #Berechnung der Spannweite self.distance = self.maxima_x[len(self.maxima_x)-1]-self.maxima_x[0] self.distance_string.set(str(self.distance)) except: tkMessageBox.showwarning(u'Probendicke hat falsche Formatierung!', u'Bitte Probendicke in der Form Z.ZZ eingeben (Z=Zahl).') def median_calculation(self): #Berechnung des Weiterreisswiderstands try: d = float(self.sample_thickness_entry.get()) #Auslesen der Probendicke self.median = np.median(self.maxima) #Berechnung des Medians self.w = self.median/d self.median_string.set(str(self.median)) self.w_string.set(str(self.w)) #Berechnung der Spannweite self.distance = self.maxima_x[len(self.maxima_x)-1]-self.maxima_x[0] self.distance_string.set(str(self.distance)) except: tkMessageBox.showwarning(u'Probendicke hat falsche Formatierung!', u'Bitte Probendicke in der Form Z.ZZ eingeben (Z=Zahl).') def save(self): #Speichern der Auswertung im Projekt if self.project_file != '' and self.sample_name_entry.get() != '': maxima_string = '' for maximum in self.maxima: maxima_string += str(maximum)+'\t' print(maxima_string) self.project_file_write = open(self.project_file, 'a') self.project_file_write.write('\n'+self.sample_name_entry.get()+'\t'+str(self.number_max)+'\t'+str(self.median)+'\t'+self.sample_thickness_entry.get()+'\t'+str(self.w)+'\t'+str(self.distance)+'\t'+self.method_string.get()+'\t'+self.comment_entry.get()+'\t'+maxima_string) self.project_file_write.close() elif self.project_file == '': tkMessageBox.showwarning(u'Keine Datei zum Speichern geöffnet!', u'Bitte Datei zum Speichern öffnen oder neue Datei erstellen.') elif self.sample_name_entry.get() == '': tkMessageBox.showwarning(u'Keine Probenname eingetragen!', u'Bitte Probenname eintragen.') def new_file(self): #Neues Projekt erstellen self.project_file = tkFileDialog.asksaveasfilename(**self.file_opt2) self.project_file_write = open(self.project_file, 'a') self.project_file_write.write('Probenname\tNMax\tMedian\tProbendicke\tWeiterreisswiderstand\tSpannweite\tMethode\tKommentar\tMaxima(80%)') self.project_file_write.close() def open_file(self): #Bestehendes Projekt öffnen self.project_file = tkFileDialog.askopenfilename(**self.file_opt3) def get_filepath(self): #Dateipfad von Messung erfragen self.sample_file = tkFileDialog.askopenfilename(**self.file_opt) self.import_data(self.sample_file) def import_data(self, loadfile): #Messung importieren self.X, self.Y = np.loadtxt(loadfile, usecols = (1,0), unpack = True) self.plot() def help(self): #Hilfeseite zeigen top = Toplevel() top.title("Hilfe") label1 = ttk.Label(top, text = u"Projekt öffnen/erstellen", font=self.normal_font) label1.pack() msg1 = Message(top, text=u'Über Datei -> Neu muss zu Beginn eine .txt-Datei erstellt werden. In dieser werden die Ergebnisse der Auswertung gespeichert.\n\nAlternativ kann über Datei -> Öffnen... ein bereits existierendes Projekt mit den neuen Ergebnissen erweitert werden. \n\n') msg1.pack() label2 = ttk.Label(top, text = u"Messung importieren und auswerten", font=self.normal_font) label2.pack() msg2 = Message(top, text=u'Zunächst muss über Datei -> Messung importieren die gewünschte Messung importiert werden.\n\nAnschließend werden Delta X und Delta Y so eingestellt, dass nur die gewünschten Maxima (rote Punkte im Graphen) vom Algorithmus erkannt werden.\n\nZur Berechnung des Weiterreißwiderstandes wird die Probendicke benötigt. Diese muss im entsprechenden Fenster eingetragen werden (Trennung durch . nicht durch , Bsp: 1.75).\n\nÜber die Schaltfläche Berechnen werden die gewünschten Werte berechnet.\n\nNachdem der Probenname und optional ein Kommentar zur Messung in die entsprechenden Fenster eingetragen wurden, lässt sich die Auswertung im zuvor gewählten Projekt abspeichern.') msg2.pack() button = Button(top, text="Verbergen", command=top.destroy) button.pack() def info(self): #Infoseite zeigen top = Toplevel() top.title(u"Über dieses Programm...") msg = Message(top, text=u'Dieses Programm dient zur Auswertung von Messungen für die Bestimmung des Weiterreißwiderstands nach DIN ISO 6133:2004-05\n\nZur Detektion der Maxima dient ein Algorithmus aus MATLAB (http://billauer.co.il/peakdet.html) verwendet, welcher nach Python übersetzt wurden.\n\nDas Programm entscheidet je nach Anzahl der Maxima selbst, welche Vorgabe für die Auswertung zu verwenden ist.\n\n\n\nErstellt von Lukas Scheffler') msg.pack() button = Button(top, text="Verbergen", command=top.destroy) button.pack() def draw_figure(self, canvas, figure, loc=(0, 0)): ''' Draw a matplotlib figure onto a Tk canvas loc: location of top-left corner of figure on canvas in pixels. Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py ''' figure_canvas_agg = FigureCanvasAgg(figure) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = PhotoImage(master=canvas, width=figure_w, height=figure_h) # Position: convert from top-left anchor to center anchor canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo) # Unfortunatly, there's no accessor for the pointer to the native renderer tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) # Return a handle which contains a reference to the photo object # which must be kept live or else the picture disappears return photo def _datacheck_peakdetect(self, x_axis, y_axis): if x_axis is None: x_axis = range(len(y_axis)) if len(y_axis) != len(x_axis): raise (ValueError, 'Input vectors y_axis and x_axis must have same length') #needs to be a numpy array y_axis = np.array(y_axis) x_axis = np.array(x_axis) return x_axis, y_axis def peakdetect(self, y_axis, x_axis = None, lookahead = 300, delta=0): """ Converted from/based on a MATLAB script at: http://billauer.co.il/peakdet.html function for detecting local maximas and minmias in a signal. Discovers peaks by searching for values which are surrounded by lower or larger values for maximas and minimas respectively keyword arguments: y_axis -- A list containg the signal over which to find peaks x_axis -- (optional) A x-axis whose values correspond to the y_axis list and is used in the return to specify the postion of the peaks. If omitted an index of the y_axis is used. (default: None) lookahead -- (optional) distance to look ahead from a peak candidate to determine if it is the actual peak (default: 200) '(sample / period) / f' where '4 >= f >= 1.25' might be a good value delta -- (optional) this specifies a minimum difference between a peak and the following points, before a peak may be considered a peak. Useful to hinder the function from picking up false peaks towards to end of the signal. To work well delta should be set to delta >= RMSnoise * 5. (default: 0) delta function causes a 20% decrease in speed, when omitted Correctly used it can double the speed of the function return -- two lists [max_peaks, min_peaks] containing the positive and negative peaks respectively. Each cell of the lists contains a tupple of: (position, peak_value) to get the average peak value do: np.mean(max_peaks, 0)[1] on the results to unpack one of the lists into x, y coordinates do: x, y = zip(*tab) """ max_peaks = [] min_peaks = [] dump = [] #Used to pop the first hit which almost always is false # check input data x_axis, y_axis = self._datacheck_peakdetect(x_axis, y_axis) # store data length for later use length = len(y_axis) #perform some checks if lookahead < 1: raise ValueError, "Lookahead must be '1' or above in value" if not (np.isscalar(delta) and delta >= 0): raise ValueError, "delta must be a positive number" #maxima and minima candidates are temporarily stored in #mx and mn respectively mn, mx = np.Inf, -np.Inf #Only detect peak if there is 'lookahead' amount of points after it for index, (x, y) in enumerate(zip(x_axis[:-lookahead], y_axis[:-lookahead])): if y > mx: mx = y mxpos = x if y < mn: mn = y mnpos = x ####look for max#### if y < mx-delta and mx != np.Inf: #Maxima peak candidate found #look ahead in signal to ensure that this is a peak and not jitter if y_axis[index:index+lookahead].max() < mx: max_peaks.append([mxpos, mx]) dump.append(True) #set algorithm to only find minima now mx = np.Inf mn = np.Inf if index+lookahead >= length: #end is within lookahead no more peaks can be found break continue #else: #slows shit down this does # mx = ahead # mxpos = x_axis[np.where(y_axis[index:index+lookahead]==mx)] ####look for min#### if y > mn+delta and mn != -np.Inf: #Minima peak candidate found #look ahead in signal to ensure that this is a peak and not jitter if y_axis[index:index+lookahead].min() > mn: min_peaks.append([mnpos, mn]) dump.append(False) #set algorithm to only find maxima now mn = -np.Inf mx = -np.Inf if index+lookahead >= length: #end is within lookahead no more peaks can be found break #else: #slows shit down this does # mn = ahead # mnpos = x_axis[np.where(y_axis[index:index+lookahead]==mn)] #Remove the false hit on the first value of the y_axis try: if dump[0]: max_peaks.pop(0) else: min_peaks.pop(0) del dump except IndexError: #no peaks were found, should the function return empty lists? pass return [max_peaks, min_peaks]
class ConstraintsWindow: constr_types = ['Fix', 'Equality', 'Concentric'] def __init__(self, master=None): self.master = master self.nspheres = 0 master.title('Constraints') self.padWE = dict(padx='0.5mm', pady='0.5mm') self.frame = ttk.Frame(self.master) self.create_widgets() self.configure_widgets() self.frame.grid(row=0, column=0) # binds self.count.trace('w', self.change_count) self.master.bind('<Configure>', self.configure_widgets) self.master.protocol('WM_DELETE_WINDOW', self.hide_window) self.master.bind('<Destroy>', self.hide_window) def create_widgets(self): self.count = StringVar() self.count.set('0') self.lbCount = ttk.Label(self.frame, text='Number of constraints:') self.sbCount = Spinbox(self.frame, from_=0, to=1000, textvariable=self.count, width=10) self.lbType = ttk.Label(self.frame, text='Type') self.lbPrm1 = ttk.Label(self.frame, text='Parameter#1') self.lbPrm2 = ttk.Label(self.frame, text='Parameter#2') self.cbTypes = [] self.cbPrm1s = [] self.cbPrm2s = [] self.btOk = ttk.Button(self.frame, text='Ok', command=self.hide_window) self.btHelp = ttk.Button(self.frame, text='Help', command=self.show_help) def configure_widgets(self, event=None): self.lbCount.grid(row=0, column=0, columnspan=2, **self.padWE) self.sbCount.grid(row=0, column=2, columnspan=2, **self.padWE) self.lbType.grid(row=1, column=0, **self.padWE) self.lbPrm1.grid(row=1, column=1, **self.padWE) self.lbPrm2.grid(row=1, column=2, **self.padWE) n = int(self.count.get()) for i in xrange(n): self.cbTypes[i].grid(row=2 + i, column=0, **self.padWE) self.cbPrm1s[i].grid(row=2 + i, column=1, **self.padWE) self.cbPrm2s[i].grid(row=2 + i, column=2, **self.padWE) self.btOk.pack_forget() self.btOk.grid(row=3 + n, column=0, **self.padWE) self.btHelp.grid(row=3 + n, column=2, **self.padWE) def hide_window(self, event=None): if (event is not None) and (event.widget != self.master): return # skip events from destruction of widgets self.master.withdraw() def show_window(self, nspheres): assert nspheres >= 0 self.nspheres = nspheres print(' Number of spheres passed to Constrains window: %i' % nspheres) self.master.deiconify() def change_count(self, var, blank, mode): n = int(self.count.get()) while len(self.cbTypes) > n: self.cbTypes[-1].destroy() self.cbTypes.pop() self.cbPrm1s[-1].destroy() self.cbPrm1s.pop() self.cbPrm2s[-1].destroy() self.cbPrm2s.pop() while len(self.cbTypes) < n: i = len(self.cbTypes) self.cbTypes.append(ttk.Combobox(self.frame, width=10)) self.cbTypes[i].configure(values=self.constr_types) self.cbTypes[i].bind('<<ComboboxSelected>>', lambda event: self.select_type(event, i)) self.cbPrm1s.append(ttk.Combobox(self.frame, width=10)) self.cbPrm2s.append(ttk.Combobox(self.frame, width=10)) print(self.cbTypes) self.configure_widgets() def select_type(self, event, irow): stype = self.cbTypes[irow].get() prms = ['scale', 'bkg0', 'bkg1', 'bkg2'] for i in xrange(self.nspheres): prms.append('a%i' % i) prms.append('x%i' % i) prms.append('y%i' % i) prms.append('z%i' % i) if stype == 'Fix': self.cbPrm1s[irow].configure(values=prms) self.cbPrm2s[irow].configure(values=[]) elif stype == 'Equality': self.cbPrm1s[irow].configure(values=prms) self.cbPrm2s[irow].configure(values=prms) elif stype == 'Concentric': prms = ['s%i' % i for i in xrange(self.nspheres)] self.cbPrm1s[irow].configure(values=prms) self.cbPrm2s[irow].configure(values=prms) else: raise Exception('Unknonw Constraint: "%s"' % stype) self.cbPrm1s[irow].delete(0, 'end') self.cbPrm2s[irow].delete(0, 'end') def get_constraints_list(self): n = int(self.count.get()) result = [] for i in xrange(n): stype = self.cbTypes[i].get() if stype == 'Fix': p1 = self.cbPrm1s[i].get() print(' %sConstraint(%s)' % (stype, p1)) result.append(FixConstraint(p1)) elif stype == 'Equality': p1 = self.cbPrm1s[i].get() p2 = self.cbPrm2s[i].get() print(' %sConstraint(%s, %s)' % (stype, p1, p2)) result.append(EqualityConstraint(p1, p2)) elif stype == 'Concentric': i1 = int(self.cbPrm1s[i].get()[1:]) i2 = int(self.cbPrm2s[i].get()[1:]) print(' %sConstraint(%i, %i)' % (stype, i1, i2)) result.append(ConcentricConstraint(i1, i2)) else: raise Exception('Unknonw Constraint: "%s"' % stype) return result def show_help(self): tkMessageBox.showinfo( 'Constraints Help', '''Types of constraints *Fix* -- don't vary the parameter during fitting. Can be applied to any parameter. *Equality* -- keep the values of to parameters equal. Can be applied to any parameters pair. *Concentric* -- maintain the centers of two spheres at the same position. This position is still varied. Can be applied to spheres pair only. ''')
class JobParameters(Toplevel): def __init__(self, parent=None, **kwargs): Toplevel.__init__(self, parent) self.title('Job Parameters') self.parent = parent self.main_frame = Frame(self) self.input_directory_gui = DirectorySelector(self.main_frame, 'Input Directory:') self.output_directory_gui = DirectorySelector(self.main_frame, 'Output Directory:', get_default=lambda: self.input_directory_gui.get_directory() + '/output/') self.input_directory_gui.set_notify(self.notify) self.beginning_year = kwargs['beginning_year'] if 'beginning_year' in kwargs else 1950 self.ending_year = kwargs['ending_year'] if 'ending_year' in kwargs else 2100 self.beginning_year_selector = YearSelector(self.main_frame, text="Beginning Year:", min_value=self.beginning_year, max_value=self.ending_year) self.ending_year_selector = YearSelector(self.main_frame, text="Ending Year:", min_value=self.beginning_year, max_value=self.ending_year) self.one_decade_range_var = IntVar() self.one_decade_range = Checkbutton(self.main_frame, text='Calculate 10 Year Range', variable=self.one_decade_range_var, command=self.on_change) self.two_decade_range_var = IntVar() self.two_decade_range = Checkbutton(self.main_frame, text='Calculate 20 Year Range', variable=self.two_decade_range_var, command=self.on_change) self.custom_range_var = IntVar() self.custom_range = Checkbutton(self.main_frame, text='Calculate Custom Year Range', variable=self.custom_range_var, command=self.on_change) self.custom_range_val = StringVar() self.custom_range_input = Spinbox(self.main_frame, from_=30, to=100, textvariable=self.custom_range_val, command=self.on_change, width=5) # Initialize widget values self.beginning_year_selector.set_value(self.beginning_year) self.beginning_year_selector.set_args(check_other_func=self.ending_year_selector.get_less_than) self.ending_year_selector.set_value(self.ending_year) self.ending_year_selector.set_args(check_other_func=self.beginning_year_selector.get_greater_than) self.one_decade_range_var.set(1) self.two_decade_range_var.set(1) self.custom_range_var.set(0) self.custom_range_input.config(state=Tkinter.DISABLED) self.button_frame = Frame(self.main_frame) self.ok_button = Button(self.button_frame, text='OK', command=self.on_submit) self.cancel_button = Button(self.button_frame, text='Cancel', command=self.on_close) self.job_id = kwargs['job_id'] if 'job_id' in kwargs else None self.entry = kwargs['entry'] if 'entry' in kwargs else None self.grab_set() self.resizable(width=False, height=False) def notify(self): self.output_directory_gui.notify() self.lift() def set_grid(self): # Layout child widgets self.main_frame.grid() self.input_directory_gui.set_grid(row=0, padx=6) self.output_directory_gui.set_grid(row=1, padx=6) self.beginning_year_selector.set_grid(row=2, padx=6) self.ending_year_selector.set_grid(row=3, padx=6) self.one_decade_range.grid(row=4, column=1, sticky='w', padx=6) self.two_decade_range.grid(row=5, column=1, sticky='w', padx=6) self.custom_range.grid(row=6, column=1, sticky='w', padx=6) self.custom_range_input.grid(row=6, column=2, sticky='w', padx=6) self.button_frame.grid(row=7, columnspan=3, sticky='nsew') self.ok_button.pack(side=Tkinter.RIGHT) self.cancel_button.pack(side=Tkinter.RIGHT) #self.ok_button.grid(row=7, column=1, pady=2) #self.cancel_button.grid(row=7, column=2, pady=2) def on_change(self): is_custom_range_checked = self.custom_range_var.get() == 1 if is_custom_range_checked: self.custom_range_input.config(state=Tkinter.NORMAL) else: self.custom_range_input.config(state=Tkinter.DISABLED) def on_submit(self): if self.input_directory_gui.get_directory() == '' or self.output_directory_gui.get_directory() == '': self.on_close() return # The job parameters are extracted from the GUI here and passed to the processing thread to run the requisite job. job = dict() job['job_id'] = self.job_id job['delimiter'] = '.' job['individual_files'] = False job['input_directory'] = self.input_directory_gui.get_directory() job['output_directory'] = self.output_directory_gui.get_directory() job['start'] = self.beginning_year_selector.get_value() job['end'] = self.ending_year_selector.get_value() job['calculate_one_decade'] = self.one_decade_range_var.get() == 1 job['calculate_two_decade'] = self.two_decade_range_var.get() == 1 job['calculate_custom_range'] = self.custom_range_var.get() == 1 job['custom_range'] = int(self.custom_range_val.get()) job['log'] = True if self.entry != None: self.entry.add_job(job) self.on_close() def on_close(self): if self.parent != None: self.parent.focus_set() self.withdraw() self.destroy() def on_focus(self): self.focus_force()
def initUI(self): self.parent.title("FIND BLR COEFFICIENT VALUE") self.pack(fill=BOTH, expand=True) self.columnconfigure(0, weight=1) # self.rowconfigure(0, weight=1) # weight attibute is used to make them growable ###### GUI Control Variables ###### self.LIMIT_L = IntVar() self.LIMIT_H = IntVar() self.PULSE_R = IntVar() self.PULSE_L = IntVar() self.pulse_height = DoubleVar() self.hdf5_file = StringVar() self.PMT = IntVar() self.EVENT = IntVar() self.amplitude_range = DoubleVar() self.delta = DoubleVar() self.noise_sigma = DoubleVar() self.coeff = DoubleVar() #self.DRAW = BooleanVar() search = Image.open("next_logo.jpg") search_temp = search.resize((170, 200), Image.ANTIALIAS) search_aux = ImageTk.PhotoImage(search_temp) label1 = Label(self, image=search_aux) label1.image = search_aux label1.grid(row=0, column=0, columnspan=10, rowspan=10, sticky=E + W + S + N) self.hdf5_file.set("2052.h5.z") e1 = Entry(self, textvariable=self.hdf5_file, width=30) e1.grid(row=1, column=1, sticky=W, columnspan=5, pady=5) e1_label = Label(self, text="HDF5 file") e1_label.grid(row=0, column=1, sticky=W, columnspan=5, pady=5) self.PMT.set("0") sb1 = Spinbox(self, from_=0, to=12, width=3, textvariable=self.PMT) sb1.grid(row=3, column=2, sticky=W) sb1_label = Label(self, text="PMT") sb1_label.grid(row=2, column=2, padx=0, sticky=W) self.EVENT.set("0") sb1 = Spinbox(self, from_=0, to=1000, width=5, textvariable=self.EVENT) sb1.grid(row=3, column=3, sticky=W) sb1_label = Label(self, text="EVENT") sb1_label.grid(row=2, column=3, padx=0, sticky=W) self.LIMIT_L.set("19000") sb1 = Spinbox(self, from_=0, to=100000, width=5, textvariable=self.LIMIT_L) sb1.grid(row=5, column=2, sticky=W) sb1_label = Label(self, text="ROI Start ") sb1_label.grid(row=4, column=2, padx=0, sticky=W) self.LIMIT_H.set("22500") sb1 = Spinbox(self, from_=0, to=100000, width=5, textvariable=self.LIMIT_H) sb1.grid(row=5, column=3, sticky=W) sb1_label = Label(self, text="ROI End ") sb1_label.grid(row=4, column=3, padx=0, sticky=W) self.PULSE_R.set("20142") sb1 = Spinbox(self, from_=0, to=100000, width=8, textvariable=self.PULSE_R) sb1.grid(row=5, column=4, sticky=E) sb1_label = Label(self, text=" Pulse Rise") sb1_label.grid(row=4, column=4, padx=0, sticky=E) self.PULSE_L.set("1200") sb1 = Spinbox(self, from_=0, to=5000, width=8, textvariable=self.PULSE_L) sb1.grid(row=5, column=5, sticky=E) sb1_label = Label(self, text=" Pulse Length") sb1_label.grid(row=4, column=5, padx=0, sticky=E) sb1_label = Label(self, text=" ") sb1_label.grid(row=2, column=7, padx=0, sticky=W) sb1_label = Label(self, text=" ") sb1_label.grid(row=6, column=7, padx=0, sticky=W) self.pulse_height.set("545.5") sb1 = Entry(self, width=8, textvariable=self.pulse_height) sb1.grid(row=7, column=3, sticky=E) sb1_label = Label(self, text=" Amplitude") sb1_label.grid(row=6, column=3, padx=0, sticky=E) self.amplitude_range.set("2") sb1 = Entry(self, width=8, textvariable=self.amplitude_range) sb1.grid(row=7, column=4, sticky=E) sb1_label = Label(self, text=" Loop Range") sb1_label.grid(row=6, column=4, padx=0, sticky=E) self.delta.set("0.1") sb1 = Entry(self, width=8, textvariable=self.delta) sb1.grid(row=7, column=5, sticky=E) sb1_label = Label(self, text=" Loop Delta") sb1_label.grid(row=6, column=5, padx=0, sticky=E) self.noise_sigma.set("4") sb1 = Entry(self, width=3, textvariable=self.noise_sigma) sb1.grid(row=5, column=6, sticky=E) sb1_label = Label(self, text=" Noise Threshold") sb1_label.grid(row=4, column=6, padx=0, sticky=E) sb_coeff_label = Label(self, text="Coefficient ") sb_coeff_label.grid(row=0, column=6, padx=0, sticky=E) self.sb_coeff = Label(self) self.sb_coeff.grid(row=1, column=6, padx=0, sticky=E) # MAIN BUTTONS obtn = Button(self, text="GO!!", command=self.find_C) obtn.grid(row=14, column=4, sticky=E, pady=10) cbtn = Button(self, text="Quit", command=self.quit) cbtn.grid(row=14, column=5, sticky=E, pady=10) hbtn = Button(self, text="Help", command=self.help_f) hbtn.grid(row=14, column=0, sticky=W, pady=10)
class MoveControl(LabelFrame): def __init__(self, root, prtr, settings, log, *arg): fn = os.path.join(settings.cmdFolder, "images", "control_xyz.png") self.image = Image.open(fn) self.photo = ImageTk.PhotoImage(self.image) LabelFrame.__init__(self, root, *arg, text="Movement") self.app = root self.hilite = None self.hilitemask = None self.settings = settings self.printer = prtr self.log = log l = Label(self, text="mm/min") l.grid(row=1, column=2) l = Label(self, text="X/Y Feed Rate:") l.grid(row=2, column=1, sticky=E) self.xyfeed = Spinbox(self, width=10, justify=RIGHT, from_=0, to=MAXFEED) self.xyfeed.grid(row=2, column=2) self.xyfeed.delete(0, END) self.xyfeed.insert(0, settings.xyfeed) self.xyfeed.bind("<FocusOut>", self.valxyFeed) self.xyfeed.bind("<Leave>", self.valxyFeed) l = Label(self, text="Z Feed Rate:") l.grid(row=3, column=1, sticky=E) self.zfeed = Spinbox(self, width=10, justify=RIGHT, from_=0, to=MAXFEED) self.zfeed.grid(row=3, column=2) self.zfeed.delete(0, END) self.zfeed.insert(0, settings.zfeed) self.zfeed.bind("<FocusOut>", self.valzFeed) self.zfeed.bind("<Leave>", self.valzFeed) self.canvas = Canvas(self, width=self.image.size[0], height=self.image.size[1], *arg) self.canvas.create_image((0, 0), image=self.photo, anchor=N+W) self.canvas.grid(row=4, column=1, columnspan=2) for m in imageMasks: self.canvas.create_oval((m[0][0]-mask_rad, m[0][1]-mask_rad, m[0][0]+mask_rad, m[0][1]+mask_rad), outline="#FF0000", width=4, tags=m[1], state=HIDDEN) self.canvas.bind("<Button-1>", self.OnLeftDown) self.canvas.bind("<Motion>", self.OnMotion) self.canvas.bind("<Enter>", self.OnEnter) self.canvas.bind("<Leave>", self.OnLeave) self.bAllOff = Button(self, text="Release Motors", command=self.allMotorsOff) self.bAllOff.grid(row=5, column=1, columnspan=2) def valxyFeed(self, *arg): x = self.validFeed(self.xyfeed.get(), 'XY') if x == None: self.xyfeed.delete(0, END) self.xyfeed.insert(0, "%d" % self.settings.xyfeed) return True if self.settings.xyfeed != x: self.settings.xyfeed = x self.settings.setModified() return True def valzFeed(self, *arg): x = self.validFeed(self.zfeed.get(), 'Z') if x == None: self.zfeed.delete(0, END) self.zfeed.insert(0, "%d" % self.settings.zfeed) return True if self.settings.zfeed != x: self.settings.zfeed = x self.settings.setModified() return True def validFeed(self, fv, axis): try: x = int(fv) except: self.log.logMsg("Value for %s feed rate not a valid integer" % axis) return None if x <=0 or x >MAXFEED: self.log.logMsg("Value for %s feed rate out of range(0-5000)" % axis) return None return x def allMotorsOff(self): if self.app.printerAvailable(cmd="M84"): self.printer.send_now("M84") def OnMotion(self, e): for i in range(len(imageGeometry)): if boundBy((e.x, e.y), imageGeometry[i][0]): self.setHilite(i) return if self.hilite != None: self.clearHilite() def OnEnter(self, e): self.clearHilite() def OnLeave(self, e): self.clearHilite() def setHilite(self, i): if i != self.hilite: self.canvas.delete("HILITE") self.canvas.create_rectangle(imageGeometry[i][0], outline="#C85E5D", width=3, fill="gray", stipple="gray50", tags="HILITE") self.hilite = i if self.hilitemask: self.canvas.itemconfig(self.hilitemask, state=HIDDEN) if imageGeometry[i][2]: self.hilitemask = imageGeometry[i][2] self.canvas.itemconfig(self.hilitemask, state=NORMAL) def clearHilite(self): self.canvas.delete("HILITE") self.hilite = None self.hilitemask = None for m in imageMasks: self.canvas.itemconfig(m[1], state=HIDDEN) def OnLeftDown(self, e): if self.app.printerAvailable(cmd="G1"): for g in imageGeometry: if boundBy((e.x, e.y), g[0]): if "G1" in g[1]: if "X" in g[1]: feed = self.settings.xyfeed elif "Y" in g[1]: feed = self.settings.xyfeed elif "Z" in g[1]: feed = self.settings.zfeed else: feed = 100 self.printer.send_now("G91") self.printer.send_now(g[1] + " F" + str(feed)) self.printer.send_now("G90") else: self.printer.send_now(g[1]) break
def __init__(self, master=None): """ Constructor """ Frame.__init__(self, master, name='pvApplication', bg='black', padx=5, pady=5) # set black background, pad sides with 15 points, top/bottom 5 points # fill=BOTH fills in padding with background color # w/o fill=BOTH padding is default color # side=TOP is the default self.pack(fill=BOTH) master.resizable(False, False) # not resizable in x or y master.title(PVAPP_TXT) # set title bar of master (a.k.a. root) master.protocol("WM_DELETE_WINDOW", self._quit) # close window to quit self.validationConstants = self.readJSON('validationConstants') self.messagetext = self.readJSON('messagetext' + '.' + LANGUAGE) MAX_STRINGS = self.validationConstants["pvapplication"]["numStrs"] MAX_MODULES = self.validationConstants["pvapplication"]["numMods"] MAX_SUNS = self.validationConstants["pvapplication"]["sysEe"] CAPTION_FONT = nametofont('TkCaptionFont') # font for titles # PVsystem pvSys = self.pvSys = PVsystem() # variables numStrs = self.numStrs = IntVar(self, NUMBERSTRS, 'numStrs') numMods = self.numMods = IntVar(self, NUMBERMODS, 'numMods') numCells = self.numCells = IntVar(self, NUMBERCELLS, 'numCells') txtIsys = self.txtIsys = DoubleVar(self, name='txtIsys') txtVsys = self.txtVsys = DoubleVar(self, name='txtVsys') txtPsys = self.txtPsys = DoubleVar(self, name='txtPsys') txtImp = self.txtImp = StringVar(self, name='txtImp') txtVmp = self.txtVmp = StringVar(self, name='txtVmp') txtPmp = self.txtPmp = StringVar(self, name='txtPmp') txtIsc = self.txtIsc = StringVar(self, name='txtIsc') txtVoc = self.txtVoc = StringVar(self, name='txtVoc') txtFF = self.txtFF = StringVar(self, name='txtFF') txtEff = self.txtEff = StringVar(self, name='txtEff') sysEe = self.sysEe = DoubleVar(self, 1, name='sysEe') txtImp.set("{:7.3f}".format(self.pvSys.Imp)) # [A] txtVmp.set("{:7.3f}".format(self.pvSys.Vmp)) # [V] txtPmp.set("{:7.3f}".format(self.pvSys.Pmp / 1000)) # [kW] txtIsc.set("{:7.3f}".format(self.pvSys.Isc)) # [A] txtVoc.set("{:7.3f}".format(self.pvSys.Voc)) # [V] txtFF.set("{:7.3f}".format(self.pvSys.FF * 100)) # [%] txtEff.set("{:7.3f}".format(self.pvSys.eff * 100)) # [%] self.msgtext = StringVar(self, READY_MSG, 'msgtext') # must register vcmd and invcmd as Tcl functions vcmd = (self.register(self.validateWidget), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') invcmd = (self.register(self.invalidWidget), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') # SP logo # convert image to tk-compatible format (.gif, .pgm, or .ppm) self.SPlogo = ImageTk.PhotoImage(Image.open(SPLOGO)) # bg='black' fills extra space with black # anchor=W aligns photoimage on left side, NW is no different # padding is ignored by images, use borderwidth Label(self, image=self.SPlogo, borderwidth=5, bg='black', anchor=W).pack(fill=BOTH) # fill=BOTH expands the photoimage to fill parent frame # w/o fill=BOTH photoimage is centered in frame even with anchor=W # Intro text introText = 'PVmismatch calculates I-V and P-V curves as well as the' introText += ' max power point (MPP) for any sized system.\nSet the' introText += ' number of strings in the system, the number of modules' introText += ' per string and the number cells per module.' # anchor=W aligns message on left side, NW is no different # fg='white' sets text color to white, default is black, so it doesn't # show on black background # default aspect is 150%, about as wide as high, or set width>0 Message(self, text=introText, width=750, bg='black', fg='white', anchor=W).pack(fill=BOTH) # fill=BOTH expands the message to fill parent frame # w/o fill=BOTH message is centered in frame even with anchor=W # PVsystem frame pvSysFrame = self.pvSysFrame = Frame(master, name='pvSysFrame') # fill=BOTH keeps widgets in frame on left when window is resized pvSysFrame.pack(fill=BOTH) # PVsystem matplotlib figure canvas self.pvSysPlotFrame = Frame(pvSysFrame, name='pvSysPlotFrame') pvSysPlotFrame = self.pvSysPlotFrame pvSysPlotFrame.pack(side=RIGHT) pvSysPlot = self.pvSysPlot = pvSys.plotSys() self.pvSysFigCanvas = FigureCanvasTkAgg(pvSysPlot, master=pvSysPlotFrame, resize_callback=None) pvSysFigCanvas = self.pvSysFigCanvas pvSysFigCanvas.get_tk_widget()._name = 'pvSysFigCanvas' # IGNORE:W0212 pvSysFigCanvas.show() # NB: FigureCanvasTkAgg._tkcanvas is FigureCanvasTkAgg.get_tk_widget() pvSysFigCanvas.get_tk_widget().pack(fill=BOTH) pvSysToolbar = NavigationToolbar2TkAgg(pvSysFigCanvas, pvSysPlotFrame) pvSysToolbar.update() pvSysToolbar.pack(fill=BOTH) # PVsystem data frame pvSysDataFrame = self.pvSysDataFrame = Frame(pvSysFrame, name='pvSysDataFrame') pvSysDataFrame.pack(side=LEFT) _row = 0 Label(pvSysDataFrame, text='PVsystem', font=CAPTION_FONT).grid(row=_row, columnspan=3, sticky=W) # number of strings _row += 1 # row 1 Label(pvSysDataFrame, text='Number of Strings').grid(row=_row, columnspan=2, sticky=W) # use textVar to set number of strings from LOAD, RESET or default spinboxCnf = { 'name': 'numStrSpinbox', 'from_': 1, 'to': MAX_STRINGS, 'textvariable': numStrs, 'width': 5, 'validate': 'all', 'validatecommand': vcmd, 'invalidcommand': invcmd, 'command': self.updatePVsys } self.numStrSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf) self.numStrSpinbox.bind("<Return>", self.keyBinding) self.numStrSpinbox.grid(row=_row, column=2) # number of modules _row += 1 # row 2 Label(pvSysDataFrame, text='Number of Modules').grid(row=_row, columnspan=2, sticky=W) # number of modules spinbox spinboxCnf = { 'name': 'numModSpinbox', 'from_': 1, 'to': MAX_MODULES, 'textvariable': numMods, 'width': 5, 'validate': 'all', 'validatecommand': vcmd, 'invalidcommand': invcmd, 'command': self.updatePVsys } self.numModSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf) self.numModSpinbox.bind("<Return>", self.keyBinding) self.numModSpinbox.grid(row=_row, column=2) # number of cells _row += 1 # row 3 Label(pvSysDataFrame, text='Number of Cells').grid(row=_row, columnspan=2, sticky=W) # http://www.logilab.org/card/pylintfeatures#basic-checker # pylint: disable = W0142 self.numCellOption = OptionMenu(pvSysDataFrame, numCells, *MODSIZES, command=self.updatePVsys) # pylint: enable = W0142 self.numCellOption._name = 'numCellOption' # IGNORE:W0212 self.numCellOption.grid(row=_row, column=2) # Advanced Configuration button _row += 1 # row 14 buttonCnf = { 'name': 'advCnfButton', 'text': 'Advanced Configuration', 'command': self.startAdvCnf_tk } pvStrButton = self.pvStrButton = Button(pvSysDataFrame, buttonCnf) pvStrButton.grid(row=_row, columnspan=3, sticky=(E + W)) # slider to explore IV curves _row += 1 # row 4, 5 & 6 self.pvSysScale = Scale(pvSysDataFrame, orient=HORIZONTAL, label='I-V Curve', font=CAPTION_FONT, command=self.getIV, showvalue=False, from_=0, to=(pvSys.pvconst.npts - 1)) self.pvSysScale.grid(row=_row, columnspan=3, sticky=(E + W)) # Isys Label(pvSysDataFrame, text='Isys [A]').grid(row=(_row + 1)) self.pvIsys = Entry(pvSysDataFrame, textvariable=txtIsys, width=7) self.pvIsys.grid(row=(_row + 2)) # Vsys Label(pvSysDataFrame, text='Vsys [V]').grid(row=(_row + 1), column=1) self.pvVsys = Entry(pvSysDataFrame, textvariable=txtVsys, width=7) self.pvVsys.grid(row=(_row + 2), column=1) # Psys Label(pvSysDataFrame, text='Psys [kW]').grid(row=(_row + 1), column=2) self.pvPsys = Entry(pvSysDataFrame, textvariable=txtPsys, width=7) self.pvPsys.grid(row=(_row + 2), column=2) # Imp, Vmp & Pmp _row += 3 # row 7, 8, 9, 10, 11 & 12 Label(pvSysDataFrame, text='I-V Characteristics', font=CAPTION_FONT).grid(row=_row, columnspan=3, sticky=W) Label(pvSysDataFrame, text='Imp [A]').grid(row=(_row + 1)) Label(pvSysDataFrame, text='Vmp [V]').grid(row=(_row + 1), column=1) Label(pvSysDataFrame, text='Pmp [kW]').grid(row=(_row + 1), column=2) self.pvImp = Entry(pvSysDataFrame, textvariable=txtImp, width=7, state='readonly') self.pvImp.grid(row=(_row + 2)) self.pvVmp = Entry(pvSysDataFrame, textvariable=txtVmp, width=7, state='readonly') self.pvVmp.grid(row=(_row + 2), column=1) self.pvPmp = Entry(pvSysDataFrame, textvariable=txtPmp, width=7, state='readonly') self.pvPmp.grid(row=(_row + 2), column=2) # Isc, Voc & FF Label(pvSysDataFrame, text='Isc [A]').grid(row=(_row + 3)) Label(pvSysDataFrame, text='Voc [V]').grid(row=(_row + 3), column=1) Label(pvSysDataFrame, text='FF [%]').grid(row=(_row + 3), column=2) self.pvIsc = Entry(pvSysDataFrame, textvariable=txtIsc, width=7, state='readonly') self.pvIsc.grid(row=(_row + 4)) self.pvVoc = Entry(pvSysDataFrame, textvariable=txtVoc, width=7, state='readonly') self.pvVoc.grid(row=(_row + 4), column=1) self.pvFF = Entry(pvSysDataFrame, textvariable=txtFF, width=7, state='readonly') self.pvFF.grid(row=(_row + 4), column=2) Label(pvSysDataFrame, text='Efficiency [%]').grid(row=(_row + 5), columnspan=2) self.pvEff = Entry(pvSysDataFrame, textvariable=txtEff, width=7, state='readonly') self.pvEff.grid(row=(_row + 5), column=2) # set suns _row += 6 # row 13 Label(pvSysDataFrame, text='Irradiance [suns]', font=CAPTION_FONT).grid(row=_row, columnspan=2, sticky=W) # number of modules spinbox spinboxCnf = { 'name': 'sunSpinbox', 'from_': 0.2, 'to': MAX_SUNS, 'increment': 0.1, 'textvariable': sysEe, 'width': 5, 'validate': 'all', 'validatecommand': vcmd, 'invalidcommand': invcmd, 'command': self.updatePVsys } self.sunSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf) self.sunSpinbox.bind("<Return>", self.keyBinding) self.sunSpinbox.grid(row=_row, column=2) # PVstring button _row += 1 # row 14 buttonCnf = { 'name': 'pvStrButton', 'text': 'PVstring', 'command': self.startPVstring_tk } pvStrButton = self.pvStrButton = Button(pvSysDataFrame, buttonCnf) pvStrButton.grid(row=_row, columnspan=3, sticky=(E + W)) # toolbar toolbar = self.toolbarframe = Frame(master, name='toolbar') toolbar.pack(fill=BOTH) self.QUIT = Button(toolbar, text='Quit', command=self._quit) self.QUIT.pack(side=RIGHT) self.SAVE = Button(toolbar, text='Save', command=self._save) self.SAVE.pack(side=RIGHT) self.LOAD = Button(toolbar, text='Load', command=self._load) self.LOAD.pack(side=RIGHT) self.RESET = Button(toolbar, text='Reset', command=self._reset) self.RESET.pack(side=RIGHT) self.UPDATE = Button(toolbar, text='Update', command=self._update) self.UPDATE.pack(side=RIGHT) self.HELP = Button(toolbar, text='Help', command=self._help) self.HELP.pack(side=RIGHT) self.MESSAGE = Message(toolbar, textvariable=self.msgtext, width=500, fg='red') self.MESSAGE.pack(side=LEFT)
class PVapplicaton(Frame): """ classdocs """ def __init__(self, master=None): """ Constructor """ Frame.__init__(self, master, name='pvApplication', bg='black', padx=5, pady=5) # set black background, pad sides with 15 points, top/bottom 5 points # fill=BOTH fills in padding with background color # w/o fill=BOTH padding is default color # side=TOP is the default self.pack(fill=BOTH) master.resizable(False, False) # not resizable in x or y master.title(PVAPP_TXT) # set title bar of master (a.k.a. root) master.protocol("WM_DELETE_WINDOW", self._quit) # close window to quit self.validationConstants = self.readJSON('validationConstants') self.messagetext = self.readJSON('messagetext' + '.' + LANGUAGE) MAX_STRINGS = self.validationConstants["pvapplication"]["numStrs"] MAX_MODULES = self.validationConstants["pvapplication"]["numMods"] MAX_SUNS = self.validationConstants["pvapplication"]["sysEe"] CAPTION_FONT = nametofont('TkCaptionFont') # font for titles # PVsystem pvSys = self.pvSys = PVsystem() # variables numStrs = self.numStrs = IntVar(self, NUMBERSTRS, 'numStrs') numMods = self.numMods = IntVar(self, NUMBERMODS, 'numMods') numCells = self.numCells = IntVar(self, NUMBERCELLS, 'numCells') txtIsys = self.txtIsys = DoubleVar(self, name='txtIsys') txtVsys = self.txtVsys = DoubleVar(self, name='txtVsys') txtPsys = self.txtPsys = DoubleVar(self, name='txtPsys') txtImp = self.txtImp = StringVar(self, name='txtImp') txtVmp = self.txtVmp = StringVar(self, name='txtVmp') txtPmp = self.txtPmp = StringVar(self, name='txtPmp') txtIsc = self.txtIsc = StringVar(self, name='txtIsc') txtVoc = self.txtVoc = StringVar(self, name='txtVoc') txtFF = self.txtFF = StringVar(self, name='txtFF') txtEff = self.txtEff = StringVar(self, name='txtEff') sysEe = self.sysEe = DoubleVar(self, 1, name='sysEe') txtImp.set("{:7.3f}".format(self.pvSys.Imp)) # [A] txtVmp.set("{:7.3f}".format(self.pvSys.Vmp)) # [V] txtPmp.set("{:7.3f}".format(self.pvSys.Pmp / 1000)) # [kW] txtIsc.set("{:7.3f}".format(self.pvSys.Isc)) # [A] txtVoc.set("{:7.3f}".format(self.pvSys.Voc)) # [V] txtFF.set("{:7.3f}".format(self.pvSys.FF * 100)) # [%] txtEff.set("{:7.3f}".format(self.pvSys.eff * 100)) # [%] self.msgtext = StringVar(self, READY_MSG, 'msgtext') # must register vcmd and invcmd as Tcl functions vcmd = (self.register(self.validateWidget), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') invcmd = (self.register(self.invalidWidget), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') # SP logo # convert image to tk-compatible format (.gif, .pgm, or .ppm) self.SPlogo = ImageTk.PhotoImage(Image.open(SPLOGO)) # bg='black' fills extra space with black # anchor=W aligns photoimage on left side, NW is no different # padding is ignored by images, use borderwidth Label(self, image=self.SPlogo, borderwidth=5, bg='black', anchor=W).pack(fill=BOTH) # fill=BOTH expands the photoimage to fill parent frame # w/o fill=BOTH photoimage is centered in frame even with anchor=W # Intro text introText = 'PVmismatch calculates I-V and P-V curves as well as the' introText += ' max power point (MPP) for any sized system.\nSet the' introText += ' number of strings in the system, the number of modules' introText += ' per string and the number cells per module.' # anchor=W aligns message on left side, NW is no different # fg='white' sets text color to white, default is black, so it doesn't # show on black background # default aspect is 150%, about as wide as high, or set width>0 Message(self, text=introText, width=750, bg='black', fg='white', anchor=W).pack(fill=BOTH) # fill=BOTH expands the message to fill parent frame # w/o fill=BOTH message is centered in frame even with anchor=W # PVsystem frame pvSysFrame = self.pvSysFrame = Frame(master, name='pvSysFrame') # fill=BOTH keeps widgets in frame on left when window is resized pvSysFrame.pack(fill=BOTH) # PVsystem matplotlib figure canvas self.pvSysPlotFrame = Frame(pvSysFrame, name='pvSysPlotFrame') pvSysPlotFrame = self.pvSysPlotFrame pvSysPlotFrame.pack(side=RIGHT) pvSysPlot = self.pvSysPlot = pvSys.plotSys() self.pvSysFigCanvas = FigureCanvasTkAgg(pvSysPlot, master=pvSysPlotFrame, resize_callback=None) pvSysFigCanvas = self.pvSysFigCanvas pvSysFigCanvas.get_tk_widget()._name = 'pvSysFigCanvas' # IGNORE:W0212 pvSysFigCanvas.show() # NB: FigureCanvasTkAgg._tkcanvas is FigureCanvasTkAgg.get_tk_widget() pvSysFigCanvas.get_tk_widget().pack(fill=BOTH) pvSysToolbar = NavigationToolbar2TkAgg(pvSysFigCanvas, pvSysPlotFrame) pvSysToolbar.update() pvSysToolbar.pack(fill=BOTH) # PVsystem data frame pvSysDataFrame = self.pvSysDataFrame = Frame(pvSysFrame, name='pvSysDataFrame') pvSysDataFrame.pack(side=LEFT) _row = 0 Label(pvSysDataFrame, text='PVsystem', font=CAPTION_FONT).grid(row=_row, columnspan=3, sticky=W) # number of strings _row += 1 # row 1 Label(pvSysDataFrame, text='Number of Strings').grid(row=_row, columnspan=2, sticky=W) # use textVar to set number of strings from LOAD, RESET or default spinboxCnf = { 'name': 'numStrSpinbox', 'from_': 1, 'to': MAX_STRINGS, 'textvariable': numStrs, 'width': 5, 'validate': 'all', 'validatecommand': vcmd, 'invalidcommand': invcmd, 'command': self.updatePVsys } self.numStrSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf) self.numStrSpinbox.bind("<Return>", self.keyBinding) self.numStrSpinbox.grid(row=_row, column=2) # number of modules _row += 1 # row 2 Label(pvSysDataFrame, text='Number of Modules').grid(row=_row, columnspan=2, sticky=W) # number of modules spinbox spinboxCnf = { 'name': 'numModSpinbox', 'from_': 1, 'to': MAX_MODULES, 'textvariable': numMods, 'width': 5, 'validate': 'all', 'validatecommand': vcmd, 'invalidcommand': invcmd, 'command': self.updatePVsys } self.numModSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf) self.numModSpinbox.bind("<Return>", self.keyBinding) self.numModSpinbox.grid(row=_row, column=2) # number of cells _row += 1 # row 3 Label(pvSysDataFrame, text='Number of Cells').grid(row=_row, columnspan=2, sticky=W) # http://www.logilab.org/card/pylintfeatures#basic-checker # pylint: disable = W0142 self.numCellOption = OptionMenu(pvSysDataFrame, numCells, *MODSIZES, command=self.updatePVsys) # pylint: enable = W0142 self.numCellOption._name = 'numCellOption' # IGNORE:W0212 self.numCellOption.grid(row=_row, column=2) # Advanced Configuration button _row += 1 # row 14 buttonCnf = { 'name': 'advCnfButton', 'text': 'Advanced Configuration', 'command': self.startAdvCnf_tk } pvStrButton = self.pvStrButton = Button(pvSysDataFrame, buttonCnf) pvStrButton.grid(row=_row, columnspan=3, sticky=(E + W)) # slider to explore IV curves _row += 1 # row 4, 5 & 6 self.pvSysScale = Scale(pvSysDataFrame, orient=HORIZONTAL, label='I-V Curve', font=CAPTION_FONT, command=self.getIV, showvalue=False, from_=0, to=(pvSys.pvconst.npts - 1)) self.pvSysScale.grid(row=_row, columnspan=3, sticky=(E + W)) # Isys Label(pvSysDataFrame, text='Isys [A]').grid(row=(_row + 1)) self.pvIsys = Entry(pvSysDataFrame, textvariable=txtIsys, width=7) self.pvIsys.grid(row=(_row + 2)) # Vsys Label(pvSysDataFrame, text='Vsys [V]').grid(row=(_row + 1), column=1) self.pvVsys = Entry(pvSysDataFrame, textvariable=txtVsys, width=7) self.pvVsys.grid(row=(_row + 2), column=1) # Psys Label(pvSysDataFrame, text='Psys [kW]').grid(row=(_row + 1), column=2) self.pvPsys = Entry(pvSysDataFrame, textvariable=txtPsys, width=7) self.pvPsys.grid(row=(_row + 2), column=2) # Imp, Vmp & Pmp _row += 3 # row 7, 8, 9, 10, 11 & 12 Label(pvSysDataFrame, text='I-V Characteristics', font=CAPTION_FONT).grid(row=_row, columnspan=3, sticky=W) Label(pvSysDataFrame, text='Imp [A]').grid(row=(_row + 1)) Label(pvSysDataFrame, text='Vmp [V]').grid(row=(_row + 1), column=1) Label(pvSysDataFrame, text='Pmp [kW]').grid(row=(_row + 1), column=2) self.pvImp = Entry(pvSysDataFrame, textvariable=txtImp, width=7, state='readonly') self.pvImp.grid(row=(_row + 2)) self.pvVmp = Entry(pvSysDataFrame, textvariable=txtVmp, width=7, state='readonly') self.pvVmp.grid(row=(_row + 2), column=1) self.pvPmp = Entry(pvSysDataFrame, textvariable=txtPmp, width=7, state='readonly') self.pvPmp.grid(row=(_row + 2), column=2) # Isc, Voc & FF Label(pvSysDataFrame, text='Isc [A]').grid(row=(_row + 3)) Label(pvSysDataFrame, text='Voc [V]').grid(row=(_row + 3), column=1) Label(pvSysDataFrame, text='FF [%]').grid(row=(_row + 3), column=2) self.pvIsc = Entry(pvSysDataFrame, textvariable=txtIsc, width=7, state='readonly') self.pvIsc.grid(row=(_row + 4)) self.pvVoc = Entry(pvSysDataFrame, textvariable=txtVoc, width=7, state='readonly') self.pvVoc.grid(row=(_row + 4), column=1) self.pvFF = Entry(pvSysDataFrame, textvariable=txtFF, width=7, state='readonly') self.pvFF.grid(row=(_row + 4), column=2) Label(pvSysDataFrame, text='Efficiency [%]').grid(row=(_row + 5), columnspan=2) self.pvEff = Entry(pvSysDataFrame, textvariable=txtEff, width=7, state='readonly') self.pvEff.grid(row=(_row + 5), column=2) # set suns _row += 6 # row 13 Label(pvSysDataFrame, text='Irradiance [suns]', font=CAPTION_FONT).grid(row=_row, columnspan=2, sticky=W) # number of modules spinbox spinboxCnf = { 'name': 'sunSpinbox', 'from_': 0.2, 'to': MAX_SUNS, 'increment': 0.1, 'textvariable': sysEe, 'width': 5, 'validate': 'all', 'validatecommand': vcmd, 'invalidcommand': invcmd, 'command': self.updatePVsys } self.sunSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf) self.sunSpinbox.bind("<Return>", self.keyBinding) self.sunSpinbox.grid(row=_row, column=2) # PVstring button _row += 1 # row 14 buttonCnf = { 'name': 'pvStrButton', 'text': 'PVstring', 'command': self.startPVstring_tk } pvStrButton = self.pvStrButton = Button(pvSysDataFrame, buttonCnf) pvStrButton.grid(row=_row, columnspan=3, sticky=(E + W)) # toolbar toolbar = self.toolbarframe = Frame(master, name='toolbar') toolbar.pack(fill=BOTH) self.QUIT = Button(toolbar, text='Quit', command=self._quit) self.QUIT.pack(side=RIGHT) self.SAVE = Button(toolbar, text='Save', command=self._save) self.SAVE.pack(side=RIGHT) self.LOAD = Button(toolbar, text='Load', command=self._load) self.LOAD.pack(side=RIGHT) self.RESET = Button(toolbar, text='Reset', command=self._reset) self.RESET.pack(side=RIGHT) self.UPDATE = Button(toolbar, text='Update', command=self._update) self.UPDATE.pack(side=RIGHT) self.HELP = Button(toolbar, text='Help', command=self._help) self.HELP.pack(side=RIGHT) self.MESSAGE = Message(toolbar, textvariable=self.msgtext, width=500, fg='red') self.MESSAGE.pack(side=LEFT) # Validation substitutions # %d Type of action: 1 for insert, 0 for delete, or -1 for focus, forced or # textvariable validation. # %i Index of char string to be inserted/deleted, if any, otherwise -1. # %P The value of the spinbox should edition occur. If you are configuring # the spinbox widget to have a new textvariable, this will be the value # of that textvariable. # %s The current value of spinbox before edition. # %S The text string being inserted/deleted, if any. Otherwise it is an # empty string. # %v The type of validation currently set. # %V The type of validation that triggered the callback (key, focusin, # focusout, forced). # %W The name of the spinbox widget. # TODO: Fix these functions so that delete and overwrite work def validateWidget(self, *args): # W = Tkinter.W = 'w' is already used, so use W_ instead (d, i, P, s, S, v, V, W_) = args # @UnusedVariable # IGNORE:W0612 logging.debug( "OnValidate: d={}, i={}, P={}, s={}, S={}, v={}, V={}, W={}". format(*args)) if W_ == ".pvSysFrame.pvSysDataFrame.numStrSpinbox": valType = INTEGERS valTest = lambda val: int(val) # IGNORE:W0108 elif W_ == ".pvSysFrame.pvSysDataFrame.numModSpinbox": valType = INTEGERS valTest = lambda val: int(val) # IGNORE:W0108 elif W_ == ".pvSysFrame.pvSysDataFrame.sunSpinbox": valType = FLOATS valTest = lambda val: float(val) # IGNORE:W0108 else: return False w = self.nametowidget(W_) w.config(validate=v) if S in valType: try: valTest(P) except ValueError: return False return True else: return False def invalidWidget(self, *args): (d, i, P, s, S, v, V, W_) = args # @UnusedVariable # IGNORE:W0612 logging.debug( "OnInvalid: d={}, i={}, P={}, s={}, S={}, v={}, V={}, W={}".format( *args)) if W_ == ".pvSysFrame.pvSysDataFrame.numStrSpinbox": errText = 'Invalid number of strings!' elif W_ == ".pvSysFrame.pvSysDataFrame.numModSpinbox": errText = 'Invalid number of modules!' elif W_ == ".pvSysFrame.pvSysDataFrame.sunSpinbox": errText = 'Invalid irradiance!' else: errText = 'Unknown widget!' w = self.nametowidget(W_) w.config(validate=v) self.msgtext.set(errText) self.bell() def getIV(self, *args): logging.debug('args:\n\t%r', args) x = np.float64(float(args[0]) / self.pvSys.pvconst.npts / 2.) xp = np.concatenate( (self.pvSys.pvconst.negpts, self.pvSys.pvconst.pts), axis=0).flatten() Vsys = np.interp(x, xp, self.pvSys.Vsys) Isys = np.interp(x, xp, self.pvSys.Isys) Psys = Vsys * Isys / 1000 self.txtVsys.set("{:7.3f}".format(Vsys)) self.txtIsys.set("{:7.3f}".format(Isys)) self.txtPsys.set("{:7.3f}".format(Psys)) def startPVstring_tk(self): top = Toplevel() app = PVstring_tk(self, top) app.mainloop() # please destroy me or I'll continue to run in background top.destroy() def startAdvCnf_tk(self): """ open advnaced config window """ top = Toplevel(name='advCnfTop') app = AdvCnf_tk(self, top) app.mainloop() # please destroy me or I'll continue to run in background top.destroy() def keyBinding(self, event): logging.debug('event widget:\n\t%r', event.widget) logging.debug('event widget get:\n\t%r', event.widget.get()) self.updatePVsys() def updatePVsys(self, *args, **kwargs): logging.debug('args:\n\t%r', args) logging.debug('kwargs:\n\t%r', kwargs) if args and isinstance(args[0], PVsystem_cls): pvsys = args[0] for n, pvstr in enumerate(pvsys.pvstrs): for pvmod in pvstr.pvmods: pvmod.calcMod() pvstr.calcString() logging.debug('updating pvstring #%d: Pmp = %g[W]', n, pvstr.Pstring.max()) return PVAPP = "pvapplication" try: numStrs = self.numStrs.get() if not (0 < numStrs <= self.validationConstants[PVAPP]["numStrs"]): raise PVValidationError('numStrs', numStrs) numMods = self.numMods.get() if not (0 < numMods <= self.validationConstants[PVAPP]["numMods"]): raise PVValidationError('numMods', numMods) sysEe = self.sysEe.get() if not (0 < sysEe <= self.validationConstants[PVAPP]["sysEe"]): raise PVValidationError('sysEe', sysEe) except PVValidationError as err: logging.debug('err:\n\t%r', err) errtext = self.messagetext[PVAPP][err.argname] self.msgtext.set(errtext) self.bell() return numCells = self.numCells.get() self.msgtext.set(self.messagetext[PVAPP]["Ready"]) pvconst = self.pvSys.pvconst pvcell = PVcell(Ee=sysEe) if numCells == 24: numCells = STD24 elif numCells == 72: numCells = STD72 elif numCells == 96: numCells = STD96 elif numCells == 128: numCells = STD128 pvmods = PVmodule(cell_pos=numCells, pvcells=pvcell) self.pvSys = PVsystem(pvconst, numStrs, numberMods=numMods, pvmods=pvmods) self.updateIVstats() def updateIVstats(self): # reuse sysPlot figure and update pvSysFigCanvas self.pvSysPlot = self.pvSys.plotSys(self.pvSysPlot) self.pvSysFigCanvas.show() self.txtImp.set("{:7.3f}".format(self.pvSys.Imp)) # [A] self.txtVmp.set("{:7.3f}".format(self.pvSys.Vmp)) # [V] self.txtPmp.set("{:7.3f}".format(self.pvSys.Pmp / 1000)) # [kW] self.txtIsc.set("{:7.3f}".format(self.pvSys.Isc)) # [A] self.txtVoc.set("{:7.3f}".format(self.pvSys.Voc)) # [V] self.txtFF.set("{:7.3f}".format(self.pvSys.FF * 100)) # [%] self.txtEff.set("{:7.3f}".format(self.pvSys.eff * 100)) # [%] def _help(self): logging.debug('show docs in browser') webbrowser.open(DOCS) def _update(self): self.msgtext.set(READY_MSG) self.updatePVsys() def _reset(self): # number of strings integer variable self.numStrs.set(NUMBERSTRS) # default # number of modules integer variable self.numMods.set(NUMBERMODS) # default # number of cells integer variable self.numCells.set(NUMBERCELLS) # default value is 96 self.msgtext.set(READY_MSG) # TODO: need to reset advCnf too logging.debug('reset') def _load(self): logging.debug('load *.pv file') def _save(self): logging.debug('save *.pv file') def _quit(self): # this is necessary on Windows to prevent # Fatal Python Error: PyEval_RestoreThread: NULL tstate self.master.quit() # stops mainloop self.master.destroy() def readJSON(self, JSONfilename): if not JSONfilename.endswith('json'): JSONfilename += '.json' JSONfullpath = os.path.join(JSONDIR, JSONfilename) with open(JSONfullpath, 'r') as JSONfile: JSONObjects = json.load(JSONfile) logging.debug('JSON objects loaded from %s.', JSONfullpath) return JSONObjects
class pump_ui(object): def __init__(self): master = Tk() master.style = ttk.Style() master.style.theme_use("default") master.config(bg=background_colour) master.resizable( 0, 0 ) # Disable resizing the UI to prevent having to make widget placing dynamic master.winfo_toplevel().title(frame_title) master.iconbitmap("bitcoin.ico") # Create pumper assistant to store data on the current BTC and alt holdings. self.pumper = pumper() self.create_title(master) self.create_api_info(master, previous_row=0) self.create_auto_sell(master, previous_row=3) self.create_stop_loss(master, previous_row=4) self.create_order_type(master, previous_row=6) self.create_fee_type(master, previous_row=7) self.create_btc_balance_picker(master, previous_row=8) self.create_alt_ticker(master, previous_row=10) self.create_pump_and_sell_buttons(master, previous_row=11) self.create_current_profit(master, previous_row=12) self.create_output_box(master, rightmost_column=1) # Can hardcode API key and Secret #self.api_key_entry.delete(0,END) #self.api_key_entry.insert(0,"KEY") #self.api_key_entry.config(state=DISABLED) #self.api_secret_entry.delete(0, END) #self.api_secret_entry.insert(0, "SECRET") #self.api_secret_entry.config(state=DISABLED) # Display the UI, this can only be called once per program. # Nothing in the main Python script will be run after creating the UI because of this. master.mainloop() def create_title(self, master, previous_row=-1, previous_column=-1): empty = Label(master, text=frame_title) empty.grid(row=previous_row + 1, column=previous_column + 2, columnspan=1) empty.config(bg=background_colour, fg=label_font_colour) def create_api_info(self, master, previous_row=-1, previous_column=-1): api_key_lbl = Label(master, text="API Key:") api_key_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0)) api_key_lbl.config(bg=background_colour, fg=label_font_colour) self.api_key_entry = Entry(master, highlightthickness=0, bd=0, width=21, show="*") self.api_key_entry.config(borderwidth=2, relief=default_relief) self.api_key_entry.grid(row=previous_row + 1, column=previous_column + 2) api_secret_lbl = Label(master, text="API Secret:") api_secret_lbl.grid(row=previous_row + 2, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0)) api_secret_lbl.config(bg=background_colour, fg=label_font_colour) self.api_secret_entry = Entry(master, highlightthickness=0, bd=0, width=21, show="*") self.api_secret_entry.config(borderwidth=2, relief=default_relief) self.api_secret_entry.grid(row=previous_row + 2, column=previous_column + 2) self.api_connect_btn = Button(master, text="Connect To Binance", command=self.on_connect_api) self.api_connect_btn.grid(row=previous_row + 3, column=previous_column + 2, columnspan=1, sticky=W + E, padx=10, pady=(0, 3)) self.api_connect_btn.config(highlightbackground=background_colour) def create_auto_sell(self, master, previous_row=-1, previous_column=-1): auto_sell_lbl = Label(master, text="Auto Sell (%):") auto_sell_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0)) auto_sell_lbl.config(bg=background_colour, fg=label_font_colour) self.auto_sell_spinbox = Spinbox(master, from_=1.0, to=300.0, increment=1.0, highlightbackground=background_colour) self.auto_sell_spinbox.config(borderwidth=2, relief=default_relief) self.auto_sell_spinbox.grid(row=previous_row + 1, column=previous_column + 2) self.auto_sell_spinbox.delete(0, "end") self.auto_sell_spinbox.insert(0, 50) def create_stop_loss(self, master, previous_row=-1, previous_column=-1): stop_loss_lbl = Label(master, text="Stop Loss (%):") stop_loss_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0)) stop_loss_lbl.config(bg=background_colour, fg=label_font_colour) self.stop_loss_spinbox = Spinbox(master, from_=-100.0, to=-10.0, increment=1.0, highlightbackground=background_colour) self.stop_loss_spinbox.config(borderwidth=2, relief=default_relief) self.stop_loss_spinbox.grid(row=previous_row + 1, column=previous_column + 2) self.stop_loss_spinbox.delete(0, "end") self.stop_loss_spinbox.insert(0, -10) def create_btc_balance_picker(self, master, previous_row=-1, previous_column=-1): self.btc_balance_str = StringVar() btc_balance_lbl = Label(master, textvar=self.btc_balance_str) btc_balance_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=2, sticky=W + E, padx=(3, 0)) btc_balance_lbl.config(bg=background_colour, fg=label_font_colour) self.set_available_btc_balance(Decimal(0)) btc_to_use_label = Label(master, text="BTC to spend:", bg=background_colour, fg=label_font_colour) btc_to_use_label.grid(row=previous_row + 2, column=previous_column + 1, sticky=E, padx=(3, 0)) self.btc_to_use_spinbox = Spinbox( master, from_=minimum_trade, to=minimum_trade, increment=btc_to_use_increment, highlightbackground=background_colour) self.btc_to_use_spinbox.config(borderwidth=2, relief=default_relief) self.btc_to_use_spinbox.grid(row=previous_row + 2, column=previous_column + 2) def create_order_type(self, master, previous_row=-1, previous_column=-1): order_type_lbl = Label(master, text="Entry Type:") order_type_lbl.grid(row=previous_row + 1, column=previous_column + 1, sticky=E, padx=(3, 0)) order_type_lbl.config(bg=background_colour, fg=label_font_colour) self.is_entry_market = True def change_order_type(*args): self.is_entry_market = (self.order_type.get() == "Market Buy \/") self.order_type = StringVar() self.order_type.trace( "w", change_order_type ) # Reduces how much work is done when the pump starts choices = {"Market Buy \/", "Limit Buy \/"} self.entry_type_option_menu = OptionMenu(master, self.order_type, *choices) self.entry_type_option_menu.grid(row=previous_row + 1, column=previous_column + 2, sticky=W + E, padx=8) self.entry_type_option_menu.config(highlightthickness=0) self.entry_type_option_menu.configure(indicatoron=0) self.order_type.set("Market Buy \/") def create_fee_type(self, master, previous_row=-1, previous_column=-1): fee_type_lbl = Label(master, text="Fee Type:") fee_type_lbl.grid(row=previous_row + 1, column=previous_column + 1, sticky=E, padx=(3, 0)) fee_type_lbl.config(bg=background_colour, fg=label_font_colour) self.is_using_bnb = True def change_fee_type(*args): self.is_using_bnb = ( self.order_type.get() == "Binance Coin (BNB) \/") self.fee_type = StringVar() self.fee_type.trace( "w", change_fee_type ) # Reduces how much work is done when the pump starts choices = {"Binance Coin (BNB) \/", "0.1% Of All Trades \/"} self.fee_type_option_menu = OptionMenu(master, self.fee_type, *choices) self.fee_type_option_menu.grid(row=previous_row + 1, column=previous_column + 2, sticky=W + E, padx=8) self.fee_type_option_menu.config(highlightthickness=0) self.fee_type_option_menu.configure(indicatoron=0) self.fee_type.set("Binance Coin (BNB) \/") def create_pump_and_sell_buttons(self, master, previous_row=-1, previous_column=-1): # Manual sell button can only be activated after initiating a pump. self.manual_sell_btn = Button(master, text="Sell", state=DISABLED, command=self.on_manual_sell) self.manual_sell_btn.grid(row=previous_row + 1, column=previous_column + 1, sticky=W + E, padx=(3, 0)) self.manual_sell_btn.config(highlightbackground=background_colour) self.pump_btn = Button(master, text="Pump", command=self.on_pump) self.pump_btn.grid(row=previous_row + 1, column=previous_column + 2, sticky=W + E, padx=8) self.pump_btn.config(highlightbackground=background_colour, state=DISABLED) def create_alt_ticker(self, master, previous_row=-1, previous_column=-1): ticker_lbl = Label(master, text="Ticker To Pump:") ticker_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0), pady=(0, 8)) ticker_lbl.config(bg=background_colour, fg=label_font_colour) self.ticker_entry = Entry(master, highlightthickness=0, bd=0, width=21) self.ticker_entry.config(borderwidth=2, relief=default_relief) self.ticker_entry.grid(row=previous_row + 1, column=previous_column + 2, pady=8) self.ticker_entry.bind('<Return>', self.on_pump_shortcut) def create_current_profit(self, master, previous_row=-1, previous_column=-1): self.current_profit_str = StringVar() current_profit_lbl = Label(master, textvar=self.current_profit_str) current_profit_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=2, sticky=W + E, padx=3, pady=(0, 3)) current_profit_lbl.config(bg=background_colour, fg=label_font_colour) self.current_profit_str.set("Current Profit: 0%") def create_output_box(self, master, rightmost_column): self.pump_output = StringVar() console_lbl = Label(master, textvar=self.pump_output, borderwidth=2, relief=default_relief, anchor=N) console_lbl.grid(row=0, column=rightmost_column + 1, columnspan=1, rowspan=14, padx=(10, 0), pady=0) console_lbl.config(width=50, height=22, bg="black", font=Font(family="Courier", size=9), fg="white") self.lines = 0 def disable_pre_pump_options(self): # Change the buttons that can be clicked to prevent the user # from trying to pump multiple coins with one bot. self.manual_sell_btn.config(state=NORMAL) self.pump_btn.config(state=DISABLED) self.btc_to_use_spinbox.config(state=DISABLED) self.ticker_entry.config(state=DISABLED) self.auto_sell_spinbox.config(state=DISABLED) self.stop_loss_spinbox.config(state=DISABLED) self.api_key_entry.config( state=DISABLED) # Comment out if hardcoding key self.api_secret_entry.config( state=DISABLED) # Comment out if hardcoding secret self.api_connect_btn.config(state=DISABLED) self.entry_type_option_menu.config(state=DISABLED) self.fee_type_option_menu.config(state=DISABLED) def enable_pump_options(self): # Change the buttons that can be clicked to prevent the user # from trying to pump multiple coins with one bot. self.manual_sell_btn.config(state=DISABLED) self.pump_btn.config(state=NORMAL) self.btc_to_use_spinbox.config(state=NORMAL) self.ticker_entry.config(state=NORMAL) self.auto_sell_spinbox.config(state=NORMAL) self.stop_loss_spinbox.config(state=NORMAL) self.api_key_entry.config( state=NORMAL) # Comment out if hardcoding key self.api_secret_entry.config( state=NORMAL) # Comment out if hardcoding secret self.api_connect_btn.config(state=NORMAL) self.entry_type_option_menu.config(state=NORMAL) self.fee_type_option_menu.config(state=NORMAL) def set_available_btc_balance(self, btc_balance): self.pumper.btc_balance = btc_balance self.btc_balance_str.set("Available Balance: " + readable_btc_balance(btc_balance)) def set_current_profit(self, current_profit): self.current_profit_str.set( "Current Profit: " + '{0:.3f}'.format(round(current_profit * Decimal(100), 3)) + "%") def write_to_console(self, line): self.lines += 1 if self.lines > max_lines_in_console: i = self.pump_output.get().index('\n') self.pump_output.set(self.pump_output.get()[i + 1:] + "\n" + line) elif self.lines == 1: self.pump_output.set(line) else: self.pump_output.set(self.pump_output.get() + "\n" + line) #### Button Behaviour #### def on_pump(self): try: api = self.api btc_to_use = Decimal(self.btc_to_use_spinbox.get()) except InvalidOperation: # The BTC to spend box is empty. self.write_to_console("Stop!") self.write_to_console("BTC to spend cannot be empty.") return except AttributeError: # There is no API object. self.write_to_console( "You need to connect to Binance before pumping.") return if btc_to_use >= minimum_trade: if btc_to_use <= self.pumper.btc_balance: target_profit_percentage = Decimal( float(self.auto_sell_spinbox.get()) / 100.0) # Validate auto-sell and stop loss if target_profit_percentage <= Decimal(0): self.write_to_console("Auto sell has to be positive.") return if Decimal(self.stop_loss_spinbox.get()) >= Decimal(0): self.write_to_console("Stop loss has to be negative.") return ticker = self.ticker_entry.get().upper() # Empty strings are False in Python if ticker: full_ticker = api.full_ticker_for(ticker) try: alt = self.api.get_ticker(symbol=full_ticker) except BinanceAPIException, e: logging.debug(str(e)) self.write_to_console("Invalid ticker.") return alt_value = Decimal(alt["askPrice"]) # Used in console output decimal_points = minimum_decimals_in_quantity.get( full_ticker, 0) self.pumper.decimal_points_in_alt = decimal_points self.pumper.set_up(btc_to_use, target_profit_percentage, alt_value, ticker) if self.is_entry_market: self.pumper.alt_holdings = api.market_buy( self.pumper.btc_to_use, full_ticker, self.is_using_bnb) self.write_to_console( "Bought " + readable_alt_balance( decimal_points, pumper=self.pumper) + " with " + readable_btc_balance(btc_to_use) + ".") else: highest_bid = Decimal(alt["bidPrice"]) if alt_value - highest_bid <= Decimal(0.00000001): to_bid = highest_bid else: # Bid between the highest bid and the lowest ask for the best odds of being filled. to_bid = (alt_value - highest_bid) / 2 + highest_bid to_bid = Decimal( floor(to_bid * Decimal(100000000.0)) ) / Decimal(100000000.0) self.pumper.starting_alt_value = to_bid expected = api.limit_buy( btc_to_alt(btc_to_use, alt_value), pumper, full_ticker, to_bid, self.is_using_bnb) self.write_to_console("Buying " + readable_alt_balance( decimal_points, alt_amount=expected, ticker=ticker ) + " for " + readable_btc_balance(btc_to_use) + ".") self.write_to_console( "This is a limit order, it may not get filled.") self.disable_pre_pump_options() self.set_stop_loss() self.start_monitoring_orderbook(full_ticker) else: # The user is trying to trade with more than they actually have. self.write_to_console("You did not enter a ticker.") else: # The user is trying to trade with more than they actually have. self.write_to_console("Stop!") self.write_to_console( "You are trying to spend more BTC than you have.") else:
class ChargenColor: def __init__(self, parent): self.colorNegative = [] self.colorNeutral = [] self.colorPositive = [] self.scaleNegative = 0.0 self.scalePositive = 0.0 self.cNegative = '#ff0000' self.cNeutral = '#000000' self.cPositive = '#0000ff' self.minNegativeLbl = Label(rootC, text='Min Found: -') self.maxPositiveLbl = Label(rootC, text='Max Found: -') self.scaleLbl = Label(rootC, text='Scale: - to -') self.sclSelectPositive = Spinbox(rootC) self.sclSelectPositive.insert(0, 0.0) self.sclSelectNegative = Spinbox(rootC) self.sclSelectNegative.insert(0, 0.0) self.buttonNegativeCharge = Button( rootC, text='Negative Charge Color', command=self.chooseNegativeCharge) self.buttonNeutralCharge = Button( rootC, text='Neutral Charge Color', command=self.chooseNeutralCharge) self.buttonPositiveCharge = Button( rootC, text='Positive Charge Color', command=self.choosePositiveCharge) self.buttonBG = Button( rootC, text='Background Color', command=self.chooseBackground) self.buttonUpdateColor = Button( rootC, text='Update', command=self.updateColor) self.title = Label(rootC, text="Select your colors") self.buttonClose = Button(rootC, text="Close", command=rootC.destroy) self.buttonBG.pack() self.title.pack() self.buttonNegativeCharge.pack() self.buttonNeutralCharge.pack() self.buttonPositiveCharge.pack() self.minNegativeLbl.pack() self.maxPositiveLbl.pack() self.scaleLbl.pack() self.sclSelectNegative.pack() self.sclSelectPositive.pack() self.buttonUpdateColor.pack() self.buttonClose.pack() def chooseNegativeCharge(self): self.colorNegative = askcolor( color=self.cNegative, title="Negative Charge Color") self.buttonNegativeCharge.config(fg=self.colorNegative[1]) self.cNegative = self.colorNegative[1] def chooseNeutralCharge(self): self.colorNeutral = askcolor( color=self.cNeutral, title="Neutral Charge Color") self.buttonNeutralCharge.config(fg=self.colorNeutral[1]) self.cNeutral = self.colorNeutral[1] def choosePositiveCharge(self): self.colorPositive = askcolor( color=self.cPositive, title="Positive Charge Color") self.buttonPositiveCharge.config(fg=self.colorPositive[1]) self.cPositive = self.colorPositive[1] def chooseBackground(self): bgcolor = askcolor( color=self.cPositive, title="Positive Charge Color") cmd.set_color("bg_chargy_color", bgcolor[0]) cmd.bg_color("bg_chargy_color") def updateColor(self): selection = 'all' stored.atoms_charge = [] stored.atoms_colors = [] cmd.map_new('chargyc_map', selection="(all)") if not self.colorNeutral: tkMessageBox.showerror("Error", "Set Neutral Color, Please") return if not self.colorNegative: tkMessageBox.showerror("Error", "Set Negative Color, Please") return if not self.colorPositive: tkMessageBox.showerror("Error", "Set Positive Color, Please") return cmd.iterate_state(1, '(' + selection + ')', 'stored.atoms_charge.append(partial_charge)') _i = 0 minValue = None maxValue = None while _i < len(stored.atoms_charge): color = [] if _i == 0: maxValue = stored.atoms_charge[_i] minValue = stored.atoms_charge[_i] if(stored.atoms_charge[_i] > maxValue): maxValue = stored.atoms_charge[_i] if stored.atoms_charge[_i] < minValue: minValue = stored.atoms_charge[_i] _i += 1 self.minNegativeLbl["text"] = 'Min Found: ' + str(round(minValue, 3)) self.maxPositiveLbl["text"] = 'Max Found: ' + str(round(maxValue, 3)) if(self.scaleNegative == 0.0 and self.scalePositive == 0.0): self.scaleNegative = round(minValue, 3) self.scalePositive = round(maxValue, 3) self.sclSelectNegative.delete(0, "end") self.sclSelectPositive.delete(0, "end") self.sclSelectNegative.insert(0, round(minValue, 3)) self.sclSelectPositive.insert(0, round(maxValue, 3)) else: self.scaleNegative = float(self.sclSelectNegative.get()) self.scalePositive = float(self.sclSelectPositive.get()) minValue = float(self.sclSelectNegative.get()) maxValue = float(self.sclSelectPositive.get()) self.scaleLbl["text"] = 'Scale: ' + str( self.scaleNegative) + ' to ' + str(self.scalePositive) middleValue = 0 if(maxValue < 0): maxValue = 0 if(minValue > 0): minValue = 0 _i = 0 while _i < len(stored.atoms_charge): color = [] cmd.set_color("neutral_color", self.colorNeutral[0]) cmd.set_color("positive_color", self.colorPositive[0]) cmd.set_color("negative_color", self.colorNegative[0]) if(stored.atoms_charge[_i] >= middleValue): if(stored.atoms_charge[_i] == middleValue): cmd.set_color(str(_i) + "_color", self.colorNeutral[0]) else: cmd.set_color(str(_i) + "_color", self.getColor( self.colorNeutral[0], self.colorPositive[0], maxValue, stored.atoms_charge[_i] if stored.atoms_charge[_i] < maxValue else maxValue)) else: cmd.set_color(str(_i) + "_color", self.getColor( self.colorNeutral[0], self.colorNegative[0], abs(minValue), abs(stored.atoms_charge[_i]) if abs(stored.atoms_charge[_i]) < abs(minValue) else abs(minValue))) index = cmd.get_color_index(str(_i) + "_color") stored.atoms_colors.append(index) _i += 1 cmd.alter_state(1, '(' + selection + ')', "color=stored.atoms_colors.pop(0)") cmd.ramp_new('chargy_ramp', 'chargyc_map', range=[self.scaleNegative, ((self.scaleNegative+self.scalePositive)/2.0), self.scalePositive], color=['negative_color', 'neutral_color', 'positive_color']) def getColor(self, color, colorMax, step, index): colorStep = [0, 0, 0] colorStep[0] = ((colorMax[0]-color[0])/step) colorStep[1] = ((colorMax[1]-color[1])/step) colorStep[2] = ((colorMax[2]-color[2])/step) return [ 1.0 if (color[0] + (colorStep[0]*index)) / 255.0 >= 1 else (color[0] + (colorStep[0]*index))/255.0, 1.0 if (color[1] + (colorStep[1]*index)) / 255.0 >= 1 else (color[1] + (colorStep[1]*index))/255.0, 1.0 if (color[2] + (colorStep[2]*index)) / 255.0 >= 1 else (color[2] + (colorStep[2]*index))/255.0 ]
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]: if type(_def_txt_[1]) in [set]: _nums_ = [str(x) for x in sorted(list(_def_txt_[1]))] Ent_It = StringVar() aux_spin = Spinbox(_row_, textvariable=Ent_It, values=tuple(_nums_)) Ent_It.set(_def_txt_[0]) else: 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] and type(_def_txt_[1]) == set: aux_spin.pack(side='left', expand=True, fill=X) else: 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 initUI(self): self.parent.title("FIND BLR COEFFICIENT VALUE") self.pack(fill=BOTH, expand=True) self.columnconfigure(0, weight=1) # self.rowconfigure(0, weight=1) # weight attibute is used to make them growable ###### GUI Control Variables ###### self.LIMIT_L = IntVar() self.LIMIT_H = IntVar() self.PULSE_R = IntVar() self.PULSE_L = IntVar() self.pulse_height = DoubleVar() self.hdf5_file = StringVar() self.PMT = IntVar() self.EVENT = IntVar() self.amplitude_range = DoubleVar() self.delta = DoubleVar() self.noise_sigma = DoubleVar() self.coeff = DoubleVar() #self.DRAW = BooleanVar() search = Image.open("next_logo.jpg") search_temp = search.resize((170, 200), Image.ANTIALIAS) search_aux = ImageTk.PhotoImage(search_temp) label1 = Label(self, image=search_aux) label1.image = search_aux label1.grid(row=0, column=0, columnspan=10, rowspan=10, sticky=E+W+S+N) self.hdf5_file.set("2052.h5.z") e1 = Entry(self, textvariable=self.hdf5_file, width=30) e1.grid(row=1,column=1, sticky=W, columnspan=5, pady=5) e1_label = Label(self, text="HDF5 file") e1_label.grid(row=0,column=1,sticky=W, columnspan=5, pady=5) self.PMT.set("0") sb1 = Spinbox(self, from_=0, to=12, width=3, textvariable=self.PMT) sb1.grid(row=3,column=2, sticky=W) sb1_label = Label(self, text="PMT") sb1_label.grid(row=2,column=2, padx=0, sticky=W) self.EVENT.set("0") sb1 = Spinbox(self, from_=0, to=1000, width=5, textvariable=self.EVENT) sb1.grid(row=3,column=3, sticky=W) sb1_label = Label(self, text="EVENT") sb1_label.grid(row=2,column=3, padx=0, sticky=W) self.LIMIT_L.set("19000") sb1 = Spinbox(self, from_=0, to=100000, width=5, textvariable=self.LIMIT_L) sb1.grid(row=5,column=2, sticky=W) sb1_label = Label(self, text="ROI Start ") sb1_label.grid(row=4,column=2, padx=0, sticky=W) self.LIMIT_H.set("22500") sb1 = Spinbox(self, from_=0, to=100000, width=5, textvariable=self.LIMIT_H) sb1.grid(row=5,column=3, sticky=W) sb1_label = Label(self, text="ROI End ") sb1_label.grid(row=4,column=3, padx=0, sticky=W) self.PULSE_R.set("20142") sb1 = Spinbox(self, from_=0, to=100000, width=8, textvariable=self.PULSE_R) sb1.grid(row=5,column=4, sticky=E) sb1_label = Label(self, text=" Pulse Rise") sb1_label.grid(row=4,column=4, padx=0, sticky=E) self.PULSE_L.set("1200") sb1 = Spinbox(self, from_=0, to=5000, width=8, textvariable=self.PULSE_L) sb1.grid(row=5,column=5, sticky=E) sb1_label = Label(self, text=" Pulse Length") sb1_label.grid(row=4,column=5, padx=0, sticky=E) sb1_label = Label(self, text=" ") sb1_label.grid(row=2,column=7, padx=0, sticky=W) sb1_label = Label(self, text=" ") sb1_label.grid(row=6,column=7, padx=0, sticky=W) self.pulse_height.set("545.5") sb1 = Entry(self, width=8, textvariable=self.pulse_height) sb1.grid(row=7,column=3, sticky=E) sb1_label = Label(self, text=" Amplitude") sb1_label.grid(row=6,column=3, padx=0, sticky=E) self.amplitude_range.set("2") sb1 = Entry(self, width=8, textvariable=self.amplitude_range) sb1.grid(row=7,column=4, sticky=E) sb1_label = Label(self, text=" Loop Range") sb1_label.grid(row=6,column=4, padx=0, sticky=E) self.delta.set("0.1") sb1 = Entry(self, width=8, textvariable=self.delta) sb1.grid(row=7,column=5, sticky=E) sb1_label = Label(self, text=" Loop Delta") sb1_label.grid(row=6,column=5, padx=0, sticky=E) self.noise_sigma.set("4") sb1 = Entry(self, width=3, textvariable=self.noise_sigma) sb1.grid(row=5,column=6, sticky=E) sb1_label = Label(self, text=" Noise Threshold") sb1_label.grid(row=4,column=6, padx=0, sticky=E) sb_coeff_label = Label(self, text= "Coefficient ") sb_coeff_label.grid(row=0,column=6, padx=0, sticky=E) self.sb_coeff = Label(self) self.sb_coeff.grid(row=1,column=6, padx=0, sticky=E) # MAIN BUTTONS obtn = Button(self, text="GO!!", command=self.find_C) obtn.grid(row=14, column=4, sticky=E, pady=10) cbtn = Button(self, text="Quit", command=self.quit) cbtn.grid(row=14, column=5, sticky=E, pady=10) hbtn = Button(self, text="Help", command=self.help_f) hbtn.grid(row=14, column=0, sticky=W, pady=10)
def initUI(self): self.parent.title("FIND SPE VALUE") self.pack(fill=BOTH, expand=True) self.columnconfigure(0, weight=1) #self.rowconfigure(0, weight=1) # weight attibute is used to make them growable self.graph_cb = BooleanVar() self.bins = IntVar() self.path = StringVar() self.n_files = IntVar() self.start_s = IntVar() self.end_s = IntVar() self.guess = IntVar() search = Image.open("next_logo.jpg") search_temp = search.resize((160, 200), Image.ANTIALIAS) search_aux = ImageTk.PhotoImage(search_temp) label1 = Label(self, image=search_aux) label1.image = search_aux label1.grid(row=0, column=0, columnspan=10, rowspan=10, sticky=E+W+S+N) #Number of Files and Bins. Spin Box self.n_files.set("2000") sb1 = Spinbox(self, from_=1, to=10000, width=6, textvariable=self.n_files) sb1.grid(row=1,column=4, sticky=W) sb1_label = Label(self, text="Files") sb1_label.grid(row=1,column=3, padx=5, sticky=E) self.bins.set("50") sb2 = Spinbox(self, from_=10, to=200, width=6, textvariable=self.bins) sb2.grid(row=1,column=6, sticky=W) sb2_label = Label(self, text="Hist. Bins") sb2_label.grid(row=1,column=5, padx=5, sticky=E) # INTEGRATION LIMITS Integration_label = Label(self, text="INTEGRATION", font = "Verdana 12 bold") Integration_label.grid(row=3,column=4, padx=5, columnspan = 2) self.start_s.set("1732") sb3 = Spinbox(self, from_=1, to=10000, width=6, textvariable=self.start_s) sb3.grid(row=4,column=4, sticky=W) sb3_label = Label(self, text="StartPoint") sb3_label.grid(row=4,column=3, padx=5, sticky=E) self.end_s.set("1752") sb4 = Spinbox(self, from_=1, to=10000, width=6, textvariable=self.end_s) sb4.grid(row=4,column=6, sticky=W) sb4_label = Label(self, text="EndPoint") sb4_label.grid(row=4,column=5, padx=5, sticky=E) sb4_label = Label(self, text="") sb4_label.grid(row=4,column=7, padx=5, sticky=E) # FITTING PARAMETERS Integration_label = Label(self, text="FITTING", font = "Verdana 12 bold") Integration_label.grid(row=6,column=4, padx=5, columnspan = 2) self.guess.set("-20") sb5 = Spinbox(self, from_=-50, to=-1, width=6, textvariable=self.guess) sb5.grid(row=7,column=4, sticky=W) sb5_label = Label(self, text="SPE guess") sb5_label.grid(row=7,column=5, padx=5, sticky=W) #Check buttons cb1 = Checkbutton(self, text="MultiGraph Output", variable=self.graph_cb ) cb1.select() cb1.grid(row=7,column=6, sticky=W) #Text Box #self.path.set("F:/DATOS_DAC/spe_1230/2046/pmt_0_trace_evt_") self.path.set("spe_1230_2046.h5.z") e1 = Entry(self, textvariable=self.path, width=45) e1.grid(row=10,column=3, sticky=W, columnspan=10, padx=10, pady=5) e1_label = Label(self, text="DataSet path (including name file)") e1_label.grid(row=9,column=3,sticky=W, columnspan=10, padx=10) # Main buttons obtn = Button(self, text="GO!!", command=self.SPE_f) obtn.grid(row=14, column=5, sticky=E, pady=5) cbtn = Button(self, text="Quit", command=self.quit) cbtn.grid(row=14, column=6, sticky=E, pady=5) hbtn = Button(self, text="Help") hbtn.grid(row=14, column=0, sticky=W, pady=5)
def initUI(self): self.parent.title("DBLR for Dummies") self.pack(fill=BOTH, expand=True) #self.columnconfigure(0, weight=1) #self.rowconfigure(0, weight=1) # weight attibute is used to make them growable self.meas = IntVar() self.point = IntVar() self.base_path = StringVar() self.coef = DoubleVar() self.noise = DoubleVar() self.n_sigma = DoubleVar() self.thr1 = DoubleVar() self.thr2 = DoubleVar() self.thr3 = DoubleVar() self.graph_sw = BooleanVar() #Image factor=0.65 search = Image.open("NEXT_official_logo.jpg") width_org, height_org = search.size search_temp = search.resize((int(width_org*factor), int(height_org*factor)), Image.ANTIALIAS) search_aux = ImageTk.PhotoImage(search_temp) label1 = Label(self, image=search_aux) label1.image = search_aux label1.grid(row=0, column=4, columnspan=2, rowspan=3, padx=5) #self.base_path.set("F:/DATOS_DAC/2052/pmt_0_trace_evt_") self.base_path.set("Argon.h5.z") e1 = Entry(self, textvariable=self.base_path, width=40) e1.grid(row=0,column=1, sticky=W, columnspan=3, pady=5, padx=5) e1_label = Label(self, text="Path & Name") e1_label.grid(row=0,column=0, columnspan=1, sticky=E, pady=5, padx=5) self.point.set("0") sb1 = Spinbox(self, from_=0, to=100, width=4, textvariable=self.point) sb1.grid(row=2,column=1, sticky=W, pady=5, padx=5) sb1_label = Label(self, text="PMT") sb1_label.grid(row=2,column=0, padx=5, sticky=E) self.meas.set("0") sb1 = Spinbox(self, from_=0, to=100, width=4, textvariable=self.meas) sb1.grid(row=2,column=3, sticky=W, pady=5, padx=5) sb1_label = Label(self, text="Event") sb1_label.grid(row=2,column=2, padx=5, sticky=E) #Check buttons # cb1 = Checkbutton(self, text="New Graph", variable=self.graph_sw) # cb1.select() # cb1.grid(row=2,column=2, sticky=W) #PARAMETERS Integration_label = Label(self, text="PARAMETERS", font = "Verdana 12 bold") Integration_label.grid(row=3,column=1, padx=5, columnspan = 2, pady=10, sticky=E) self.coef.set("1.65E-3") e2 = Entry(self, width=12, textvariable=self.coef) e2.grid(row=4,column=1, sticky=W, pady=5, padx=5) e2_label = Label(self, text="DBLR Coef") e2_label.grid(row=4,column=0, sticky=E, pady=5, padx=5) self.noise.set("0.75") e3 = Entry(self, width=12, textvariable=self.noise) e3.grid(row=4,column=3, sticky=W, pady=5, padx=5) e3_label = Label(self, text="Noise (LSB)") e3_label.grid(row=4,column=2, sticky=E, pady=5, padx=5) self.n_sigma.set("4") e4 = Entry(self, width=12, textvariable=self.n_sigma) e4.grid(row=4,column=5, sticky=W, pady=5, padx=5) e4_label = Label(self, text="Noise Threshold") e4_label.grid(row=4,column=4, sticky=E, pady=5, padx=5) self.thr1.set("0") e5 = Entry(self, width=12, textvariable=self.thr1) e5.grid(row=5,column=1, sticky=W, pady=5, padx=5) e5_label = Label(self, text="Threshold 1") e5_label.grid(row=5,column=0, sticky=E, pady=5, padx=5) self.thr2.set("0") e6 = Entry(self, width=12, textvariable=self.thr2) e6.grid(row=5,column=3, sticky=W, pady=5, padx=5) e6_label = Label(self, text="Threshold 2") e6_label.grid(row=5,column=2, sticky=E, pady=5, padx=5) self.thr3.set("0") e7 = Entry(self, width=12, textvariable=self.thr3) e7.grid(row=5,column=5, sticky=W, pady=5, padx=5) e7_label = Label(self, text="Threshold 3") e7_label.grid(row=5,column=4, sticky=E, pady=5, padx=5) # Main buttons obtn = Button(self, text="GO!!", command=self.DBLR_f) obtn.grid(row=6, column=4, sticky=E, pady=10) cbtn = Button(self, text="Quit", command=self.quit) cbtn.grid(row=6, column=5, sticky=E, pady=10) hbtn = Button(self, text="Help", command=self.help_f) hbtn.grid(row=6, column=0, sticky=W, pady=10)
class UIFrame(Frame): ''' This class is responsible for creating configuring and laying out all controls on the main GUI window. It returns UIFrame object (based on Frame) representing the populated window for the application to interact with. ''' def __init__(self, parent): ''' Creates and returns a new UIFrame object. _Parameters_ parent (required) - The parent widget object under which this console is to be created. _Return_ UIFrame Object ''' Frame.__init__(self, parent) self.parent = parent #Main window frames self._optionsFrame = Frame(self.parent) self._runFrame = Frame(self.parent) self._consoleFrame = Frame(self.parent) #Member widget creation and configuration - widgets configured in their constructors self._lblLoopCount = Label(self._optionsFrame, text = "Loop Count") self.LoopSpinner = Spinbox(self._optionsFrame, from_ = 1, to = 5000, repeatdelay = 500, repeatinterval = 50) self._lblOptions = Label(self._optionsFrame, text="Options String") self.OptionsEntry = Entry(self._optionsFrame, exportselection = False) self.ClearButton = Button(self._runFrame, text="Clear") self.RunButton = Button(self._runFrame, text="Run!!!") self.Console = ConsoleFrame(self._consoleFrame) #Geometry control #First pack the main window frames self._optionsFrame.pack(fill = "x") self._runFrame.pack() self._consoleFrame.pack(fill = "both", expand = True, padx = 2, pady = 2) #This line is needed to allow the options column to have the correct width self._optionsFrame.columnconfigure(1, weight = 1) #widgets in options frame self._lblLoopCount.grid(row = 0, column = 0, sticky = "w", padx = 2, pady = 2) self.LoopSpinner.grid(row = 1, column = 0, sticky = "w", padx = 2, pady = 2) self._lblOptions.grid(row = 0, column = 1, sticky = "w", padx = 2, pady = 2) self.OptionsEntry.grid(row = 1, column = 1, sticky = "e"+"w", padx = 2, pady = 2) #widgets in run frame self.RunButton.pack(side = "left", padx = 2, pady = 2) self.ClearButton.pack(side = "left", padx = 2, pady = 2) #note - Console frame packed in constructor for console object #set minimum window size self.master.update_idletasks() self.master.minsize(self.master.winfo_width(), self.master.winfo_height())
def __init__(self, master): self.master = master master.title(u"Weiterreißwiderstand") self.big_font = tkFont.Font(family='Helvetica', size=36, weight='bold') self.normal_font = tkFont.Font(family='Helvetica', size=20, weight='normal') self.X = None self.Y = None self.maxima = None self.maxima_x = None self.number_max = 0 self.number_max_string = StringVar() self.max_max = 0.0 self.max_max_string = StringVar() self.min_max = 0.0 self.min_max_string = StringVar() self.median = 0.0 self.median_string = StringVar() self.w_string = StringVar() self.distance_string = StringVar() self.method_string = StringVar() self.sample_file = '' self.project_file = '' self.w = 0.0 self.distance = 0.0 ######################################################################### ''' Optionen für Dateidialoge ''' self.file_opt = options = {} options['defaultextension'] = '.txt' options['filetypes'] = [('text files', '.txt')] options['initialfile'] = '' options['parent'] = master options['title'] = 'Messung importieren' self.file_opt2 = options = {} options['defaultextension'] = '.txt' options['filetypes'] = [('text files', '.txt')] options['initialfile'] = '' options['parent'] = master options['title'] = 'Neues Projekt erstellen.' self.file_opt3 = options = {} options['defaultextension'] = '.txt' options['filetypes'] = [('text files', '.txt')] options['initialfile'] = '' options['parent'] = master options['title'] = 'Vorhandenes Projekt öffnen.' ##################################################################################################### ''' GUI ''' ''' MenueLeiste ''' ############################################################################################### self.menubar = Menu(master) # create a pulldown menu, and add it to the menu bar self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label="Neu", command=self.new_file, font = self.normal_font) self.filemenu.add_command(label=u"Öffnen...", command=self.open_file, font = self.normal_font) self.filemenu.add_separator() self.filemenu.add_command(label="Messung importieren", command=self.get_filepath, font = self.normal_font) self.filemenu.add_separator() self.filemenu.add_command(label="Beenden", command=root.quit, font = self.normal_font) self.menubar.add_cascade(label="Datei", menu=self.filemenu, font = self.normal_font) self.helpmenu = Menu(self.menubar, tearoff=0) self.helpmenu.add_command(label="Hilfe", command=self.help, font = self.normal_font) self.helpmenu.add_command(label=u"Über", command=self.info, font = self.normal_font) self.menubar.add_cascade(label="Hilfe", menu=self.helpmenu, font = self.normal_font) master.config(menu=self.menubar) ############################################################################################## ''' Parameter ''' self.option_label = ttk.Label(master, text = "Parameter", font = self.big_font) self.option_label.grid(row = 0, rowspan = 2, columnspan = 4, sticky=W) self.delta_x_label = ttk.Label(master, text = "Delta X", font = self.normal_font) self.delta_x_label.grid(row = 3, sticky=W) self.delta_x_spinbox = Spinbox(master, from_=10, to=500, increment = 10, font = self.normal_font, width = 4, command = self.plot) self.delta_x_spinbox.grid(row = 3, column = 1) self.delta_y_label = ttk.Label(master, text = "Delta Y", font = self.normal_font) self.delta_y_label.grid(row = 4, column = 0, sticky=W) self.delta_y_spinbox = Spinbox(master, from_=0, to=2, increment = 0.05, font = self.normal_font, width = 4, command = self.plot) self.delta_y_spinbox.grid(row = 4, column = 1) # self.plot_button = Button(master, text = "Plotten", font = self.normal_font, command = self.plot, width = 10) # self.plot_button.grid(row = 3, column = 2, columnspan = 1) self.sample_thickness_label = ttk.Label(master, text = "Probendicke [mm]", font = self.normal_font) self.sample_thickness_label.grid(row = 5, column = 0, sticky=W) self.sample_thickness_entry = ttk.Entry(master, font = self.normal_font, width = 5) self.sample_thickness_entry.grid(row = 5, column = 1) self.calculate_button = Button(master, text = "Berechnen", font = self.normal_font, command = self.calculate, width = 10) self.calculate_button.grid(row = 6, column = 1, columnspan = 1) ########################################################################################################## ''' Speichern ''' self.save_label = ttk.Label(master, text = "Auswertung Speichern", font = self.big_font) self.save_label.grid(row = 7, rowspan = 2, columnspan = 4, sticky=W) self.sample_name_label = ttk.Label(master, text = "Probenname", font = self.normal_font) self.sample_name_label.grid(row = 9, sticky=W) self.sample_name_entry = ttk.Entry(master, font = self.normal_font) self.sample_name_entry.grid(row = 9, column = 1, columnspan = 3) self.comment_label = ttk.Label(master, text = "Kommentar", font = self.normal_font) self.comment_label.grid(row = 10, sticky=W) self.comment_entry = ttk.Entry(master, font = self.normal_font) self.comment_entry.grid(row = 10, column = 1, columnspan = 3) self.save_button = Button(master, text = "Speichern", font = self.normal_font, command = self.save, width = 10) self.save_button.grid(row = 12, column = 1, columnspan = 2, sticky=W) ############################################################################################################## ''' Analyse ''' self.number_max_label = ttk.Label(master, text = "Anzahl Maxima:", font = self.normal_font) self.number_max_label.grid(row = 9, column = 6, sticky=W) self.number_max_int_label = ttk.Label(master, textvariable = self.number_max_string, font = self.normal_font) self.number_max_int_label.grid(row = 9, column = 7) self.max_max_label = ttk.Label(master, text = "Median [N]:", font = self.normal_font) self.max_max_label.grid(row = 10, column = 6, sticky=W) self.max_max_int_label = ttk.Label(master, textvariable = self.median_string, font = self.normal_font) self.max_max_int_label.grid(row = 10, column = 7) self.min_max_label = ttk.Label(master, text = u"Weiterreißwiderstand [N/mm]:", font = self.normal_font) self.min_max_label.grid(row = 11, column = 6, sticky=W) self.min_max_int_label = ttk.Label(master, textvariable = self.w_string, font = self.normal_font) self.min_max_int_label.grid(row = 11, column = 7) self.min_max_label = ttk.Label(master, text = u"Spannweite [mm]:", font = self.normal_font) self.min_max_label.grid(row = 12, column = 6, sticky=W) self.min_max_int_label = ttk.Label(master, textvariable = self.distance_string, font = self.normal_font) self.min_max_int_label.grid(row = 12, column = 7) self.method_label = ttk.Label(master, text="Methode:", font = self.normal_font) self.method_label.grid(row = 13, column = 6, sticky=W) self.method_method_label = ttk.Label(master, textvariable = self.method_string, font = self.normal_font) self.method_method_label.grid(row = 13, column = 7) ########################################################################################################## ''' Canvas ''' # Create a canvas self.w, self.h = 800, 500 self.canvas = Canvas(master, width=self.w, height=self.h) self.canvas.grid(row = 0, column = 5, columnspan = 5, rowspan = 9) '''
class Outlier4dfp(Frame): def __init__(self, parent, filename=None, filename_roi=None, filename_csv=None, dirname=None, obj_return_value=None): Frame.__init__(self, parent) self.parent = parent self.obj_return_value = obj_return_value # check filenames if filename is None or not os.path.isfile(filename): if dirname is not None: filename = tkFileDialog.askopenfilename(initialdir=dirname) else: filename = tkFileDialog.askopenfilename() if not os.path.isfile(filename): parent.destroy() return if filename_roi is None or not os.path.isfile(filename_roi): if dirname is not None: filename_roi = tkFileDialog.askopenfilename(initialdir=dirname) else: filename_roi = tkFileDialog.askopenfilename() if not os.path.isfile(filename_roi): parent.destroy() return if dirname is None: self.dirname = os.path.dirname(filename) else: self.dirname = dirname if filename_csv is None: filename_csv = os.path.join( self.dirname, filename_wo_ext(os.path.basename(filename)) + '.csv') self.filename = filename self.filename_roi = filename_roi self.filename_csv = filename_csv self.dat = nib.load(filename).get_data() self.shape = self.dat.shape print self.shape dz = self.shape[2] df = self.shape[-1] self.badenc = np.zeros((dz, df), dtype=np.int16) self.prev = np.zeros((dz, df), dtype=np.int16) self.z = 0 self.initUI() self.run() #if filename_csv is not None and os.path.isfile(filename_csv): # self.run_read() def reset(self): dz = self.shape[2] df = self.shape[-1] self.badenc[:, :] = np.zeros((dz, df), dtype=np.int16) self.prev[:, :] = np.zeros((dz, df), dtype=np.int16) def make_checkbox_all(self, frame, width=4, ncol=20): self.lst_checkbox_slices_values = [] self.lst_checkbox_slices = [] ii = 0 for z in range(self.shape[2]): self.lst_checkbox_slices_values.append( [BooleanVar() for f in range(self.shape[3])]) boxes = [ Checkbutton(frame, text=str('%s' % f), variable=self.lst_checkbox_slices_values[z][f], width=width) for f in range(self.shape[3]) ] jj = 0 for f in range(self.shape[3]): btn = boxes[f] btn.grid(row=z, column=f) jj += 1 if ncol is not None and ncol <= jj: ii += 1 jj = 0 self.lst_checkbox_slices.append(boxes) if jj > 0: ii += 1 def make_checkbox(self, frame, width=4, ncol=20): #self.lst_checkbox_slices_values = [BooleanVar() for f in range(self.shape[3])] self.lst_checkbox_slices_values = [ IntVar() for f in range(self.shape[3]) ] self.lst_checkbox_slices = [ Checkbutton(frame, text=str('%s' % f), variable=self.lst_checkbox_slices_values[f], width=width, command=functools.partial(self.click_check, f)) for f in range(self.shape[3]) ] ii = 0 jj = 0 for f in range(self.shape[3]): btn = self.lst_checkbox_slices[f] btn.grid(row=ii, column=jj) jj += 1 if ncol is not None and ncol <= jj: jj = 0 ii += 1 if jj > 0: ii += 1 def click_check(self, f): value = self.lst_checkbox_slices_values[f].get() if value == 1: value = 0 else: value = 1 self.lst_checkbox_slices_values[f].set(value) self.badenc[self.z, f] = value print self.z, f, self.badenc[self.z, f] def set_z(self, z=None): if z is None: z = self.z else: self.z = z for i in range(len(self.lst_checkbox_slices_values)): chkbox = self.lst_checkbox_slices_values[i] # FIXME # avail chkbox if self.prev[z, i] > 0 or self.badenc[z, i] > 0: to_check = True to_check = 1 self.lst_checkbox_slices[i].select() else: to_check = False to_check = 0 self.lst_checkbox_slices[i].deselect() chkbox.set(to_check) # avail def run(self): dat = self.dat roi = nib.load(self.filename_roi).get_data().astype(bool) print dat.shape print roi.shape dz = self.shape[2] df = self.shape[3] self.values = np.zeros((dz, df), dtype=dat.dtype) for z in range(dz): for f in range(df): self.values[z, f] = dat[:, :, z, f][roi[:, :, z]].mean() self.draw_slice() def draw_slice(self): z = self.z df = self.shape[3] print z #r = self.frame_graph.axes.boxplot(self.values.T) sorted_values = np.sort(self.values[z, :]) q1 = sorted_values[df / 4] q2 = sorted_values[df / 2] q3 = sorted_values[df - df / 4] iqr = q3 - q1 #if1 = q1 - 1.5*iqr #if2 = q3 + 1.5*iqr of1 = q1 - 3 * iqr of2 = q3 + 3 * iqr xx = np.arange(df) z_mean = self.values[z, :].mean() z_std = self.values[z, :].std() #z_min = self.values[z,:].min() #z_max = self.values[z,:].max() #self.frame_graph.axes.hold(False) self.frame_graph.axes.clear() self.frame_graph.axes.plot([0, df], [z_mean, z_mean], 'k-') #self.frame_graph.axes.hold(True) self.frame_graph.axes.plot([0, df], [z_mean + 1 * z_std, z_mean + 1 * z_std], 'y--') self.frame_graph.axes.plot([0, df], [z_mean + 2 * z_std, z_mean + 2 * z_std], 'g--') self.frame_graph.axes.plot([0, df], [z_mean + 3 * z_std, z_mean + 3 * z_std], 'b--') self.frame_graph.axes.plot([0, df], [of2, of2], 'r-') for f in range(df): if self.prev[z, f] > 0: self.frame_graph.axes.plot(f, self.values[z, f], 'ko') self.frame_graph.axes.text(f + 0.2, self.values[z, f], str(f)) elif of1 < self.values[z, f] < of2: #if self.values[z,f] < z_mean + 3*z_std: self.frame_graph.axes.plot(f, self.values[z, f], 'bo') if self.values[z, f] > z_mean + 3 * z_std: self.frame_graph.axes.text(f + 0.2, self.values[z, f], str(f)) else: self.frame_graph.axes.plot(f, self.values[z, f], 'ro') self.frame_graph.axes.text(f + 0.2, self.values[z, f], str(f)) self.frame_graph.draw() self.set_z(z) def run_read(self): filename = tkFileDialog.askopenfilename(initialdir=self.dirname) if filename == '': return with open(filename) as f: values = [[int(tmp) for tmp in line.strip().split(',')] for line in f.readlines()] self.prev[:, :] = values def run_save(self): filename = tkFileDialog.asksaveasfilename( initialdir=os.path.dirname(self.filename_csv), initialfile=os.path.basename(self.filename_csv)) if filename == '': return dz = self.shape[2] df = self.shape[-1] badenc = self.badenc.copy() badenc[self.prev > 0] = 1 with open(filename, 'w') as f: for z in range(dz): f.write('%s\n' % (','.join([str(tmp) for tmp in badenc[z, :]]))) with open(os.path.join(self.dirname, 'badenc.dat'), 'wb') as fout: if False: for z in range(dz): row = struct.pack('i' * df, *badenc[z, :]) fout.write(row) fout.write('%s %s\n' % (dz, df)) for z in range(dz): row = ' '.join(str(tmp) for tmp in badenc[z, :]) fout.write('%s\n' % row) if self.obj_return_value is not None: self.obj_return_value.delete(0, len(self.obj_return_value.get())) self.obj_return_value.insert(0, filename) def initUI(self): self.frame_top = Frame(self) self.frame_graph = MplCanvas(self) self.frame_bottom = Frame(self) Label(self.frame_top, text='Z = ').pack(side=LEFT) self.spin_z = Spinbox(self.frame_top, from_=0, to=self.shape[2] - 1, increment=1, command=self.change_z) self.spin_z.pack(side=LEFT) self.make_checkbox(self.frame_bottom, width=4) Label(self.frame_top, text=' CSV').pack(side=LEFT) self.txt_filename_csv = Entry(self.frame_top) self.txt_filename_csv.pack(side=LEFT) self.button_read = Button(self.frame_top, text='Read', command=self.run_read) self.button_read.pack(side=LEFT) self.button_save = Button(self.frame_top, text='Save', command=self.run_save) self.button_save.pack(side=LEFT) Label(self.frame_top, text=' ').pack(side=LEFT) button_reset = Button(self.frame_top, text='Reset', command=self.reset).pack(side=LEFT) self.frame_top.pack(side=TOP) self.frame_graph.get_tk_widget().pack(fill=BOTH, expand=TRUE) self.frame_bottom.pack(fill=BOTH, expand=TRUE) self.pack(fill=BOTH, expand=True) def change_z(self): self.z = int(self.spin_z.get()) self.draw_slice() def reset_box(self, box, text): box.delete(0, len(box.get())) box.insert(0, text)
def run(self): # run the whole app self.root = tk.Tk() self.root2 = tk.Tk() self.root3 = tk.Tk() self.root.title('Keyboard Simulation') # keyboard setup self.canvas = tk.Canvas(self.root, width=self.winWidth, height=self.winHeight) self.canvas.pack(side=LEFT) # self.S = Scrollbar(self.root2) self.T = Text(self.root2, height=4, width=50) self.S.pack(side=RIGHT, fill=Y, expand=True) self.T.pack(side=LEFT, fill=Y, expand=True) #self.S.pack() #self.T.pack() self.S.config(command=self.T.yview) self.T.config(yscrollcommand=self.S.set) self.T.delete(1.0, END) self.T.insert(END, self.inputText) self.T.see(END) l = Label(self.root3, text="Hover time Limit:", state='disabled') l.pack() w = Spinbox(self.root3, from_=0, to=10) w.pack() w.delete(0, "end") w.insert(0, 4) l2 = Label(self.root3, text="Hover select progress:") l2.pack() self.progress = ttk.Progressbar(self.root3, orient="horizontal", length=200, mode="determinate") self.progress["value"] = 0 self.progress["maximum"] = 10 self.progress.pack() def hv_toggle(): if self.hv_btn.config('text')[-1] == "Hover Select: On": self.hv_btn.config(text="Hover Select: off") self.hoverOn = not self.hoverOn else: self.hv_btn.config(text="Hover Select: On") self.hoverOn = not self.hoverOn self.hv_btn = tk.Button(self.root3, text="Hover Select: On", command=hv_toggle) self.hv_btn.pack() def ck_toggle(): if self.ck_btn.config('text')[-1] == "Click Select: On": self.ck_btn.config(text="Click Select: off") self.clickOn = not self.clickOn else: self.ck_btn.config(text="Click Select: On") self.clickOn = not self.clickOn self.ck_btn = tk.Button(self.root3, text="Click Select: On", command=ck_toggle) self.ck_btn.pack() #self.hoverlimit = int(w.get()) if self.clickOn: self.root.bind('<Button-1>', self.clickEvent) def timerFired(): try: self.hoverlimit = int(w.get()) except: pass self.progress["value"] = self.progress[ "maximum"] * self.hoverDt / self.hoverlimit self.lightUpHovering() self.movementLogging() if self.hoverOn: self.hoverSelect() self.redrawAll() self.canvas.after(self.dt, timerFired) self.appStartTime = time.time() timerFired() self.root.protocol("WM_DELETE_WINDOW", self.exitEvent) self.root2.protocol("WM_DELETE_WINDOW", self.exitEvent) self.root3.protocol("WM_DELETE_WINDOW", self.exitEvent) self.root.mainloop() # This call BLOCKS self.root2.mainloop() self.root3.mainloop()