def test_get_from_int(self): v = DoubleVar(self.root, 1.23, "name") self.assertAlmostEqual(1.23, v.get()) self.root.globalsetvar("name", "3.45") self.assertAlmostEqual(3.45, v.get()) self.root.globalsetvar("name", "456") self.assertAlmostEqual(456, v.get())
def __init__(self, parent, value=0, unit=None, parameter_type='number'): # initialize the parameter either as a number or as text if parameter_type == 'number': self.variable = DoubleVar(parent, value) elif parameter_type == 'bool': self.variable = BooleanVar(parent, value) else: self.variable = StringVar(parent, value) self.unit = unit self.parameter_type = parameter_type
def valueCheck(): answer = False while answer == False: try: var_entry = DoubleVar() except: print("Erronous value !") answer = False else: answer = True
def entries(self): self.points = StringVar() self.alpha, self.beta, self.ro = DoubleVar(), DoubleVar(), DoubleVar() self.Q = IntVar() self.points_entry = Entry(self, textvariable=self.points) self.points_entry.place(y=135, x=25, width=250) self.alpha_entry = Entry(self, textvariable=self.alpha) self.alpha_entry.place(y=180, x=25, width=25) self.beta_entry = Entry(self, textvariable=self.beta) self.beta_entry.place(y=225, x=25, width=25) self.ro_entry = Entry(self, textvariable=self.ro) self.ro_entry.place(y=270, x=25, width=25) self.Q_entry = Entry(self, textvariable=self.Q) self.Q_entry.place(y=315, x=25, width=25) self.alpha.set(1) self.beta.set(6) self.ro.set(0.4) self.points.set("1 12 16 28 39 26 43") self.Q.set(100)
def __init__(self, modelProc, tick): self.modelProc = modelProc self.tick = tick self.queue = modelProc.getQueue() # ----------------- Model parameters ----------------- # Waiting time between two events self.refreshRate = DEFAULT_REFRESH_RATE # Elapsed time (in number of ticks) self.count = 0 # ------------------------ GUI ----------------------- # Main window self.window = Tk() self.window.title("Model Rendering") self.window.configure(bg=BG_COLOR) self.window.protocol("WM_DELETE_WINDOW", self.onClosing) # Main pane mainPane = PanedWindow(self.window, orient=HORIZONTAL, bg=BG_COLOR) mainPane.pack(side=TOP, expand=Y, fill=BOTH, pady=5, padx=5) # Canvas frame canvasFrame = LabelFrame(mainPane, text="Rendering", padx=10, pady=10, bg=BG_COLOR) mainPane.add(canvasFrame) self.canvas = Canvas(canvasFrame, width=CANVAS_X, height=CANVAS_Y, background="white") self.canvas.pack() # Parameters frame paramFrame = LabelFrame(mainPane, text="Simulation parameters",\ padx=20, pady=20, bg=BG_COLOR) mainPane.add(paramFrame) # ===> Refresh rate slider self.stepVar = DoubleVar(paramFrame, value=DEFAULT_REFRESH_RATE) slider = Scale(paramFrame, from_=0, to_=0.5, resolution=0.001, length=350, orient=VERTICAL,\ variable=self.stepVar, label="# Refresh rate", bg=BG_COLOR, bd=1) slider.bind("<ButtonRelease-1>", self.updateRate) slider.grid(row=1, column=1) # ===> Elapsed time self.timeLabel = Label(paramFrame, text="# Elapsed time (hours) :\n0", bg=BG_COLOR) self.timeLabel.grid(row=3, column=1) # Rows and columns configuration paramFrame.grid_columnconfigure(0, weight=1) paramFrame.grid_columnconfigure(1, weight=2) paramFrame.grid_columnconfigure(2, weight=1) paramFrame.grid_rowconfigure(0, weight=1) paramFrame.grid_rowconfigure(2, weight=2) paramFrame.grid_rowconfigure(4, weight=2)
def transfer(): """ Função para iniciar a transferência """ def threadFunction(): """ Função que será executada dentro de uma Thread para realizar a transferência sem causar danos à interface gráfica. """ try: self.fileTransfer.transfer(progressFunction) self.__progressBar.forget() self.__infoLabel.config(text="Transfer completed successfully.") Button(self.__window,text="Close",command=self.close,style="TButton").pack() except: self.__progressBar.forget() if self.__mode == FileTransfer.CLIENT: self.__infoLabel.config(text="A failure occurred during the transfer.") else: self.__infoLabel.config(text="Connection terminated.") Button(self.__window,text="Close",command=self.close,style="TButton").pack() # Destrói o botão para permitir o download downloadButton.destroy() # Cria um objeto de DoubleVar para o preenchimento da barra de progresso self.__variable = DoubleVar() self.__variable.set(0) # Cria uma barra de progresso para o usuário ter uma noção maior do andamento da transferência self.__progressBar = Progressbar( self.__window, variable=self.__variable, maximum=100, length=100*(int(self.screen_geometry[0]/100))-(self.__sep*2) ) self.__progressBar.pack() # Executa toda a transferência dentro de uma thread Thread(target=threadFunction).start()
def init_vmat(self): def load_open(): f = filedialog.askopenfilename() self.vmat_openimg.set(f) def load_dmlc(): f = filedialog.askopenfilename() self.vmat_dmlcimg.set(f) def analyze_vmat(): images = (self.vmat_openimg.get(), self.vmat_dmlcimg.get()) if self.vmat_test.get() == 'DRGS': v = vmat.DRGS(image_paths=images) else: v = vmat.DRMLC(image_paths=images) v.analyze(tolerance=self.vmat_tol.get()) fname = osp.join(self.vmat_dmlcimg.get().replace('.dcm', '.pdf')) v.publish_pdf(fname) self.vmat_pdf.set(fname) utilities.open_path(fname) self.vmat_tab = Frame(self.notebook) self.vmat_openimg = StringVar() self.vmat_dmlcimg = StringVar() self.vmat_test = StringVar(value='DRGS') self.vmat_tol = DoubleVar(value=1.5) self.vmat_pdf = StringVar() Button(self.vmat_tab, text='Load Open Image...', command=load_open).grid(column=1, row=1) Button(self.vmat_tab, text='Load DMLC Image...', command=load_dmlc).grid(column=1, row=3) Label(self.vmat_tab, textvariable=self.vmat_openimg).grid(column=1, row=2) Label(self.vmat_tab, textvariable=self.vmat_dmlcimg).grid(column=1, row=4) Label(self.vmat_tab, text='Test type:').grid(column=1, row=5) Combobox(self.vmat_tab, values=('DRGS', 'DRMLC'), textvariable=self.vmat_test).grid(column=2, row=5) Label(self.vmat_tab, text='Tolerance (%):').grid(column=1, row=6) Entry(self.vmat_tab, width=7, textvariable=self.vmat_tol).grid(column=2, row=6) Button(self.vmat_tab, text='Analyze', command=analyze_vmat).grid(column=1, row=8) Label( self.vmat_tab, text= 'Analysis will analyze the file(s) according to the settings, \nsave a PDF in the same directory as the original file location and then open it.' ).grid(column=1, row=9) Label(self.vmat_tab, text='Save file:').grid(column=1, row=10) Label(self.vmat_tab, textvariable=self.vmat_pdf).grid(column=1, row=11) self.notebook.add(self.vmat_tab, text='VMAT') for child in self.vmat_tab.winfo_children(): child.grid_configure(padx=10, pady=5)
def main(): """Sets up the UI for the calculator """ window = Tk() window.title("Laskin") calculator = Calculator() result_var = DoubleVar() ui = UI(window, calculator, result_var, note_service) ui.start() window.mainloop()
def __init__(self, notebook_page, caller): self.motors_frame = Frame(notebook_page, padding=10, relief=SUNKEN) self.caller = caller # an array of the execute buttons self.forward_buttons = [] self.reverse_buttons = [] # an array of the scale widgets self.motor_scales = [] # an array of the values for the scale widgets self.motor_values = [] self.directions = [] for x in range(0, 2): # set the mode label with an associated signal channel number l = Label(self.motors_frame, text=('Motor ' + str(x + 1) + ' Speed: ')) l.grid(row=x, column=0, padx=[20, 5], pady=[22, 0]) self.motor_values.append(DoubleVar()) motor_scale = Scale(self.motors_frame, variable=self.motor_values[x], orient='horizontal', troughcolor='white', resolution=0.01, from_=0.00, to=1.00) self.motor_scales.append(motor_scale) motor_scale.grid(row=x, column=1) b = Button(self.motors_frame, text='Move Forward', command=partial(self.move_forward, x)) self.forward_buttons.append(b) b.grid(row=x, column=2, pady=[22, 0], padx=[40, 40]) b = Button(self.motors_frame, text='Move Reverse', command=partial(self.move_reverse, x)) self.reverse_buttons.append(b) b.grid(row=x, column=3, pady=[22, 0]) self.motors_frame.grid(row=0, column=0, sticky='EW', columnspan=49, padx=125, pady=[50, 0])
def init_planar_imaging(self): def load_phan(): f = filedialog.askopenfilename() self.phan_file.set(f) def analyze_phan(): phantom = getattr(planar_imaging, self.phan_type.get())(self.phan_file.get()) phantom.analyze() name, _ = osp.splitext(self.phan_file.get()) fname = name + '.pdf' fname = utilities.file_exists(fname) phantom.publish_pdf(utilities.file_exists(fname)) self.phan_pdf.set(fname) utilities.open_path(fname) self.phan_tab = Frame(self.notebook) self.phan_file = StringVar() self.phan_pdf = StringVar() self.phan_locon = DoubleVar(value=0.1) self.phan_hicon = DoubleVar(value=0.5) self.phan_inver = BooleanVar(value=False) self.phan_type = StringVar(value='LeedsTOR') Button(self.phan_tab, text='Load planar phantom DICOM file...', command=load_phan).grid(column=1, row=1) Label(self.phan_tab, textvariable=self.phan_file).grid(column=1, row=2) Label(self.phan_tab, text='Phantom:').grid(column=1, row=3) Combobox(self.phan_tab, values=('LeedsTOR', 'LasVegas', 'StandardImagingQC3'), textvariable=self.phan_type).grid(column=2, row=3) Label(self.phan_tab, text='Low contrast threshold:').grid(column=1, row=4) Entry(self.phan_tab, width=7, textvariable=self.phan_locon).grid(column=2, row=4) Label(self.phan_tab, text='High contrast threshold:').grid(column=1, row=5) Entry(self.phan_tab, width=7, textvariable=self.phan_hicon).grid(column=2, row=5) Checkbutton(self.phan_tab, text='Force image inversion?', variable=self.phan_inver).grid(column=1, row=6) Button(self.phan_tab, text='Analyze', command=analyze_phan).grid(column=1, row=9) Label(self.phan_tab, text='Analysis will analyze the file(s) according to the settings, \nsave a PDF in the same directory as the original file location and then open it.').grid( column=1, row=10) Label(self.phan_tab, text='Save file:').grid(column=1, row=11) Label(self.phan_tab, textvariable=self.phan_pdf).grid(column=1, row=12) self.notebook.add(self.phan_tab, text='2D Phantoms') for child in self.phan_tab.winfo_children(): child.grid_configure(padx=10, pady=5)
def __init__(self, master): self.master = master master.title('Calculator') self.total = 0.0 self.entered_number = 0.0 self.total_label_text = DoubleVar() self.total_label_text.set(self.total) self.total_label = Label(master, textvariable=self.total_label_text) self.label = Label(master, text="Total:") vcmd = master.register(self.validate) # we have to wrap the command self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P')) self.add_button = Button(master, text="+", command=lambda: self.update("add")) self.subtract_button = Button(master, text="-", command=lambda: self.update("subtract")) self.reset_button = Button(master, text="Clear", command=lambda: self.update("reset")) self.multiply_button = Button(master, text="*", command=lambda: self.update("multiply")) # LAYOUT self.label.grid(row=0, column=0, sticky=W) self.total_label.grid(row=0, column=1, columnspan=2, sticky=E) self.entry.grid(row=1, column=0, columnspan=3, sticky=W + E) self.add_button.grid(row=2, column=0, sticky=W + E) self.subtract_button.grid(row=2, column=1, sticky=W + E) self.reset_button.grid(row=2, column=2, sticky=W + E) self.multiply_button.grid(row=3, column=1, sticky=W + E)
def initializeControls(self): ctrlFrame = Frame(self.tk) ctrlFrame.pack() self.openBtn = Button( ctrlFrame, text='打开', command=self.openFileCommand) self.openBtn.pack(side=TK_LEFT) self.playPauseBtn = Button( ctrlFrame, text='播放', command=self.playAndStopWaveCommand) self.playPauseBtn.pack(side=TK_LEFT) freqFrame = Frame(self.tk) freqFrame.pack() lb = Label(freqFrame, text='七弦频率') lb.pack(side=TK_LEFT) self.freq7Variable = DoubleVar(value=DefaultFreq7) self.freq7Entry = Entry( freqFrame, textvariable=self.freq7Variable) self.freq7Entry.pack(side=TK_LEFT) self.retuneBtn = Button( freqFrame, text='调弦设置', command=self.retuneCommand) self.retuneBtn.pack(side=TK_LEFT) chordFrame = Frame(self.tk) chordFrame.pack() lb2 = Label(chordFrame, text='当前使用的弦:') lb2.pack(side=TK_LEFT) possibleChords = ('一', '二', '三', '四', '五', '六', '七') self.chordList = Combobox( chordFrame, values=possibleChords, state='readonly') self.chordList.current(6) self.chordList.pack(side=TK_LEFT) self.chordList.bind('<<ComboboxSelected>>', self.chordChanged) self.analyzeBtn = Button( chordFrame, text='分析指迹', command=self.analyzeCommand) self.analyzeBtn.pack()
def __init__(self, container, *args, **kwargs): """ Constructor. :param tkinter.Frame container: reference to container frame :param args: optional args to pass to Frame parent class :param kwargs: optional kwargs for value ranges, or to pass to Frame parent class """ self._bpsrate_rng = kwargs.pop("bpsrates", BPSRATE_RNG) self._databits_rng = kwargs.pop("databits", DATABITS_RNG) self._stopbits_rng = kwargs.pop("stopbits", STOPBITS_RNG) self._parity_rng = kwargs.pop("parities", PARITY_RNG) self._timeout_rng = kwargs.pop("timeouts", TIMEOUT_RNG) self._preselect = kwargs.pop("preselect", ()) self._readonlybg = kwargs.pop("readonlybackground", BGCOL) Frame.__init__(self, container, *args, **kwargs) self._show_advanced = False self._status = DISCONNECTED self._ports = () self._port = StringVar() self._port_desc = StringVar() self._bpsrate = IntVar() self._databits = IntVar() self._stopbits = DoubleVar() self._parity = StringVar() self._rtscts = IntVar() self._xonxoff = IntVar() self._timeout = StringVar() self._img_refresh = ImageTk.PhotoImage(Image.open(ICON_REFRESH)) self._img_expand = ImageTk.PhotoImage(Image.open(ICON_EXPAND)) self._img_contract = ImageTk.PhotoImage(Image.open(ICON_CONTRACT)) self._body() self._do_layout() self._get_ports() self._attach_events() self.reset()
def add_vectors(self): self.clear() num_vectors = DoubleVar() dimension = DoubleVar() num_vectors.set(2) dimension.set(2) num_vectors_entry = Entry(mainframe, width=5, textvariable=num_vectors, font=MATRIX_FONT) num_vectors_entry.grid(column=1, row=2, sticky=W) dimension_entry = Entry(mainframe, width=5, textvariable=dimension, font=MATRIX_FONT) dimension_entry.grid(column=1, row=3, sticky=W) num_vectors_label = Label(mainframe, text="vectors", font=LABEL_FONT) num_vectors_label.grid(column=2, row=2, sticky=E) dimension_label = Label(mainframe, text="dimensions", font=LABEL_FONT) dimension_label.grid(column=2, row=3, sticky=E) def add_vectors_input(): try: num_vectors_value = num_vectors.get() dimension_value = dimension.get() if 2 <= num_vectors_value <= 15 and 2 <= dimension_value <= 15 and num_vectors_value % 1 == 0 and dimension_value % 1 == 0: self.vectors_input(int(num_vectors_value), int(dimension_value), ADD_VECTORS) else: raise ValueError except ValueError: messagebox.showerror( "Error", "Number of vectors or dimensions must be between 2 and 15") except TclError: messagebox.showerror("Error", "Invalid input") return submit = Button(mainframe, text="Submit", command=add_vectors_input, font=LABEL_FONT) submit.grid(column=1, row=4, columnspan=2, sticky=W) dimension_header = Label( mainframe, text="Enter the number of vectors to add and their dimensions:", font=LABEL_FONT) dimension_header.grid(column=1, row=1, columnspan=FILL, sticky=W)
def __init__(self, master): super().__init__(master) self.master.title("Chat Player") self.pack(fill=BOTH, expand=True) # Variables self.font_size_var: IntVar = IntVar(value=DEFAULT_FONT_SIZE) self.time_display_var: StringVar = StringVar(value='0:00:00') self.speed_display_var: StringVar = StringVar(value='1.00') self.seconds_elapsed_var: DoubleVar = DoubleVar(value=0) self.autoscroll_var: BooleanVar = BooleanVar(value=True) self.paused_var: BooleanVar = BooleanVar(value=True) self.always_on_top_var: BooleanVar = BooleanVar(value=False) self.pause_button_text_var: StringVar = StringVar(value='⏵') self.search_regex_var: BooleanVar = BooleanVar(value=False) self.search_case_sensitive_var: BooleanVar = BooleanVar(value=False) self.search_count_var: IntVar = IntVar() # Style self.chat_font = Font(family="Helvetica", size=self.font_size_var.get()) # Gui # self.chat_frame_container = Scrollable(self, outer_kwargs={'padding': 0}) # self.chat_frame_container.pack(side=TOP, fill=BOTH, expand=True) # self.chat_frame = self.chat_frame_container.frame self.chat_text = ChatText(self, undo=False, wrap=WORD, padx=6) self.chat_text.search_frame.regex_check.configure(variable=self.search_regex_var) self.chat_text.search_frame.case_check.configure(variable=self.search_case_sensitive_var) self.options_frame = OptionsFrame(self, pad=2) self.options_frame.autoscroll_check.configure(variable=self.autoscroll_var) self.options_frame.font_size_label.configure(textvariable=self.font_size_var) self.speed_control_frame = self.options_frame.speed_control_frame self.speed_control_frame.speed_label.configure(textvariable=self.speed_display_var) self.time_frame = TimeFrame(self, height=150) self.time_frame.play_pause_button.configure(textvariable=self.pause_button_text_var) self.time_frame.time_elapsed_label.configure(textvariable=self.time_display_var) self.time_frame.time_scale.configure(variable=self.seconds_elapsed_var) self.time_frame.pack(side=BOTTOM, fill=X, anchor=S) Separator(self, orient=HORIZONTAL).pack(side=BOTTOM, anchor=W, fill=X) self.options_frame.pack(side=BOTTOM, fill=X, anchor=S) self.options_frame.always_on_top_check.configure(variable=self.always_on_top_var) Separator(self, orient=HORIZONTAL).pack(side=BOTTOM, fill=X, anchor=W) # Separator(self, orient=HORIZONTAL).pack(side=TOP, anchor=N, fill=X, pady=(5, 0), ipady=0) self.chat_text.pack(side=TOP, fill=BOTH, expand=True) self.master.attributes('-topmost', True) self.master.attributes('-topmost', False)
def create_buttons(self, parent, create_sliders): self.jso = Button(parent, text="Import from .json", command=self.import_json) self.jso.grid(row=0, column=0, sticky="w") self.sav = Button(parent, text="Import from .sav", command=self.import_sav) self.sav.grid(row=0, column=1, sticky="w") self.scales = [] # create sliders if create_sliders: self.jso.grid_configure(row=0, column=0) self.sav.grid_configure(row=1, column=0) resources = [ 'minerals', 'energy', 'physics', 'society', 'engineering' ] colors = ["red", "yellow", "blue", "green", "orange"] for i in range(len(resources)): var = DoubleVar() var.set(500) callback = lambda event, tag=i: self.weight_update(event, tag) b = Scale(parent, from_=1, to=1000, variable=var, length=135, orient='horizontal', troughcolor=colors[i], resolution=1, label=resources[i], showvalue=0) b.grid(row=2 + i, column=0, sticky="w") b.bind('<ButtonRelease-1>', self.redraw) # redraw when user release scale self.scales.append(var)
def __init__(self, master,requesthandler,SeasonInfo): clearscreen() Frame.__init__(self,master) self.pack(expand=YES,fill=BOTH) self.master = master self.master.protocol("WM_DELETE_WINDOW",on_close) self.requesthandler = requesthandler self.SeasonInfo = SeasonInfo # (seasonname, season info tuple) self.Session_ID = self.SeasonInfo[1] # season info tuple self.checkincrement = IntVar() self.checkincrement.set(120) self.devicecheckcount = IntVar() self.devicecheckcount.set(0) self.AutoRegisterEnabled = False self.ServerTimeOffset = datetime.timedelta(0,0,0) self.RequestLatency = DoubleVar() OptionFrame = Frame(self) OptionFrame.pack(side=TOP,fill=X) Button(OptionFrame,text="뒤로",command=lambda:SeasonScreen(self.master,self.requesthandler)).pack(side=RIGHT) Label(OptionFrame,text=self.SeasonInfo[0]+" "+str(SeasonInfo[1])).pack(anchor=W,fill=X) self.PopulateClass()
def vectors_input(self, num_vectors, dimensions, func): self.clear() Label(mainframe, text="Enter vectors:", font=LABEL_FONT).grid(column=1, row=1, columnspan=FILL, sticky=W) entries = [] def process_input(): vectors = [] try: for r in range(num_vectors): vectors.append([]) for c in range(dimensions): vectors[r].append(entries[r][c].get()) except TclError: messagebox.showerror("Error", "Invalid input") return if func == ADD_VECTORS: add_vectors_solver = AddVectorsSolver(vectors) add_vectors_solver.calculate() elif func == DOT_PRODUCT: dot_product_solver = DotProductSolver(vectors) dot_product_solver.calculate() elif func == CROSS_PRODUCT: cross_product_solver = CrossProductSolver(vectors) cross_product_solver.calculate() for r in range(num_vectors): entries.append([]) Label(mainframe, text="[", font=MATRIX_FONT).grid(column=1, row=r + 2, sticky=W) for c in range(dimensions): entries[r].append(DoubleVar()) entries[r][c].set("") Entry(mainframe, width=4, textvariable=entries[r][c], font=MATRIX_FONT).grid(column=c + 2, row=r + 2, sticky=W) Label(mainframe, text="]", font=MATRIX_FONT).grid(column=dimensions + 2, row=r + 2, sticky=W) Button(mainframe, text="Submit", command=process_input, font=LABEL_FONT).grid(column=1, row=len(entries) + 2, columnspan=FILL, sticky=W)
def inverse(self, func): self.clear() rows = DoubleVar() rows.set(2) row_entry = Entry(mainframe, width=5, textvariable=rows, font=MATRIX_FONT) row_entry.grid(column=1, row=2, sticky=W) row_label = Label(mainframe, text="rows and columns", font=LABEL_FONT) row_label.grid(column=2, row=2, sticky=E) def inverse_input(): try: row_value = rows.get() if 2 <= row_value <= 7 and row_value % 1 == 0: self.matrix_input(int(row_value), int(row_value), func) else: raise ValueError except ValueError: messagebox.showerror("Error", "Matrix must be between 2x2 and 7x7") except TclError: messagebox.showerror("Error", "Invalid input") return submit = Button(mainframe, text="Submit", command=inverse_input, font=LABEL_FONT) submit.grid(column=1, row=3, columnspan=2, sticky=W) dimension_header = Label( mainframe, text="Enter the dimensions of the matrix (2x2 - 7x7):", font=LABEL_FONT) dimension_header.grid(column=1, row=1, columnspan=4, sticky=W)
def systems(self): self.clear() var = DoubleVar() eq = DoubleVar() var.set(2) eq.set(2) var_entry = Entry(mainframe, width=5, textvariable=var, font=MATRIX_FONT) var_entry.grid(column=1, row=2, sticky=W) eq_entry = Entry(mainframe, width=5, textvariable=eq, font=MATRIX_FONT) eq_entry.grid(column=1, row=3, sticky=W) var_label = Label(mainframe, text="variables (2-10)", font=LABEL_FONT) var_label.grid(column=2, row=2, sticky=E) eq_label = Label(mainframe, text="equations (2-10)", font=LABEL_FONT) eq_label.grid(column=2, row=3, sticky=E) def systems_input(): try: var_value = var.get() eq_value = eq.get() if 2 <= var_value <= 10 and 2 <= eq_value <= 10 and var_value % 1 == 0 and eq_value % 1 == 0: self.matrix_input(int(eq_value), int(var_value) + 1, SYSTEMS) else: raise ValueError except ValueError: messagebox.showerror( "Error", "Number of variables or equations must be between 2 and 10" ) except TclError: messagebox.showerror("Error", "Invalid input") return submit = Button(mainframe, text="Submit", command=systems_input, font=LABEL_FONT) submit.grid(column=1, row=4, columnspan=2, sticky=W) dimension_header = Label( mainframe, text="Enter the number of variables and equations:", font=LABEL_FONT) dimension_header.grid(column=1, row=1, columnspan=4, sticky=W)
def dot_product(self): self.clear() dimension = DoubleVar() dimension.set(2) dimension_entry = Entry(mainframe, width=5, textvariable=dimension, font=MATRIX_FONT) dimension_entry.grid(column=1, row=2, sticky=W) dimension_label = Label(mainframe, text="dimensions", font=LABEL_FONT) dimension_label.grid(column=2, row=2, sticky=E) def dot_product_input(): try: dimension_value = dimension.get() if 2 <= dimension_value <= 15 and dimension_value % 1 == 0: self.vectors_input(2, int(dimension_value), DOT_PRODUCT) else: raise ValueError except ValueError: messagebox.showerror( "Error", "Number of dimensions must be between 2 and 15") except TclError: messagebox.showerror("Error", "Invalid input") return submit = Button(mainframe, text="Submit", command=dot_product_input, font=LABEL_FONT) submit.grid(column=1, row=4, columnspan=FILL, sticky=W) dimension_header = Label( mainframe, text="Enter the number of dimensions for the vectors:", font=LABEL_FONT) dimension_header.grid(column=1, row=1, columnspan=FILL, sticky=W)
def __init__(self, window, text=' ', instance=str): if instance == str: self.variable = StringVar(window.root, value=text) elif instance == float: self.variable = DoubleVar(window.root, value=text) elif instance == int: self.variable = IntVar(window.root, value=text) elif instance == bool: self.variable = BooleanVar(window.root, value=text) widget = Label(window.main_frame, textvar=self.variable) HOPSWidget.__init__(self, window, widget, 'Label')
def show_entries(_, title: str, temperature: tk.DoubleVar, values_entry: tk.Text): title_str = title.format(temperature.get()) try: mbox.showinfo( "Extra Point Viewer", "{}\n{}".format( title_str, "\n".join("{}. {}".format(i + 1, x.strip()) for i, x in enumerate( values_entry.get(1.0, tk.END).split(","))))) except ValueError: mbox.showwarning( title_str, "Text in the field is malformed, please update the values.")
def __init__(self, parent, matches: Matches, column=1, row=1): super().__init__(parent, text=" Manual input ") self._matches = matches self._var_title = StringVar() self._var_ratio_1 = DoubleVar() self._var_ratio_x = DoubleVar() self._var_ratio_2 = DoubleVar() self.grid(column=column, row=row, sticky=NSEW, padx=PAD_X, pady=PAD_Y) self.create_widgets()
def __init__(self, control, *args, **kwargs): Frame.__init__(self, *args, **kwargs) self.config(padx=2) self.queue = Queue() self.control = control self.disabledWhileRunning = [] self.formulae = list(map(lambda t: StringVar(self, t), ["x/22.5+4", "50-x*50/180"])) self.executionTime = DoubleVar(self, "360") self.programSpeed = IntVar(self, "292") self.maxTravel = IntVar(self, "-200000") self.loadSettings() self.createWidgets() self.thread = None
def __init__(self, simil_dict: str): ''' Constructor. ''' # set the brainy model self.modelo = utils.brainy.getPredictionModel( utils.brainy.Model.MobileNet) # Window self.raiz = Tk() self.raiz.title("Colibri Lime") if 'nt' == os.name: self.raiz.iconbitmap(r'img/icon.ico') else: self.raiz.iconphoto( True, PhotoImage(file=os.path.join('img', "icon.png"))) # Interface control variables self.__kernel_size = IntVar(value=4) self.__max_dist = IntVar(value=200) self.__ratio = DoubleVar(value=0.2) self.__num_perturb = IntVar(value=150) self.__kernel_width = DoubleVar(value=0.25) self.__num_top_features = IntVar(value=4) # Windows controls self.createControls() # Simil data self._simil_data, _ = self._load_simil_dict_file_data(simil_dict) # Show controls self.showControl() # start the main window loop self.raiz.mainloop()
def __init__(self, notebook_page, caller): self.drive_outputs_frame = Frame(notebook_page, padding=10, relief=SUNKEN) self.caller = caller # an array of the execute buttons self.execute_buttons = [] # an array of the scale widgets self.drive_scales = [] # an array of the values for the scale widgets self.drive_values = [] for x in range(0, 4): # set the mode label with an associated signal channel number # noinspection PyPep8 l = Label(self.drive_outputs_frame, text=('Drive ' + str(x + 1) + ' Value:')) l.grid(row=x, column=0, padx=[20, 5], pady=[22, 0]) self.drive_values.append(DoubleVar()) drive_scale = Scale(self.drive_outputs_frame, variable=self.drive_values[x], orient='horizontal', troughcolor='white', resolution=0.01, from_=0.00, to=1.00) self.drive_scales.append(drive_scale) drive_scale.grid(row=x, column=1) b = Button(self.drive_outputs_frame, text='Set Drive ' + str(x + 1) + ' Value', command=partial(self.set_drive_value, x)) self.execute_buttons.append(b) b.grid(row=x, column=2, pady=[22, 0], padx=40) self.drive_outputs_frame.grid(row=0, column=0, sticky='EW', columnspan=49, padx=[170, 0], pady=[20, 0])
def buildFrame(self, params): """ This function constructs frames inside the container and fills the frames with entry fields and labels. The params variable is a dictionary of dictionaries with the structure: {id:[{'name': '', 'value':'', 'variable':'', 'tip':''}} where 'id' is an integer and stores the algorithm id, 'name' is a string and stores the name to be used as a label. 'value' stores the value to be set in the entry box. 'variable' stores a mapping to the model object. 'tip' stores the tooltip to be displayed. """ self._clearFrame() self.frame_elements = [] n_inputs = len(params) n_subframes = (int(n_inputs / self.inputs_per_subframe) + int( (n_inputs % self.inputs_per_subframe))) idx = 0 for n in range(n_subframes): subframe = tk.Frame(self.container) subframe.pack(side=LEFT, anchor='s') for m in range(self.inputs_per_subframe): name = params[idx]['label'] self.frame_elements += [{ 'label': tk.Label(subframe, text=name, wraplength=self.wrap, justify=CENTER) }] self.frame_elements[idx]['label'].pack(side=TOP) self.frame_elements[idx]['tk_var'] = DoubleVar() if ((type(params[idx]['value']) == int) | (type(params[idx]['value']) == float)): self.frame_elements[idx]['tk_var'].set( params[idx]['value']) self.frame_elements[idx]['entry'] = tk.Entry( subframe, width=self.entry_width, textvariable=self.frame_elements[idx]['tk_var']) self.frame_elements[idx]['entry'].pack(side=TOP) self.frame_elements[idx]['variable'] = params[idx]['variable'] txt = params[idx]['tip'] CreateToolTip(self.frame_elements[idx]['label'], futures.ThreadPoolExecutor(max_workers=1), txt) if ((idx + 1) in range(len(params))): idx += 1 else: break
def _init_vars(self): """ Initialise double variables for entry widgets""" # initialise variables for entry widgets self._food = DoubleVar() self._entertainment = DoubleVar() self._fitness = DoubleVar() self._rent = DoubleVar() self._shopping = DoubleVar() self._transport = DoubleVar() return
def __init__(self, master=None): super().__init__(master) self.master = master self.grid(padx=4, pady=0) self.window_width = 1850 self.window_height = 900 self._geom = '{x}x{y}+0+0'.format(x=self.window_width, y=self.window_height) self.master.geometry(self._geom) self.image_size = 450 self.canvases = dict() self.scale_value = DoubleVar() self.create_window() self.create_widgets()
def set_offset(self, label): var = self.input_var step = self.step res = self.res offset = self.offset def update_other_label(*args): value = var.get() multiplier = round(value * step, res) product = round(offset + multiplier - step, res) input_var_mult.set(product) self.input_var.trace_add("write", update_other_label) input_var_mult = DoubleVar() label.config(textvariable=input_var_mult)
def Dropdown(self, options, x, y, value=None, **kw): kw = var_check(kw) if value is not None: value1 = value else: value1 = options[0] if isinstance(value1, str): self.widget_frame.value1 = StringVar() else: self.widget_frame.value1 = DoubleVar() self.widget_frame.value1.set(value1) self.widget_frame.dropdown_options = OptionMenu( self.widget_frame, self.widget_frame.value1, *options) self.widget_frame.dropdown_options.place(relx=x, rely=y, anchor=kw['anchor'], relwidth=kw['relwidth'], relheight=kw['relheight']) return self.widget_frame.value1
def __init__(self, root, default_folder=""): ttk.Frame.__init__(self, root, padding="3 3 12 12") self.default_folder = default_folder logging.debug("Create main frame") #mainframe = ttk.Frame(root, padding="3 3 12 12") self.grid(column=0, row=0, sticky=(N, W, E, S)) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) logging.debug("Create variable") self.filepath_ctf = StringVar() self.image_folder = StringVar() self.vh_ratio = DoubleVar(value=0.76200) self.results_text = StringVar() self.pcx = 0.0 self.pcy = 0.0 self.dd = 0.0 logging.debug("Create ctf components") ctf_entry = ttk.Entry(self, width=80, textvariable=self.filepath_ctf) ctf_entry.grid(column=2, row=1, sticky=(W, E)) ttk.Button(self, text="Select CTF file", command=self.open_ctf_file).grid(column=3, row=1, sticky=W) logging.debug("Create image folder components") image_entry = ttk.Entry(self, width=80, textvariable=self.image_folder) image_entry.grid(column=2, row=2, sticky=(W, E)) ttk.Button(self, text="Select Image folder", command=self.open_image_folder).grid(column=3, row=2, sticky=W) logging.debug("Create vh_ratio components") ttk.Label(self, text="VH Ratio").grid(column=1, row=3, sticky=(W, E)) image_entry = ttk.Entry(self, width=10, textvariable=self.vh_ratio) image_entry.grid(column=2, row=3, sticky=(W, E)) ttk.Button(self, text="Prepare data", command=self.prepare_data, width=80).grid(column=2, row=4, sticky=W) results_label = ttk.Label(self, textvariable=self.results_text, state="readonly") results_label.grid(column=2, row=5, sticky=(W, E)) for child in self.winfo_children(): child.grid_configure(padx=5, pady=5) ctf_entry.focus()
def __init__(self): Tk.__init__(self) self.title("Nim") self.kamen = PhotoImage(file = './kamen.ppm') self.nacin = BooleanVar() #0 is ai, 1 is human self.nacin = 0 self.zahtevnost = DoubleVar() #0, 1, 2 are (easy, medium hard) self.vnos_nacina = Entry(self, textvariable = "način") ni = Button(self, text="Nova igra", command=self.nova_igra) ni.grid(column = 2, row = 0) self.platno = Canvas(self, width=700, height = 500, bg='white') self.platno.grid(row= 3, column = 0, columnspan=4) self.vrhovi = [] self.z1 = Radiobutton(self, text = "Skoraj Nepremagljivo!", variable = self.zahtevnost, value=1) self.z2 = Radiobutton(self, text = "Srednje zahtevno ", variable = self.zahtevnost, value=2) self.z3 = Radiobutton(self, text = "Za majhne punčke ", variable = self.zahtevnost, value=3) self.z1.grid(column = 0, row = 0) self.z2.grid(column = 0, row = 1) self.z3.grid(column = 0, row = 2) self.z1.select() self.konec = Label() self.mainloop()
def __init__(self, pype, toplevel=False, **runargs): ''' ''' self.pype = pype self.runargs = runargs self.toplevel = toplevel self.sweep_result = {} self.powerVar = DoubleVar(value=20) #dBm self.set_power_BoolVar = BooleanVar(value=True) self.start_freq_Var = DoubleVar(value=26350) #MHz self.stop_freq_Var = DoubleVar(value=26600) #MHz self.start_search_freq_Var = DoubleVar(value=26450) #MHz self.stop_search_freq_Var = DoubleVar(value=26510) #MHz self.sweep_time_Var = DoubleVar(value=15) #s self.num_points_Var = IntVar(value=400) #ms self.spanVar = DoubleVar(value=100) self.stepVar = DoubleVar(value=4) #self.fit_channel_Var = StringVar(value='xdata') self.result_str_Var = StringVar(value='') self._BuildGui()
class dpph_measurement: ''' ''' def __init__(self, pype, toplevel=False, **runargs): ''' ''' self.pype = pype self.runargs = runargs self.toplevel = toplevel self.sweep_result = {} self.powerVar = DoubleVar(value=20) #dBm self.set_power_BoolVar = BooleanVar(value=True) self.start_freq_Var = DoubleVar(value=26350) #MHz self.stop_freq_Var = DoubleVar(value=26600) #MHz self.start_search_freq_Var = DoubleVar(value=26450) #MHz self.stop_search_freq_Var = DoubleVar(value=26510) #MHz self.sweep_time_Var = DoubleVar(value=15) #s self.num_points_Var = IntVar(value=400) #ms self.spanVar = DoubleVar(value=100) self.stepVar = DoubleVar(value=4) #self.fit_channel_Var = StringVar(value='xdata') self.result_str_Var = StringVar(value='') self._BuildGui() def _BuildGui(self): ''' Dpph popup window ''' row = 0 ################################################################## # Lockin Scan Label(self.toplevel, text='Input Power' ).grid(row=row, column=0, sticky='ew') Entry(self.toplevel, textvariable=self.powerVar ).grid(row=row, column=1, sticky='ew') Label(self.toplevel, text='[dBm]', justify='left' ).grid(row=row, column=2, sticky='w') Checkbutton(self.toplevel, text="Don't Change", variable=self.set_power_BoolVar).grid(row=row, column=3) row += 1 Label(self.toplevel, text='Scan Frequency Range' ).grid(row=row, column=0, sticky='ew') Entry(self.toplevel, textvariable=self.start_freq_Var ).grid(row=row, column=1, sticky='ew') Entry(self.toplevel, textvariable=self.stop_freq_Var ).grid(row=row, column=2, columnspan=2, sticky='ew') Label(self.toplevel, text='[MHz]').grid(row=row, column=4, sticky='w') row += 1 Label(self.toplevel, text='Sweep Time' ).grid(row=row, column=0, sticky='ew') Entry(self.toplevel, textvariable=self.sweep_time_Var ).grid(row=row, column=1, sticky='ew') Label(self.toplevel, text='[s]').grid(row=row, column=2, sticky='w') row += 1 Label(self.toplevel, text='Number of Points' ).grid(row=row, column=0, sticky='ew') Entry(self.toplevel, textvariable=self.num_points_Var ).grid(row=row, column=1, sticky='ew') row += 1 Button(self.toplevel, text='take data', command=self._CollectSweep ).grid(row=row, column=0) row += 1 Label(self.toplevel, text='-'*50).grid(row=row, column=0, columnspan=4, sticky='ew') row += 1 ################################################################## # Resonance Search Label(self.toplevel, text='Search Frequency Range' ).grid(row=row, column=0, sticky='ew') Entry(self.toplevel, textvariable=self.start_search_freq_Var ).grid(row=row, column=1, sticky='ew') Entry(self.toplevel, textvariable=self.stop_search_freq_Var ).grid(row=row, column=2, columnspan=2, sticky='ew') Label(self.toplevel, text='[MHz]').grid(row=row, column=4, sticky='w') row += 1 #ch_options = ['xdata', 'ydata'] #OptionMenu(self.toplevel, self.fit_channel_Var, *ch_options # ).grid(row=row, column=0, rowspan=2, sticky='ew') Button(self.toplevel, text='find resonance', command=self._FindResonance ).grid(row=row, column=1, rowspan=2, sticky='ew') Label(self.toplevel, textvariable=self.result_str_Var ).grid(row=row, column=2, rowspan=2, columnspan=3, sticky='ew') row += 2 Button(self.toplevel, text='Dump To json', command=self._SaveJson ).grid(row=row, column=0) Button(self.toplevel, text='Save Image', command=self._SaveFigure ).grid(row=row, column=1) Button(self.toplevel, text='Log DPPH', command=self._LogDPPH ).grid(row=row, column=2) self._SetupPlot(row=0, column=5) def _SetupPlot(self, row, column): ''' Initialize the plot in the gui ''' self.figure = Figure() self.figure.subplots_adjust(left=0.15, bottom=0.2) self.subfigure = self.figure.add_subplot(1, 1, 1) self.subfigure.plot([0], [0]) self.subfigure.plot([0], [0]) self.subfigure.set_xlabel('Freq [MHz]') self.canvas = FigureCanvasTkAgg(self.figure, master=self.toplevel) self.canvas.show() self.canvas.get_tk_widget().grid(row=row, column=column, rowspan=10) def _CollectSweep(self): ''' ''' tmp_power = self.powerVar.get() if self.set_power_BoolVar.get(): tmp_power = False while True: sweep = _GetSweptVoltages(pype=self.pype, start_freq=self.start_freq_Var.get(), stop_freq=self.stop_freq_Var.get(), sweep_time=self.sweep_time_Var.get(), power=tmp_power, num_points=self.num_points_Var.get()) self.sweep_result = sweep.copy() freqdata = array(sweep['frequency_curve']) magdata = sweep['amplitude_curve'] if type(magdata[0]) is unicode: print('Warning: _GetSweptVoltages failed;') print('magdata:') print(magdata) print('Acquiring data again...') elif type(magdata[0]) is int: break if not sweep['frequencies_confirmed']: showwarning('Warning', 'Communication with lockin amp failed. Frequencies data may be wrong') magdata = magdata - mean(magdata) #ydata = sweep['y_curve'] print('freq range is ', min(freqdata), ' to ', max(freqdata)) #xdata = sweep['x_curve'] y_del = max((max(magdata) - min(magdata)) * .05, 1) self.subfigure.set_xlim(left=freqdata[0], right=freqdata[-1]) self.subfigure.set_ylim(bottom=(min(magdata) - y_del), top=(max(magdata) + y_del)) line = self.subfigure.get_lines()[0] line.set_xdata(array(freqdata)) line.set_ydata(array(magdata)) line.set_label('lockin output') #line = self.subfigure.get_lines()[1] #line.set_xdata(array(freqdata)) #line.set_ydata(array(ydata)) #line.set_label('y output') self.figure.legends = [] self.figure.legend(*self.subfigure.get_legend_handles_labels()) self.figure.legends[0].draggable(True) self.canvas.draw() self.canvas.show() print('Searching for resonance...') self._FindResonance() def _FindResonance(self): ''' ''' #if self.fit_channel_Var.get() == 'xdata': # line = self.subfigure.get_lines()[0] #elif self.fit_channel_Var.get() == 'ydata': # line = self.subfigure.get_lines()[1] line = self.subfigure.get_lines()[0] #else: # raise ValueError('not a valid dataset selection') xdata = line.get_xdata() ydata = line.get_ydata() fit = _FindFieldFFT(min_freq=self.start_search_freq_Var.get(), max_freq=self.stop_search_freq_Var.get(), freq_data=xdata, volts_data=ydata) outline = self.subfigure.get_lines()[1] factor = max(ydata) / max(fit['result']) scaled_data = [val * factor for val in fit['result']] scaled_data = scaled_data - mean(scaled_data) outline.set_xdata(fit['freqs']) outline.set_ydata(scaled_data) outline.set_label('filter result') self.figure.legends = [] self.figure.legend(*self.subfigure.get_legend_handles_labels()) self.figure.legends[0].draggable(True) self.canvas.draw() self.canvas.show() res_freq = max(zip(fit['result'], fit['freqs']))[1] res_unct = fit['freqs'][1] - fit['freqs'][0] print('resonance found at:', res_freq, 'MHz') print('err is:', res_unct) geff = 2.0036 chargemass = 1.758e11 freq_to_field = 4 * pi * 10 ** 7 / (geff * chargemass) res_field = freq_to_field * res_freq res_field_unct = freq_to_field * res_unct print('for a field of', res_field) print('field unct of', res_field_unct) self.result_str_Var.set('{:.4E} +/- {:.1E} MHz \n({:.4E} +/- {:.1E} kG)'.format( res_freq, res_unct, res_field, res_field_unct)) self.sweep_result.update({'res_freq': res_freq, 'res_freq_unct': res_unct, 'res_field': res_field, 'res_field_unct': res_field_unct}) def _SaveJson(self): ''' ''' if not self.sweep_result: print('no result stored') return outfile = asksaveasfile(defaultextension='.json') dump(self.sweep_result, outfile, indent=4) outfile.close() def _SaveFigure(self): ''' ''' file_extensions = [('vectorized', '.eps'), ('adobe', '.pdf'), ('image', '.png'), ('all', '.*')] outfile = asksaveasfilename(defaultextension='.pdf', filetypes=file_extensions) self.figure.savefig(outfile) def _LogDPPH(self): if not self.sweep_result: print('no dpph_result stored') return result = { 'uncal': self.sweep_result['res_freq'], 'uncal_err': self.sweep_result['res_freq_unct'], 'uncal_units': 'MHz', 'cal': self.sweep_result['res_field'], 'cal_err': self.sweep_result['res_field_unct'], 'cal_units': 'kG', } dpph_result = {'uncal_val': ' '.join([str(result['uncal']), '+/-', str(result['uncal_err']), result['uncal_units']]), 'cal_val': ' '.join([str(result['cal']), '+/-', str(result['cal_err']), result['cal_units']]), 'timestamp': datetime.utcnow()} self.pype.LogValue(sensor='dpph_field', **dpph_result) print('dpph_result stored')
def test_default(self): v = DoubleVar(self.root) self.assertEqual(0.0, v.get())
def __init__(self, master, par=False): """ GUI for selecting default parameters - will write parameters to file \ of users choosing. :type master: Tk :param master: Tkinter window :type par: EQcorrscanParameters :param par: Default parameters to start-up with. """ from tkinter import Label, Button, Entry, DoubleVar, StringVar, IntVar from tkinter import BooleanVar, OptionMenu, Checkbutton import tkMessageBox from eqcorrscan.utils import parameters from obspy import UTCDateTime import warnings # Set the default par, only if they don't already exist. if not par: par = parameters.EQcorrscanParameters([''], 2, 10, 4, 100, 2, '1900-01-01', '2300-01-01', '', 'seishub', 4, False, '', 'jpg', False, 8, 'MAD', 6) # Callback functions for all variables (ugly) def update_template_names(*args): par.template_names = [name.strip() for name in template_names.get().split(',')] template_names.set(', '.join(par.template_names)) def update_lowcut(*args): par.lowcut = lowcut.get() lowcut.set(par.lowcut) def update_highcut(*args): par.highcut = highcut.get() if par.highcut >= 0.5 * par.samp_rate: msg = ('Highcut must be less than the Nyquist, setting to ' + str((par.samp_rate / 2.0) - 1)) tkMessageBox.showwarning(title="Nyquist error", message=msg) par.highcut = (par.samp_rate / 2.0) - 1 highcut.set(par.highcut) def update_filt_order(*args): par.filt_order = filt_order.get() filt_order.set(par.filt_order) def update_samp_rate(*args): par.samp_rate = samp_rate.get() if par.highcut >= 0.5 * par.samp_rate: msg = ('Highcut must be less than the Nyquist, setting to ' + str((par.samp_rate / 2.0) - 1)) tkMessageBox.showwarning(title="Nyquist error", message=msg) par.highcut = (par.samp_rate / 2.0) - 1 highcut.set(par.highcut) samp_rate.set(par.samp_rate) def update_debug(*args): par.debug = debug.get() debug.set(par.debug) def update_startdate(*args): par.startdate = UTCDateTime(startdate.get()) startdate.set(str(par.startdate)) def update_enddate(*args): par.enddate = UTCDateTime(enddate.get()) enddate.set(str(par.enddate)) def update_archive(*args): par.archive = archive.get() archive.set(par.archive) def update_arc_type(*args): par.arc_type = arc_type.get() arc_type.set(par.arc_type) def update_cores(*args): par.cores = cores.get() cores.set(par.cores) def update_plotvar(*args): par.plotvar = plotvar.get() plotvar.set(par.plotvar) def update_plot_format(*args): par.plot_format = plot_format.get() plot_format.set(par.plot_format) def update_tempdir(*args): par.tempdir = tempdir.get() tempdir.set(par.tempdir) def update_threshold(*args): par.threshold = threshold.get() threshold.set(par.threshold) def update_threshold_type(*args): par.threshold_type = threshold_type.get() threshold_type.set(par.threshold_type) def update_plotdir(*args): par.plotdir = plotdir.get() plotdir.set(par.plotdir) def update_trigger_interval(*args): par.trigger_interval = trigger_interval.get() trigger_interval.set(par.trigger_interval) # Set some grid parameters nrows = 25 ncolumns = 3 self.master = master master.title("EQcorrscan parameter setup") self.label = Label(master, text="Alpha GUI for default setup") self.label.grid(column=0, columnspan=ncolumns, row=0) # Set up parameter input self.t_names_label = Label(master, text="Template names", anchor='e') self.t_names_label.grid(column=0, row=1, sticky='e') template_names = StringVar() template_names.set(', '.join(par.template_names)) self.t_names_box = Entry(master, bd=2, textvariable=template_names) self.t_names_box.grid(column=1, row=1) template_names.trace("w", update_template_names) self.t_names_lookup = Button(master, text="Lookup", command=lambda: self.get_template_names(par)) self.t_names_lookup.grid(column=2, row=1) self.lowcut_label = Label(master, text="Lowcut (Hz)", anchor='e') self.lowcut_label.grid(column=0, row=2, sticky='e') lowcut = DoubleVar() lowcut.set(par.lowcut) self.lowcut_box = Entry(master, bd=2, textvariable=lowcut) self.lowcut_box.grid(column=1, row=2) lowcut.trace("w", update_lowcut) self.highcut_label = Label(master, text="Highcut (Hz)", anchor='e') self.highcut_label.grid(column=0, row=3, sticky='e') highcut = DoubleVar() highcut.set(par.highcut) self.highcut_box = Entry(master, bd=2, textvariable=highcut) self.highcut_box.grid(column=1, row=3) highcut.trace("w", update_highcut) self.filt_order_label = Label(master, text="Filter order") self.filt_order_label.grid(column=0, row=4, sticky='e') filt_order = DoubleVar() filt_order.set(par.filt_order) self.filt_order_box = Entry(master, bd=2, textvariable=filt_order) self.filt_order_box.grid(column=1, row=4) filt_order.trace("w", update_filt_order) self.samp_rate_label = Label(master, text="Sample rate (Hz)") self.samp_rate_label.grid(column=0, row=5, sticky='e') samp_rate = DoubleVar() samp_rate.set(par.samp_rate) self.samp_rate_box = Entry(master, bd=2, textvariable=samp_rate) self.samp_rate_box.grid(column=1, row=5) samp_rate.trace("w", update_samp_rate) self.debug_label = Label(master, text="Debug") self.debug_label.grid(column=0, row=6, sticky='e') debug = IntVar() debug.set(par.debug) self.debug_box = Entry(master, bd=2, textvariable=debug) self.debug_box.grid(column=1, row=6) debug.trace("w", update_debug) self.startdate_label = Label(master, text="Start date (yyyy-mm-dd)") self.startdate_label.grid(column=0, row=6, sticky='e') startdate = StringVar() startdate.set(par.startdate) self.startdate_box = Entry(master, bd=2, textvariable=startdate) self.startdate_box.grid(column=1, row=6) startdate.trace("w", update_startdate) self.enddate_label = Label(master, text="End date (yyyy-mm-dd)") self.enddate_label.grid(column=0, row=8, sticky='e') enddate = StringVar() enddate.set(par.enddate) self.enddate_box = Entry(master, bd=2, textvariable=enddate) self.enddate_box.grid(column=1, row=8) enddate.trace("w", update_enddate) self.archive_label = Label(master, text="Archive") self.archive_label.grid(column=0, row=9, sticky='e') archive = StringVar() archive.set(par.archive) self.archive_box = Entry(master, bd=2, textvariable=archive) self.archive_box.grid(column=1, row=9) archive.trace("w", update_archive) self.archive_lookup = Button(master, text="Lookup", command=lambda: self.get_archive(par)) self.archive_lookup.grid(column=2, row=9) self.arc_type_label = Label(master, text="Archive type") self.arc_type_label.grid(column=0, row=10, sticky='e') arc_type = StringVar() arc_type.set(par.arc_type) self.arc_type_box = OptionMenu(master, arc_type, "seishub", "fdsn", "day_vols") self.arc_type_box.grid(column=1, row=10, sticky='w,e') arc_type.trace("w", update_arc_type) self.cores_label = Label(master, text="Number of cores") self.cores_label.grid(column=0, row=11, sticky='e') cores = IntVar() cores.set(par.cores) self.cores_box = Entry(master, bd=2, textvariable=cores) self.cores_box.grid(column=1, row=11) cores.trace("w", update_cores) self.plotvar_label = Label(master, text="Plotting on/off") self.plotvar_label.grid(column=0, row=12, sticky='e') plotvar = BooleanVar() plotvar.set(par.plotvar) self.plotvar_box = Checkbutton(master, text='Plot on', var=plotvar, onvalue=True, offvalue=False) self.plotvar_box.grid(column=1, row=12) plotvar.trace("w", update_plotvar) self.plotdir_label = Label(master, text="Plot directory") self.plotdir_label.grid(column=0, row=13, sticky='e') plotdir = StringVar() plotdir.set(par.plotdir) self.plotdir_box = Entry(master, bd=2, textvariable=plotdir) self.plotdir_box.grid(column=1, row=13) plotdir.trace("w", update_plotdir) self.plotdir_lookup = Button(master, text="Lookup", command=lambda: self.get_plotdir(par)) self.plotdir_lookup.grid(column=2, row=13) self.plot_format_label = Label(master, text="Plot format") self.plot_format_label.grid(column=0, row=14, sticky='e') plot_format = StringVar() plot_format.set(par.plot_format) self.plot_format_box = OptionMenu(master, plot_format, "jpg", "eps", "pdf", "png") self.plot_format_box.grid(column=1, row=14, sticky='w,e') plot_format.trace("w", update_plot_format) self.tempdir_label = Label(master, text="Temporary directory") self.tempdir_label.grid(column=0, row=15, sticky='e') tempdir = StringVar() tempdir.set(par.tempdir) self.tempdir_box = Entry(master, bd=2, textvariable=tempdir) self.tempdir_box.grid(column=1, row=15) tempdir.trace("w", update_tempdir) self.tempdir_lookup = Button(master, text="Lookup", command=lambda: self.get_tempdir(par)) self.tempdir_lookup.grid(column=2, row=15) self.threshold_label = Label(master, text="Threshold") self.threshold_label.grid(column=0, row=16, sticky='e') threshold = DoubleVar() threshold.set(par.threshold) self.threshold_box = Entry(master, bd=2, textvariable=threshold) self.threshold_box.grid(column=1, row=16) threshold.trace("w", update_threshold) self.threshold_type_label = Label(master, text="Threshold type") self.threshold_type_label.grid(column=0, row=17, sticky='e') threshold_type = StringVar() threshold_type.set(par.threshold_type) self.threshold_type_box = OptionMenu(master, threshold_type, "MAD", "absolute", "av_chan_corr") self.threshold_type_box.grid(column=1, row=17, sticky='w,e') threshold_type.trace("w", update_threshold_type) self.trigger_interval_label = Label(master, text="Minimum trigger " + "interval (s)") self.trigger_interval_label.grid(column=0, row=18, sticky='e') trigger_interval = DoubleVar() trigger_interval.set(par.trigger_interval) self.trigger_interval_box = Entry(master, bd=2, textvariable=trigger_interval) self.trigger_interval_box.grid(column=1, row=18) trigger_interval.trace("w", update_trigger_interval) # End of user editable section, now we have read/write buttons self.read_button = Button(master, text="Read parameters", command=lambda: self.read_par(master)) self.read_button.grid(column=0, row=nrows-2, sticky='w,e') self.write_button = Button(master, text="Write parameters", command=lambda: self.write_par(par)) self.write_button.grid(column=1, row=nrows-2, sticky='w,e')
class TkMainGui(ttk.Frame): def __init__(self, root, default_folder=""): ttk.Frame.__init__(self, root, padding="3 3 12 12") self.default_folder = default_folder logging.debug("Create main frame") #mainframe = ttk.Frame(root, padding="3 3 12 12") self.grid(column=0, row=0, sticky=(N, W, E, S)) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) logging.debug("Create variable") self.filepath_ctf = StringVar() self.image_folder = StringVar() self.vh_ratio = DoubleVar(value=0.76200) self.results_text = StringVar() self.pcx = 0.0 self.pcy = 0.0 self.dd = 0.0 logging.debug("Create ctf components") ctf_entry = ttk.Entry(self, width=80, textvariable=self.filepath_ctf) ctf_entry.grid(column=2, row=1, sticky=(W, E)) ttk.Button(self, text="Select CTF file", command=self.open_ctf_file).grid(column=3, row=1, sticky=W) logging.debug("Create image folder components") image_entry = ttk.Entry(self, width=80, textvariable=self.image_folder) image_entry.grid(column=2, row=2, sticky=(W, E)) ttk.Button(self, text="Select Image folder", command=self.open_image_folder).grid(column=3, row=2, sticky=W) logging.debug("Create vh_ratio components") ttk.Label(self, text="VH Ratio").grid(column=1, row=3, sticky=(W, E)) image_entry = ttk.Entry(self, width=10, textvariable=self.vh_ratio) image_entry.grid(column=2, row=3, sticky=(W, E)) ttk.Button(self, text="Prepare data", command=self.prepare_data, width=80).grid(column=2, row=4, sticky=W) results_label = ttk.Label(self, textvariable=self.results_text, state="readonly") results_label.grid(column=2, row=5, sticky=(W, E)) for child in self.winfo_children(): child.grid_configure(padx=5, pady=5) ctf_entry.focus() def open_ctf_file(self): logging.debug("open_ctf_file") filename = filedialog.askopenfilename(filetypes=(("CTF file", "*.ctf"), ), initialdir=self.default_folder) logging.debug(filename) self.filepath_ctf.set(filename) basename = os.path.splitext(filename)[0] if os.path.isdir(basename + "Images"): self.image_folder.set(basename + "Images") elif os.path.isdir(basename + "_Images"): self.image_folder.set(basename + "_Images") def open_image_folder(self): logging.debug("open_image_folder") folder_name = filedialog.askdirectory(initialdir=self.default_folder) logging.debug(folder_name) self.image_folder.set(folder_name) def prepare_data(self): logging.debug("prepare_data") self.find_pattern_parameters() self.create_cpr_file() self.rename_image_folder() if self.pcx == 0.0 or self.pcy == 0.0 or self.dd == 0.0 or self.vh_ratio == 0.0: self.results_text.set("Error") else: self.results_text.set("Completed") def find_pattern_parameters(self): logging.debug("find_pattern_parameters") number_files = 0 extension = "" folder_name = self.image_folder.get() for filename in sorted(os.listdir(folder_name), reverse=True): try: basename, extension = os.path.splitext(filename) items = basename.split("_") number_files = int(items[-1]) break except: pass logging.debug(number_files) logging.debug(filename) start = filename.rfind("_%i" % (number_files)) image_filename = filename[:start+1] + "%0*i" % (len(str(number_files)), number_files/2) + extension logging.debug(image_filename) image_filepath = os.path.join(folder_name, image_filename) image = Image.open(image_filepath) for items in image.tag.values(): logging.debug(items) try: root = ET.fromstring(items[0]) logging.debug(root.tag) logging.debug(root.attrib) for element in root.iter('pattern-center-x-pu'): self.pcx = float(element.text) for element in root.iter('pattern-center-y-pu'): self.pcy = float(element.text) for element in root.iter('detector-distance-pu'): self.dd = float(element.text) except (TypeError, ET.ParseError): pass def create_cpr_file(self): logging.debug("create_cpr_file") lines = [] lines.append("\n") line = "VHRatio=%.5f\n" % (self.vh_ratio.get()) lines.append(line) line = "PCX=%.17f\n" % (self.pcx) lines.append(line) line = "PCY=%.17f\n" % (self.pcy) lines.append(line) line = "DD=%.17f\n" % (self.dd) lines.append(line) line = "IsFake=false;\n" lines.append(line) line = "// set isfake to true for X_Y image names and false for HLK style image names.\n" lines.append(line) filepath_ctf = self.filepath_ctf.get() filepath_cpr = os.path.splitext(filepath_ctf)[0] + ".cpr" logging.debug(filepath_cpr) with open(filepath_cpr, 'w') as file_cpr: file_cpr.writelines(lines) def rename_image_folder(self): logging.debug("rename_image_folder") folder_name = self.image_folder.get() if folder_name.endswith("_Images"): logging.debug(folder_name) start = folder_name.rfind("_Images") new_folder_name = folder_name[:start] + "Images" logging.debug(new_folder_name) try: os.replace(folder_name, new_folder_name) except OSError as message: logging.error(message)
class Nim(Tk): def __init__(self): Tk.__init__(self) self.title("Nim") self.kamen = PhotoImage(file = './kamen.ppm') self.nacin = BooleanVar() #0 is ai, 1 is human self.nacin = 0 self.zahtevnost = DoubleVar() #0, 1, 2 are (easy, medium hard) self.vnos_nacina = Entry(self, textvariable = "način") ni = Button(self, text="Nova igra", command=self.nova_igra) ni.grid(column = 2, row = 0) self.platno = Canvas(self, width=700, height = 500, bg='white') self.platno.grid(row= 3, column = 0, columnspan=4) self.vrhovi = [] self.z1 = Radiobutton(self, text = "Skoraj Nepremagljivo!", variable = self.zahtevnost, value=1) self.z2 = Radiobutton(self, text = "Srednje zahtevno ", variable = self.zahtevnost, value=2) self.z3 = Radiobutton(self, text = "Za majhne punčke ", variable = self.zahtevnost, value=3) self.z1.grid(column = 0, row = 0) self.z2.grid(column = 0, row = 1) self.z3.grid(column = 0, row = 2) self.z1.select() self.konec = Label() self.mainloop() def nova_igra(self): # print(self.zahtevnost.get()) if self.vrhovi != []: self.unici_kamne() self.k1.destroy() self.k2.destroy() self.k3.destroy() self.ligralec.destroy() # print(self.vrhovi) self.vrhovi = [randint(1, 5), randint(1, 5), randint(1, 5)] self.kamni = [[],[],[]] self.narisi_kamne(1) self.ligralec = Label(self, text='Na vrsti ste vi!', bg='white', font=("Calibri",21)) self.lracunalnik = Label(self, text='Na vrsti je računalnik', bg='white', font=("Calibri",21)) self.k1 = Label(self, text="Prvi kupček", bg='white') self.k1.place(x = 10, y=220) self.k2 = Label(self, text="Drugi kupček", bg='white') self.k2.place(x = 10, y=330) self.k3 = Label(self, text="Tretji kupček", bg='white') self.k3.place(x = 10, y=440) self.ligralec.place(x=300, y=130) self.konec.destroy() def preveri_zmagovalca(self, igralec): if max(self.vrhovi)<1: self.ligralec.destroy() self.lracunalnik.destroy() if igralec == 0: self.konec = Label(text='Čestitamo, zmagali ste!', bg = 'white', font=("Calibri", 24)) else: self.konec = Label(text = 'Več sreče prihodnjič!', bg = 'white', font=("Calibri",24)) self.konec.place(x=150, y=250) self.k1.destroy() self.k2.destroy() self.k3.destroy() def sestevek(self): s = 0 for i in range(len(self.vrhovi)): s = s^self.vrhovi[i] return s def sestevki(self): return [a^self.X < a for a in self.vrhovi] def naredi_potezo_AI(self): #Ta del kode sem dobil tako, da sem priredil kodo iz wikipedije #vir: http://en.wikipedia.org/wiki/Nim self.X = self.sestevek() S = self.sestevki() odstranjenih = 0 if self.X == 0: if max(self.vrhovi) >1: print("Can't win") for i, vrh in enumerate(self.vrhovi): if vrh>0: izbrani, odstranjenih = i, vrh else: izbrani = S.index(True) odstranjenih = self.vrhovi[izbrani] - (self.vrhovi[izbrani]^self.X) dva_alivec = 0 for i, vrh in enumerate(self.vrhovi): if i == izbrani: if vrh-odstranjenih > 1: dva_alivec += 1 else: if vrh > 1: dva_alivec += 1 if dva_alivec == 0: izbrani = self.vrhovi.index(max(self.vrhovi)) vrhov_z1 = sum(v == 1 for v in self.vrhovi) if vrhov_z1%2 == 1: odstranjenih = self.vrhovi[izbrani]-1 else: odstranjenih = self.vrhovi[izbrani] if odstranjenih == 0: odstranjenih = 1 izbrani = self.vrhovi.index(True) x = 10*(1-(1/self.zahtevnost.get())) v = randint(1, 10) if v < x: neprazni = [] for i, vr in enumerate(self.vrhovi): if vr>0: neprazni.append(i) izbrani = choice(neprazni) odstranjenih = randint(1, self.vrhovi[izbrani]) self.vrhovi[izbrani] -= odstranjenih self.unici_kamne() self.narisi_kamne(b=1) self.lracunalnik.place_forget() self.ligralec.place(x=300, y=130) self.preveri_zmagovalca(1) # print("Odstranil sem " + str(odstranjenih+1) + " kamenčkov iz " + str(izbrani+1) + " vrha.") def narisi_kamne(self, b=0): # print("narisi kamne") self.kamni = [[],[],[]] for i, j in enumerate(self.vrhovi): for k in range(j): self.kamni[i].append(Label(self, image=self.kamen, bd=0)) self.kamni[i][k].place(x=(100+110*k), y=(200+110*i)) par = (k+1, i+1) if b == 1: self.kamni[i][k].bind('<Button-1>', partial(self.izberi_kamen, par)) def unici_kamne(self): for vrh in self.kamni: for kamen in vrh: kamen.destroy() def naredi_potezo_clovek_text(self): izbrani = int(input("Izberi vrh: ")) odstranjenih = int(input("Stevilo kamenckov: ")) self.vrhovi[izbrani] -= odstranjenih # print(self.vrhovi) def izberi_kamen(self, par, j): # print("izbrali ste kamen ", par[0], " iz ", par[1], " vrha.") self.vrhovi[par[1]-1] = par[0]-1 # print(self.vrhovi) self.unici_kamne() self.narisi_kamne(0) self.ligralec.place_forget() self.lracunalnik.place(x=300, y=130) self.preveri_zmagovalca(0) self.after(1000, self.naredi_potezo_AI)
def initui(self): self.parent.title("Light pollution map") self.style = Style() self.style.theme_use("alt") self.grid(row=0, column=0) padding = {'padx':'5', 'pady':'5'} big_heading_font = ("Arial", 14, 'bold') small_heading_font = ("Arial", 10, 'bold') # Create frames. # There are three frames for settings - preprocessing, convolve, and contour. # Each also has an image frame underneath it. # Layout is as follows: # # -------------------------------------------------------------------------- # | | | | | # | | | | | # | import_body | process_body | contour_body | export_body | # | | | | | # | | | | | # -------------------------------------------------------------------------- # Settings frames top = self.winfo_toplevel() top.rowconfigure(0, weight=1) top.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.columnconfigure(1, weight=1) self.columnconfigure(2, weight=1) self.columnconfigure(3, weight=1) import_body = Frame(self, relief=RAISED, borderwidth=1) import_body.grid(row=0, column=0, sticky=N+S+E+W) process_body = Frame(self, relief=RAISED, borderwidth=1) process_body.grid(row=0, column=1, sticky=N+S+E+W) contour_body = Frame(self, relief=RAISED, borderwidth=1) contour_body.grid(row=0, column=2, sticky=N+S+E+W) export_body = Frame(self, relief=RAISED, borderwidth=1) export_body.grid(row=0, column=3, sticky=N+S+E+W) # ============================================================================================================= # # Contents of load_image_frame # # ============================================================================================================= # Heading processing_frame_header = Label(import_body, text="Import", font=big_heading_font) processing_frame_header.grid(row=0, column=0, sticky=N, **padding) filename_variable = StringVar() # Import image import_canvas = Canvas(import_body, width=canvas_size, height=canvas_size, background='black') import_canvas.grid(row=1, column=0, sticky=N, **padding) # Load file method def choosefile(): filename_variable.set(filedialog.askopenfilename(parent=import_body)) image = Image.open(filename_variable.get()) thumbnail = create_thumbnail(image, canvas_size) import_canvas.create_image(0, 0, image=thumbnail, anchor=NW) load_image_button = Button(import_body, text="Import image", command=choosefile) load_image_button.grid(row=2, column=0, columnspan=2, sticky=E+W+S, **padding) import_body.rowconfigure(2, weight=1) # ============================================================================================================= # # Contents of processing_frame # # ============================================================================================================= processing_frame_header = Label(process_body, text="Process", font=big_heading_font) processing_frame_header.grid(row=0, column=0, columnspan=2, sticky=N, **padding) clipping_variable = IntVar() constants_label = Label(process_body, text="Clipping", font=("Arial", 10, 'bold')) constants_label.grid(row=1, column=0, sticky=E, **padding) clipping_label = Label(process_body, text="Remove pixels with \n brightness under") clipping_label.grid(row=2, column=0, sticky=E, **padding) clipping_entry = Entry(process_body, textvariable=clipping_variable, width=4) clipping_entry.grid(row=2, column=1, sticky=W, **padding) clipping_variable.set(value=default_clipping_value) convolve_header = Label(process_body, text="Kernel", font=small_heading_font) convolve_header.grid(row=4, column=0, sticky=E, **padding) kernel_size_variable = IntVar() kernel_size_label = Label(process_body, text="Convolve kernel size", justify=RIGHT) kernel_size_label.grid(row=5, column=0, sticky=E, **padding) kernel_size_entry = Entry(process_body, textvariable=kernel_size_variable, width=4) kernel_size_entry.grid(row=5, column=1, sticky=W, **padding) kernel_size_variable.set(value=default_kernel_size) # Constants for convolve equation constants_label = Label(process_body, text="Falloff", font=("Arial", 10, 'bold')) constants_label.grid(row=6, column=0, sticky=E, **padding) constant_a_label = Label(process_body, text="Constant A:") constant_b_label = Label(process_body, text="Constant B:") constant_c_label = Label(process_body, text="Constant C:") constant_a_label.grid(row=7, column=0, sticky=E, **padding) constant_b_label.grid(row=8, column=0, sticky=E, **padding) constant_c_label.grid(row=9, column=0, sticky=E, **padding) constant_a_variable = DoubleVar() constant_b_variable = DoubleVar() constant_c_variable = DoubleVar() constant_a_entry = Entry(process_body, textvariable=constant_a_variable, width=4) constant_b_entry = Entry(process_body, textvariable=constant_b_variable, width=4) constant_c_entry = Entry(process_body, textvariable=constant_c_variable, width=4) constant_a_variable.set(default_constant_a) constant_b_variable.set(default_constant_b) constant_c_variable.set(default_constant_c) constant_a_entry.grid(row=7, column=1, **padding) constant_b_entry.grid(row=8, column=1, **padding) constant_c_entry.grid(row=9, column=1, **padding) constants_note = Label(process_body, text="Falloff equation is (Ax^B)-C", font=("Arial", 9)) constants_note.grid(row=10, column=0, columnspan=2, sticky=E, **padding) # Start button! def process(): print("Filename was " + filename_variable.get()) image_data = process_image(filename=filename_variable.get(), kernel_size=kernel_size_variable.get(), clipping_value=clipping_variable.get(), constant_a=constant_a_variable.get(), constant_b=constant_b_variable.get(), constant_c=constant_c_variable.get() ) image_data = Image.open("processed_image.png") thumbnail = create_thumbnail(image_data, canvas_size) export_canvas.create_image(0, 0, image=thumbnail, anchor=NW) start_button = Button(process_body, text="Process image", command=process) start_button.grid(row=11, column=0, columnspan=3, sticky=E+W+S, **padding) process_body.rowconfigure(11, weight=1) # ============================================================================================================= # # Contents of contour_frame # # ============================================================================================================= contour_header = Label(contour_body, text="Contour", font=big_heading_font) contour_header.grid(row=0, column=0, sticky=S, columnspan=2, **padding) contour_note = Label(contour_body, text="(optional)") contour_note.grid(row=1, column=0, sticky=S, columnspan=2) scale_options = {"width":"5", "length":"150"} slider_padding = {"padx":"2", "pady":"0"} scale_list = [] scale_values_list = [] default_scale_values = [5, 7, 10, 20, 30, 40, 60, 100, 200] for i in range(9): scale = Scale(contour_body, from_=0, to_=255, orient=HORIZONTAL, **scale_options) scale.grid(row=i+2, column=0, columnspan=2, sticky=S, **slider_padding) scale.set(default_scale_values[i]) scale_list.append(scale) for scale in scale_list: print(scale) print(type(scale)) #print(scale.get()) def contour(): scale_values_list.clear() for scale in scale_list: scale_values_list.append(scale.get()) contour_image(scale_values_list) image_data = Image.open("Contoured_image.png") thumbnail = create_thumbnail(image_data, canvas_size) export_canvas.create_image(0, 0, image=thumbnail, anchor=NW) contour_button = Button(contour_body, text="Contour image", command=contour) contour_button.grid(row=11, column=0, columnspan=2, sticky=E+S+W, **padding) contour_body.rowconfigure(11, weight=1) contour_body.columnconfigure(1, weight=1) # ============================================================================================================= # # Contents of export_body # # ============================================================================================================= filename_export_variable = StringVar() def export_file(): filename_options = {} filename_options['filetypes'] = [('PNG', '.png')] filename_options['initialfile'] = 'output.png' filename_options['parent'] = self filename_export_variable.set(filedialog.asksaveasfilename(**filename_options)) image_data = Image.open("Contoured_image.png") image_data.save(filename_export_variable.get()) export_header = Label(export_body, text="Export", font=big_heading_font) export_header.grid(row=0, column=0, sticky=N, **padding) export_canvas = Canvas(export_body, width=canvas_size, height=canvas_size, background='black') export_canvas.grid(row=1, column=0, **padding) export_button = Button(export_body, text="Export image", command=export_file) export_button.grid(row=2, column=0, columnspan=2, sticky=E+W+S, **padding) export_body.rowconfigure(2, weight=1)
class Gui(Frame): def __init__(self, control, *args, **kwargs): Frame.__init__(self, *args, **kwargs) self.config(padx=2) self.queue = Queue() self.control = control self.disabledWhileRunning = [] self.formulae = list(map(lambda t: StringVar(self, t), ["x/22.5+4", "50-x*50/180"])) self.executionTime = DoubleVar(self, "360") self.programSpeed = IntVar(self, "292") self.maxTravel = IntVar(self, "-200000") self.loadSettings() self.createWidgets() self.thread = None def compileFormulae(self): rv = [] for f in self.formulae: body = "def formula5480750923(x):\n return " + f.get() l = {} try: exec(body, {}, l) except: rv.append(None) continue compiled = l["formula5480750923"] compiled(0) rv.append(compiled) return rv def plotFormulae(self): try: compiled = self.compileFormulae() except: return for g in self.graphs: g.points = [] self.canvas.x.end = self.executionTime.get() self.canvas.clear() for x in range(self.canvas.x.start, int(self.canvas.x.end)): point = [] for c in range(len(compiled)): v = None if compiled[c]: v = compiled[c](x) assert isinstance(v, float) point.append(v) self.__addPoint__(x, point) self.canvas.update() def __start__(self): self.canvas.x.end = self.executionTime.get() pumps = self.compileFormulae() self.setValues() self.control.mover.setSpeed(abs(int(self.programSpeed.get()))) start_time = float(self.current_time.get()) def calcPumpValues(time): values = list(map(lambda x: x(time), pumps)) self.__addPoint__(time, values) self.current_time.set(time) return values def thFunc(): try: for g in self.graphs: g.points = [] self.control.executeProgram(start_time, calcPumpValues) finally: self.invoke(self.__enableControls__) self.__disableControls__() self.canvas.clear() self.thread = Thread(target=thFunc, name="Control") self.thread.start() def __enableControls__(self): for e in self.disabledWhileRunning: e.config(state=NORMAL) def __disableControls__(self): for e in self.disabledWhileRunning: e.config(state="disabled") def __addPoint__(self, x, values): for v in values: assert isinstance(v, float) def c(): for i in range(len(self.canvas.graphs)): self.canvas.graphs[i].addPoint(x, values[i]) self.invoke(c) def invoke(self, callable): self.after_idle(callable) def __stop__(self): self.control.stop() def __quit__(self): def quitting(): self.__stop__() if self.thread and self.thread.is_alive(): print("Thread is active") return False self.quit() return True run_repeating(self, quitting) def __move__(self, steps): speed = int(self.speed.get()) if speed < 0: speed *= -1 self.speed.set(speed) self.control.mover.setSpeed(speed) self.control.mover.go(steps) def __up__(self): steps = int(self.steps.get()) self.__move__(steps) def __down__(self): steps = int(self.steps.get()) self.__move__(-steps) def showValues(self): self.maxTravel.set(self.control.mover.maxTravel) self.executionTime.set(self.control.fullTime) self.programSpeed.set(self.control.mover.getSpeed()) def setValues(self): self.control.mover.maxTravel = int(self.maxTravel.get()) self.control.fullTime = float(self.executionTime.get()) self.control.mover.setSpeed(abs(int(self.programSpeed.get()))) def loadSettings(self): config = Config() try: config.read() except KeyError: pass config.configureControl(self.control) for i in range(len(self.formulae)): self.formulae[i].set(config.formulae[i]) self.showValues() def saveSettings(self): self.setValues() config = Config() config.getFromControl(self.control) for i in range(len(self.formulae)): config.formulae[i] = self.formulae[i].get() config.write() def createWidgets(self): panel = Frame(self, name="mainMenu") panel.grid(sticky=W) Button(panel, name="quit", text="Выход", command=self.__quit__).grid(row=0, column=0) Button(panel, name="reconnect", text="Пересоединение", command=self.control.reconnect).grid(row=0, column=1) b = Button(panel, text="Загрузить", command=self.loadSettings) b.grid(row=0, column=2) self.disabledWhileRunning.append(b) b = Button(panel, text="Сохранить", command=self.saveSettings) b.grid(row=0, column=3) self.disabledWhileRunning.append(b) panel = LabelFrame(self, text="Прямое управление стаканом", name="motor") panel.grid(sticky=W) b = Button(panel, text="Вверх", command=self.__up__, name="up") b.grid(row=0, column=0) self.disabledWhileRunning.append(b) b = Button(panel, text="Вниз", command=self.__down__, name="down") b.grid(row=1, column=0) self.disabledWhileRunning.append(b) Label(panel, text="Шаг:").grid(sticky=E, row=0, column=1) self.steps = IntVar(self, "10000") Entry(panel, textvariable=self.steps, width=6).grid(sticky=W, row=0, column=2) Label(panel, text="Скорость:").grid(sticky=E, row=1, column=1) self.speed = IntVar(self, "2000") Entry(panel, textvariable=self.speed, width=6).grid(sticky=W, row=1, column=2) self.position = IntVar(self, "1000") def readPosition(): try: self.position.set(self.control.mover.getPosition()) except (ConnectionResetError, Timeout): pass run_repeating(self, readPosition, 10000) b = Button(panel, text="Прочитать положение", command=readPosition) b.grid(row=0, column=3, columnspan=2) self.disabledWhileRunning.append(b) Label(panel, text="Положение:").grid(sticky=E, row=1, column=3) Entry(panel, textvariable=self.position, width=8, state="disabled").grid(sticky=W, row=1, column=4) panel = LabelFrame(self, text="Программа", name="program") program = panel panel.grid(sticky=W + E) panel.columnconfigure(1, weight=1) row = 0 for f in self.formulae: columns, rows = self.grid_size() Label(panel, text="Насос %d:" % (row + 1)).grid(row=row, column=0, sticky=E) e = Entry(panel, textvariable=f) e.grid(sticky=E + W, row=row, column=1) self.disabledWhileRunning.append(e) f.trace("w", lambda *x: self.after_idle(self.plotFormulae)) row += 1 panel = Frame(program, name="mover") panel.grid(columnspan=2, sticky=W) Label(panel, text="Максимальное смещение:").grid(sticky=E) Entry(panel, textvariable=self.maxTravel).grid(sticky=W, row=0, column=1) Label(panel, text="Скорость:").grid(sticky=E) Entry(panel, textvariable=self.programSpeed).grid(sticky=W, row=1, column=1) Label(panel, text="Время выполнения (в секундах):").grid(sticky=E) e = Entry(panel, textvariable=self.executionTime) e.grid(sticky=W, row=2, column=1) self.current_time = DoubleVar(self, "0") Label(panel, text="Текущее время:").grid(sticky=E) e = Entry(panel, textvariable=self.current_time) e.grid(sticky=W, row=3, column=1) self.disabledWhileRunning.append(e) self.executionTime.trace("w", lambda *x: self.plotFormulae()) panel = Frame(program, name="bottom") panel.grid(columnspan=2, sticky=W) row = 0 startButton = Button(panel, name="start", text="Старт", command=self.__start__) startButton.grid(row=row, column=0) self.disabledWhileRunning.append(startButton) Button(panel, text="Стоп", command=self.__stop__).grid(row=row, column=1) self.canvas = GraphCanvas(self) self.graphs = (Graph(self.canvas), Graph(self.canvas)) self.canvas.x.end = 100 self.canvas.y.end = 24 self.plotFormulae() self.canvas.grid(sticky=E + W + S + N) columns, rows = self.grid_size() self.columnconfigure(columns - 1, weight=1) self.rowconfigure(rows - 1, weight=1)
def test_invalid_value(self): v = DoubleVar(self.root, name="name") self.root.globalsetvar("name", "value") with self.assertRaises(ValueError): v.get()
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) Home_Button = ttk.Button(self, text = "Home", command = lambda: controller.show_frame(home_module.Home)) # Button to open Home screen Home_Button.grid(column = 2, row = 9, sticky = "nwes") WDB_Button = ttk.Button(self, text = "Watts To dB", command = lambda: controller.show_frame(watts_to_decibels.WDB))# Button to open W to dB screen WDB_Button.grid(column = 1, row = 9, sticky = "nwes") def dB_W(*args): try: Value = float(Data_In.get()) Range_Set = str(Range_1.get()) if Range_Set == 'dBm': dBm.set(Value) dBW.set(Value - 30) dBk.set(Value - 60) mW.set(pow(10, (Value / 10))) W.set(pow(10, (Value / 10)) / 1000) kW.set(pow(10, (Value / 10)) / 1000000) if Range_Set == 'dBW': dBm.set(Value + 30) dBW.set(Value) dBk.set(Value - 30) mW.set(pow(10, (Value / 10)) * 1000) W.set(pow(10, (Value / 10))) kW.set(pow(10, (Value / 10)) / 1000) if Range_Set == 'dBk': dBm.set(Value + 60) dBW.set(Value + 30) dBk.set(Value) mW.set(pow(10, (Value / 10)) * 1000000) W.set(pow(10, (Value / 10)) * 1000) kW.set(pow(10, (Value / 10))) except ValueError: dBm.set(0.0) dBW.set(0.0) dBk.set(0.0) mW.set(0.0) W.set(0.0) kW.set(0.0) def dB_range_select(*args): Range_Set = str(Range_1.get()) if Range_Set == 'dBm': Range_2.set("mW") if Range_Set == 'dBW': Range_2.set("W") if Range_Set == 'dBk': Range_2.set("kW") Range_1 = StringVar() Range_1.set('dBm') Range_2 = StringVar() Range_2.set('mW') Range_Selection = ttk.Combobox(self, textvariable = Range_1, state = 'readonly') Range_Selection['values'] = ('dBm', 'dBW', 'dBk') Range_Selection.grid(column = 2, row = 1, sticky = "nwes") Range_Selection.bind('<<ComboboxSelected>>', dB_range_select) Data_In = StringVar() Data_In.set(0) dBm = StringVar() dBm.set(0.0) dBW = StringVar() dBW.set(0.0) dBk = StringVar() dBk.set(0.0) mW = StringVar() mW.set(0.0) W = StringVar() W.set(0.0) kW = DoubleVar() kW.set(0.0) dB_entry = ttk.Entry(self, width = 7, textvariable = Data_In) dB_entry.grid(column = 2, row = 2, sticky = "nwes") ttk.Label(self, textvariable = dBm).grid(column = 2, row = 3, sticky = "nwes") ttk.Label(self, textvariable = dBW).grid(column = 2, row = 4, sticky = "nwes") ttk.Label(self, textvariable = dBk).grid(column = 2, row = 5, sticky = "nwes") ttk.Label(self, textvariable = mW).grid(column = 2, row = 6, sticky = "nwes") ttk.Label(self, textvariable = W).grid(column = 2, row = 7, sticky = "nwes") ttk.Label(self, textvariable = kW).grid(column = 2, row = 8, sticky = "nwes") ttk.Button(self, text = "Calculate", command = dB_W).grid(column = 3, row = 9, sticky = "nwes") ttk.Label(self, text = "Please choose a range :").grid(column = 1, row = 1, sticky = "nwes") ttk.Label(self, text = "Please enter a number :").grid(column = 1, row = 2, sticky = "nwes") ttk.Label(self, textvariable = Range_1).grid(column = 3, row = 2, sticky = "nwes") ttk.Label(self, text = "Is equivalent to :").grid(column = 1, row = 3, sticky = "nwes") ttk.Label(self, textvariable = Range_2).grid(column = 3, row = 3, sticky = "nwes") ttk.Label(self, text = "dBm").grid(column = 3, row = 3, sticky = "nwes") ttk.Label(self, text = "dBW").grid(column = 3, row = 4, sticky = "nwes") ttk.Label(self, text = "dBk").grid(column = 3, row = 5, sticky = "nwes") ttk.Label(self, text = "mW").grid(column = 3, row = 6, sticky = "nwes") ttk.Label(self, text = "W").grid(column = 3, row = 7, sticky = "nwes") ttk.Label(self, text = "kW").grid(column = 3, row = 8, sticky = "nwes") for child in DBW.winfo_children(self): child.grid_configure(padx = 5, pady = 5)