Beispiel #1
0
 def setYrng(self):
     ylow = sd.askfloat("Input","Min Y value")
     if ylow is not None:            
         yhigh = sd.askfloat("Input","Max Y value")
         if yhigh is not None:
             self.prevyrng=self.yrng
             self.yrng=[ylow,yhigh]
Beispiel #2
0
 def addHyp(self, proj):
     self.showlnhp = True
     vel = sd.askfloat("Input", "Velocity?")
     if vel is not None:
         zerotwtt = sd.askfloat("Input", "Zero two-way travel time?")
         if zerotwtt is not None:
             proj.addHyp(zerotwtt=zerotwtt, vel=vel)
def principal():
    cantidadTrabajadores = simpledialog.askinteger(
        "Número estudiantes", "Ingrese la cantidad de trabajadores:")

    while cantidadTrabajadores <= 0:
        messagebox.showerror(title="Error",
                             message="Erro, la cantidad debe ser positiva.")
        cantidadTrabajadores = simpledialog.askinteger(
            "Número estudiantes", "Ingrese la cantidad de trabajadores:")

    nombres = [None] * cantidadTrabajadores
    apellidos = [None] * cantidadTrabajadores
    salarios = [0.0] * cantidadTrabajadores

    for i in range(cantidadTrabajadores):
        nombres[i] = simpledialog.askstring("Nombre", "Escriba el nombre:")
        apellidos[i] = simpledialog.askstring("Apellido",
                                              "Escriba el apellido:")
        salario = simpledialog.askfloat("Notas", "Escribas el salario:")

        while salario < 0:
            messagebox.showerror(title="Error",
                                 message="Ingresar un salario mayor a 0")
            salario = simpledialog.askfloat("Notas", "Escribas la nota:")

        salarios[i] = salario

    prom = calcularSalarioPromedio(salarios)

    reporteT.config(state="normal")
    reporteT.insert(INSERT, prom)
    reporteT.config(state="disable")
Beispiel #4
0
 def angle_callback(self, angle) :
   #print("Got angle :",angle)
   if angle == "roll":
     f = simpledialog.askfloat( "Title", "Prompt?", initialvalue = self.master.m_roll, minvalue = -360.0 )
     if f != None :
       self.master.m_roll = f
       print('φ : ', self.master.m_roll )
       self.master.statusBar_frame.set(f'φ : {self.master.m_roll}' )
     else:
       self.master.statusBar_frame.set( 'φ set cancelled' )
   elif angle == "pitch":
     f = simpledialog.askfloat( "Title", "Prompt?", initialvalue = self.master.m_pitch, minvalue = -360.0 )
     if f != None :
       self.master.m_pitch = f#Converting angles from degrees to radians.
       print('θ : ', self.master.m_pitch )
       self.master.statusBar_frame.set(f'θ: {self.master.m_pitch}' )
     else:
       self.master.statusBar_frame.set( 'θ set cancelled' )
   elif angle == "yaw":
     f = simpledialog.askfloat( "Title", "Prompt?", initialvalue = self.master.m_yaw, minvalue = -360.0 )
     if f != None :
       self.master.m_yaw = f#Converting angles from degrees to radians.
       print('ψ : ', self.master.m_yaw )
       self.master.statusBar_frame.set(f'ψ: {self.master.m_yaw}' )
     else:
       self.master.statusBar_frame.set( 'ψ set cancelled' )
   else:
     print("No angle received")
Beispiel #5
0
def laser_engraving_estimation(layers, colours, selections, update_statusbar,
                               update_canvas, canvas):
    if not layers:
        messagebox.showerror("Cannot estimate laser time",
                             "You must load a file first")
        raise AbortAction()

    if not selections:
        messagebox.showerror("Cannot estimate laser time",
                             "You must select one or more layers to estimate")
        raise AbortAction()

    idle_speed = simpledialog.askfloat("Idle Speed",
                                       "Please enter the tool idle speed",
                                       initialvalue=10)
    active_speed = simpledialog.askfloat("Active Speed",
                                         "Please enter the tool active speed",
                                         initialvalue=800)
    scanline = simpledialog.askfloat("Scanline Distance",
                                     "Please enter the scanline distance",
                                     initialvalue=0.05)

    update_statusbar("Estimating engraving time")

    lines = sum((list(layers[layer_name]) for layer_name in selections), [])

    idle_time, time = estimated_engrave_time(lines, active_speed, idle_speed,
                                             scanline, update_canvas, canvas)

    update_statusbar(
        "Engraving will take ~{} seconds, spending ~{} seconds idle".format(
            int(round(time, 0)), int(round(idle_time, 0))))

    return layers, colours
Beispiel #6
0
def laser_estimation(layers, colours, selections, update_statusbar,
                     update_canvas, canvas):
    if not layers:
        messagebox.showerror("Cannot estimate laser time",
                             "You must load a file first")
        raise AbortAction()

    if not selections:
        messagebox.showerror("Cannot estimate laser time",
                             "You must select one or more layers to estimate")
        raise AbortAction()

    idle_speed = simpledialog.askfloat("Idle Speed",
                                       "Please enter the tool idle speed",
                                       initialvalue=100)
    active_speed = simpledialog.askfloat("Active Speed",
                                         "Please enter the tool active speed",
                                         initialvalue=35)

    time = 0

    for layer_name in selections:
        layer = layers[layer_name]

        time += estimated_laser_time(layer, idle_speed, active_speed)

    prefix = "This layer" if len(selections) == "1" else "These layers"

    update_statusbar("{} should take ~{} seconds".format(
        prefix, int(round(time, 0))))

    return layers, colours
 def offsetWin(self):
     if self.devID == 0:  # Motor
         self.ml = simpledialog.askfloat("Offset",
                                         "Degree offset [deg], +:CCW",
                                         parent=self.master,
                                         minvalue=-360.0,
                                         maxvalue=360,
                                         initialvalue=self.ml)
     elif self.devID == 3:  # EMV+
         self.ml = simpledialog.askfloat("Offset",
                                         "PEEP offset [mmHg]",
                                         parent=self.master,
                                         minvalue=-30.0,
                                         maxvalue=30,
                                         initialvalue=self.ml)
     else:
         if self.devID == 1:
             den = 1.0
         else:
             den = 10.0
         self.ml = simpledialog.askfloat("Offset",
                                         "Enter volume [ml], +:eject",
                                         parent=self.master,
                                         minvalue=-25 / den,
                                         maxvalue=25 / den,
                                         initialvalue=self.ml)
     if self.ml != None:
         self.offset()
Beispiel #8
0
    def mlp_classifier(self, x_train_original, y_train_original, x_train_soften, y_train_soften, x_test, y_test):

        # Get input
        momentum = simpledialog.askfloat('Multi-layer Perceptron', 'Momentum', minvalue=0)
        learning_rate = simpledialog.askfloat('Multi-layer Perceptron', 'Learning rate', minvalue=0)
        cv = simpledialog.askinteger('Multi-layer Perceptron', 'Cross Validation', minvalue=2)

        # Get number of attributes and number of classes
        num_of_attr = self.get_num_attr()
        num_of_classes = self.get_num_classes()

        # Get dataset size
        size_original = self.get_train_set_size()
        size_softened = self.get_new_train_set_size()

        # Show results of the mlp classifier
        self.parent.output.insert(INSERT, 'Results of the Multi-layer Perceptron Classifier\n\n')

        # get accuracy of the original training set
        acc, cross_acc, cross_mean = multi_layer_perceptron(x_train_original, x_test, y_train_original, y_test,
                                                              momentum, learning_rate, size_original,
                                                              num_of_attr, num_of_classes, cv)
        self.parent.output.insert(INSERT, 'Original dataset\n')
        self.parent.output.insert(INSERT, 'Accuracy with automatically generated test set: %0.2f\n' % acc)
        self.parent.output.insert(INSERT, 'Cross Validated Accuracy: %0.2f (+/- %0.2f)\n\n' % (cross_acc, cross_mean))

        # get accuracy of the softened training set
        acc, cross_acc, cross_mean = multi_layer_perceptron(x_train_soften, x_test, y_train_soften, y_test,
                                                              momentum, learning_rate, size_softened,
                                                              num_of_attr, num_of_classes, cv)
        self.parent.output.insert(INSERT, 'Soften dataset\n')
        self.parent.output.insert(INSERT, 'Accuracy with automatically generated test set: %0.2f\n' % acc)
        self.parent.output.insert(INSERT, 'Cross Validated Accuracy: %0.2f (+/- %0.2f)\n\n' % (cross_acc, cross_mean))

        self.parent.output.insert(INSERT, '---------------------------------------------------------------------\n')
Beispiel #9
0
 def keyDown(e):
     global moveState, commandQueue
     if e.char == 'w' and moveState != "forward":
         moveState = "forward"
         app.moveForward()
     if e.char == 'a' and moveState != "left":
         moveState = "left"
         app.moveLeft()
     if e.char == 's' and moveState != "backward":
         moveState = "backward"
         app.moveBackward()
     if e.char == 'd' and moveState != "right":
         moveState = "right"
         app.moveRight()
     if e.char == 'q' and moveState != "forward left":
         moveState = "forward_left"
         app.move_forward_left()
     if e.char == 'e' and moveState != "forward right":
         moveState = "forward_right"
         app.move_forward_right()
     if e.char == 'm':
         commandQueue = ["manual"]
     if e.char == 'p':
         ans = simpledialog.askfloat("Kp", "Enter proportional constant Kp:")
         if ans is not None:
             commandQueue = ["pid_p_" + str(ans)]
     if e.char == 'i':
         ans = simpledialog.askfloat("Ki", "Enter integral constant Ki:")
         if ans is not None:
             commandQueue = ["pid_i_" + str(ans)]
     if e.char == 'o':
         ans = simpledialog.askfloat("Kd", "Enter derivative constant Kd:")
         if ans is not None:
             commandQueue = ["pid_d_" + str(ans)]
Beispiel #10
0
 def adjProfile(self, proj):
     minPos = sd.askfloat("Input", "Start x coordinate")
     if minPos is not None:
         maxPos = sd.askfloat("Input", "End x coordinate")
         if maxPos is not None:
             proj.adjProfile(minPos=minPos, maxPos=maxPos)
             self.xrng = [minPos, maxPos]
Beispiel #11
0
        def bhpf():
            global currnt_img
            D0 = askfloat("Enter the value of D0",'please enter D0')
            if(D0 == None):
                D0 = 3.0
            Order = askfloat("Order of Butterworth HPF",'please enter an integer') 
            if(Order == None):
                Order = 2
            # crops the given image into (m/2,n/2) image
            def crop(image):
                lx, ly = image.shape
                return image[:lx/2, :ly/2]
            def hpf(shape,d0=3,order=2):
                d0  =float(d0)  
                m, n = shape
                u = np.linspace(-0.5, 0.5, n) *n
                v = np.linspace(-0.5, 0.5, m) *m
                d = np.sqrt((u**2)[np.newaxis] + (v**2)[:, np.newaxis]) # calculating d
                filt = 1 /(1.0 + (d0/d)**(2*order)) # butterworth filter
                return filt

            img = currnt_img
            m, n = img.shape
            new_img = np.zeros((2*m,2*n))
            new_img[:img.shape[0],:img.shape[1]] = img #reshaping image and padding 

            fft_orig = np.fft.fftshift(np.fft.fft2(new_img))# fourier transform of original image with shift
            high_pass  = hpf(new_img.shape,D0,Order)#filter
            new_filt = fft_orig*high_pass# fft of modified image
            recon_image = np.abs(np.fft.ifft2(np.fft.ifftshift(new_filt)))
            currnt_img = crop(recon_image)#crop
Beispiel #12
0
    def search_peaks(self):
        '''this function will detect the peaks and return:
        peaks, peaks2: stream 1 and stream 2 peaks list
        (referenced to each stream array) and which will be used to shift streams
        gr_plt_data, vn_plt_data: stream 1 and 2 plot data already sliced
        delta_time: time shift between 2 streams, calculated with first peaks
        '''
        peaks_not_detected = True
        user_cancelled = False

        while (peaks_not_detected and not user_cancelled):
            print()
            print()
            print('input GRAPHTEC peak threshold')
            graphtec_mph = tksd.askfloat('Input', 'Enter GRAPHTEC peak threshold', minvalue = 0.0001, maxvalue = 5.0)
            if graphtec_mph:

                print()
                print()
                print('input VectorNav peak threshold')
                #get the threshold
                vn_mph = tksd.askfloat('Input', 'Enter VectorNav peak threshold', minvalue = 0.0001, maxvalue = 50.0)
                if vn_mph:
                    peaks = detect_peaks(self.graphtec['CH8_diff'].values, mph=graphtec_mph)          

                    peaks2 = detect_peaks(self.vn_clean['Acceleration.Z_diff'].values, mph=vn_mph)
                    if len(peaks)==0:
                        print('Graphtec peaks not detectd - choose a lower threshold')
                    if len(peaks2)==0:
                        print('VectorNav peaks not detectd - choose a lower threshold')
                    if (len(peaks)>0) and (len(peaks2)>0):
                        print('peaks found')
                        peaks_not_detected = False
                else:
                    user_cancelled = True
            else:
                user_cancelled = True
        if user_cancelled == False:
            
            print('Graphtec initial timestamp: {}'.format(self.graphtec['wrong_dt'].iloc[0]))
            print('Graphtec peak detected at: {}'.format(self.graphtec['wrong_dt'].iloc[peaks[0]]))
            print('VectorNav initial timestamp: {}'.format(self.vn_clean['time'].iloc[0]))
            print('VectorNav peak detected at: {}'.format(self.vn_clean['time'].iloc[peaks2[0]]))
            print()

            dt_window = 10 # plot plus or minus seconds around found peak
            
            delta_time = self.graphtec['wrong_dt'].iloc[peaks[0]]-self.vn_clean['time'].iloc[peaks2[0]]
            print()
            gr_plt_data = self.graphtec[(self.graphtec['wrong_dt'] > (self.graphtec['wrong_dt'].iloc[peaks[0]]-pd.Timedelta(seconds=dt_window))) &
                  (self.graphtec['wrong_dt'] < (self.graphtec['wrong_dt'].iloc[peaks[0]]+pd.Timedelta(seconds=dt_window)))]

            vn_plt_data = self.vn_clean[(self.vn_clean['time'] > (self.vn_clean['time'].iloc[peaks2[0]]-pd.Timedelta(seconds=dt_window))) &
                  (self.vn_clean['time'] < (self.vn_clean['time'].iloc[peaks2[0]]+pd.Timedelta(seconds=dt_window)))]

            return peaks, peaks2, gr_plt_data, vn_plt_data, delta_time
        else:
            return [np.array(None), np.array(None), np.array(None), np.array(None), np.array(None)]
 def __init__(self):
     #inputs from the GUI
     self.application_window = tk.Tk()
     self.application_window.withdraw()
     self.ac=simpledialog.askfloat("Input", "Ac?", parent=self.application_window)
     self.am=simpledialog.askfloat("Input", "Am?", parent=self.application_window)
     self.fm=simpledialog.askfloat("Input", "fm?", parent=self.application_window)
     self.fc=simpledialog.askfloat("Input", "fc?", parent=self.application_window)
     self.modulating_index=simpledialog.askfloat("Input", "Modulation Index?", parent=self.application_window)
     self.plot_all()
Beispiel #14
0
 def setVelRng(self):
     vmin = sd.askfloat("Input", "Minimum velocity")
     if vmin is not None:
         self.vmin = vmin
     vmax = sd.askfloat("Input", "Maximum velocity")
     if vmax is not None:
         self.vmax = vmax
     vint = sd.askfloat("Input", "Velocity step size (interval)")
     if vint is not None:
         self.vint = vint
Beispiel #15
0
 def adjProfile(self,proj):
     flipit = mesbox.askyesno("Question","Flip the profile (left to right)?")
     if flipit:
         proj.flipProfile()        
     minPos = sd.askfloat("Input","Start x coordinate")
     if minPos is not None:
         maxPos = sd.askfloat("Input","End x coordinate")
         if maxPos is not None:
             proj.adjProfile(minPos=minPos,maxPos=maxPos)
             self.xrng=[minPos,maxPos]
Beispiel #16
0
 def showHyp(self,proj,a):
     x0 = sd.askfloat("Input","Hyperbola center on profile [m]")
     if x0 is not None:
         t0 = sd.askfloat("Input","Hyperbola apex location (two-way travel time [ns])")
         if t0 is not None:
             v  = sd.askfloat("Input","Estimated velocity [m/ns]")
             if v is not None:
                 y=proj.profilePos-x0
                 d=v*t0/2.0
                 k=np.sqrt(d**2 + np.power(y,2))
                 t2=2*k/v
                 a.plot(proj.profilePos,t2,'--c',linewidth=3)
def add_two_image():
    global img, img2, edited_image, my_img_string, just_file_name
    messagebox.showinfo("Please Select Two Images One", "Select the first image, then select the second image")

    openfile()
    openfile2()

    img_alpha = simpledialog.askfloat("User Input", "Please Enter Alpha Value for the first Image: 0.0 - 1.0 ")
    img2_beta = simpledialog.askfloat("User Input", "Please Enter Beta Value for the second Image: 0.0 - 1.0 ")
    img3 = cv2.addWeighted(img, img_alpha, img2, img2_beta, 0)
    edited_image = img3
    messagebox.showinfo("Image Blending Successful", "Click View to See the Image")
Beispiel #18
0
def rundeath():
    rat_inp = simpledialog.askfloat(title="Input",
                                    prompt="What is the rat weighting?:",
                                    initialvalue=0.8)

    pop_inp = simpledialog.askfloat(
        title="Input",
        prompt="What is the population weighting?:",
        initialvalue=1.3)

    calc_deaths(rat_inp, pop_inp)
    create_map(deaths, 'Estimated deaths')
Beispiel #19
0
    def create_node(self):
        x = simpledialog.askfloat("X", "Rentrez la valeur de X")
        y = simpledialog.askfloat("Y", "Rentrez la valeur de Y")
        z = simpledialog.askfloat("Z", "Rentrez la valeur de Z")
        name = simpledialog.askstring("Nom du point", "Rentrez un nom pour le point")

        if x is None or y is None or z is None or name is None:
            raise BaseException("Missing field ! All fields have to be filled.")
        else:
            new_node = NamedNode3D(x, y, z, pname=name)
            self.viewer.add_node(new_node)
            self.list_of_nodes.insert("end", new_node)

            self.draw()
Beispiel #20
0
def random_simu():
    global numsimu
    n = tks.askinteger("Input", "Combien d'objet voulez vous ?", parent=root)
    x = tks.askfloat("Input", "X_min", parent=root)
    x_max = tks.askfloat("Input", "X_max", parent=root)
    y = tks.askfloat("Input", "Y_min", parent=root)
    y_max = tks.askfloat("Input", "Y_max", parent=root)
    v = tks.askfloat("Input", "v_min", parent=root)
    v_max = tks.askfloat("Input", "v_max", parent=root)
    M_min = tks.askfloat("Input", "M_min", parent=root)
    M_max = tks.askfloat("Input", "M_max", parent=root)
    ask = message.askyesno("Question", "Voulez vous lancer la simulation ?")
    if ask:
        curlcommande = ("curl " + addresServ + "/paramInit/" + str(n) + "/" +
                        str(x) + "/" + str(x_max) + "/" + str(y) + "/" +
                        str(y_max) + "/" + str(v) + "/" + str(v_max) + "/" +
                        str(M_min) + "/" + str(M_max))
        process = sb.Popen(curlcommande.split(), stdout=sb.PIPE)
        output, error = process.communicate()
        numsimu += 1
        curlcommande = "curl " + addresServ + "/retourDonnees/CI.dat --output initial_data/CI" + str(
            numsimu) + ".dat"
        process = sb.Popen(curlcommande.split(), stdout=sb.PIPE)
        output, error = process.communicate()
        ask = message.askyesno(
            "Question", "voulez vous lancer la simulation?" +
            "initial_data/CI" + str(numsimu) + ".dat")
        if ask:
            lanceSimul("initial_data/CI" + str(numsimu) + ".dat")
Beispiel #21
0
def principal():
    numE = simpledialog.askinteger("Número estudiantes",
                                   "Ingrese la cantidad de estudiantes:")

    while numE <= 0:
        messagebox.showerror(title="Error",
                             message="Erro, la cantidad debe ser positiva.")
        numE = simpledialog.askinteger("Número estudiantes",
                                       "Ingrese la cantidad de estudiantes:")

    nombres = [None] * numE
    notas = [0.0] * numE
    i = 0

    while i < numE:
        nombres[i] = simpledialog.askstring("Nombre", "Escriba el nombre:")
        nota = simpledialog.askfloat("Notas", "Escribas la nota:")

        while nota < 0 or nota > 5:
            messagebox.showerror(title="Error",
                                 message="Ingresar una nota entre 0.0 y 5.0")
            nota = simpledialog.askfloat("Notas", "Escribas la nota:")

        notas[i] = nota
        i += 1

    varNumeroE.set(numE)

    prom = calcularPromedio(notas)
    varPromedio.set(prom)

    reporte = generarReporte(nombres, notas)

    ordenamientoNumericoAscendente(notas, nombres)
    reporte2 = generarReporte(nombres, notas)

    neAprobados = calcularAprobados(notas)
    varAprobados.set(neAprobados)

    neReprobados = calcularReprobados(notas)
    varReprobados.set(neReprobados)

    reporteE.config(state="normal")
    reporteE.insert(INSERT, reporte)
    reporteE.config(state="disable")

    reporteOrdenadoT.config(state="normal")
    reporteOrdenadoT.insert(INSERT, reporte2)
    reporteOrdenadoT.config(state="disable")
Beispiel #22
0
    def set_pxl_size(self):

        zoom = 1
        self.drawing = False
        window_name = 'Draw a rectangle with a known height (in cm), Click "-" to resize, Esc to exit'
        cv2.namedWindow(window_name)
        cv2.setMouseCallback(window_name, self.on_mouse)
        self.img = self.video_buffer[0].copy()
        self.img_cp = self.img.copy()
        self.ul_cr = (0, 0)
        self.lr_cr = (self.img.shape[1], self.img.shape[0])
        while True:
            cv2.imshow(window_name, self.img_cp)
            k = cv2.waitKey(20) & 0xFF
            if k == 27:
                break
            if k == ord('-'):
                self.img = cv2.resize(self.img,
                                      None,
                                      fx=0.5,
                                      fy=0.5,
                                      interpolation=cv2.INTER_AREA)
                self.img_cp = self.img.copy()
                self.ul_cr = (0, 0)
                self.lr_cr = (self.img.shape[1], self.img.shape[0])
                zoom *= 2
        cv2.destroyAllWindows()
        heigth = np.abs(self.ul_cr[0] - self.lr_cr[0]) * zoom
        rect_height = simpledialog.askfloat('Input',
                                            'Insert rectangle heigth in cm')
        self.pix_heigth = rect_height / heigth
        return
def fahrenheit():
    global unit1
    global unit2
    global num
    unit2 = 12  #sets this unit as second choice if first has been selected
    if unit1 == 10 and unit2 == 12:  #if celsius then fahrenheit is selected
        num = (9 / 5) * num + 32
        messagebox.showinfo("Result",
                            "Your conversion is {0:.2f}°F".format(num))
        again()
    elif unit1 == 11 and unit2 == 12:  #if kelvins then fahrenheit is selected
        num = (9 / 5) * (num - 273) + 32
        messagebox.showinfo("Result",
                            "Your conversion is {0:.2f}°F".format(num))
        again()
    else:  #if the first choice has not been selected
        unit1 = 12
        while True:  #if this button is the first choice, then ask user for their value
            try:
                num = askfloat("Celsius", "Please enter a number")
                if num == None:
                    unit1 = 0
                    break
                elif num <= 0:
                    messagebox.showinfo(
                        "Error", "Your value can't be zero or negative")
                else:
                    messagebox.showinfo("ACCEPTED",
                                        "Your value has been accepted")
                    fahren.place_forget()
                    break
            except (ValueError, error):
                showerror("Error", "Enter a valid number")
                continue
def hour():
    global unit1
    global unit2
    global num
    unit2 = 15  #sets this unit as second choice if first has been selected
    if unit1 == 13 and unit2 == 15:  #if seconds then hours is selected
        num /= 3600
        messagebox.showinfo("Result",
                            "Your conversion is {0:.2f}hrs".format(num))
        again()
    elif unit1 == 14 and unit2 == 15:  #if minutes then hours is selected
        num /= 60
        messagebox.showinfo("Result",
                            "Your conversion is {0:.2f}hrs".format(num))
        again()
    else:  #if the first choice has not been selected
        unit1 = 15
        while True:  #if this button is the first choice, then ask user for their value
            try:
                num = askfloat("Hours", "Please enter a number")
                if num == None:
                    unit1 = 0
                    break
                elif num <= 0:
                    messagebox.showinfo(
                        "Error", "Your value can't be zero or negative")
                else:
                    messagebox.showinfo("ACCEPTED",
                                        "Your value has been accepted")
                    hr.place_forget()
                    break
            except (ValueError, error):
                showerror("Error", "Enter a valid number")
                continue
def mmHgUnit():
    global unit1
    global unit2
    global num
    unit2 = 18  #sets this unit as second choice if first has been selected
    if unit1 == 16 and unit2 == 18:  #if atmospheres then mmHg is selected
        num = num * 760
        messagebox.showinfo("Result",
                            "Your conversion is {0:.2f}mmHg".format(num))
        again()
    elif unit1 == 17 and unit2 == 18:  #if kilopascals then mmHg is selected
        num = num * 7.50062
        messagebox.showinfo("Result",
                            "Your conversion is {0:.2f}mmHg".format(num))
        again()
    else:  #if the first choice has not been selected
        unit1 = 18
        while True:  #if this button is the first choice, then ask user for their value
            try:
                num = askfloat("mmHg", "Please enter a number")
                if num == None:
                    unit1 = 0
                    break
                elif num <= 0:
                    messagebox.showinfo(
                        "Error", "Your value can't be zero or negative")
                else:
                    messagebox.showinfo("ACCEPTED",
                                        "Your value has been accepted")
                    mmHg.place_forget()
                    break
            except (ValueError, error):
                showerror("Error", "Enter a valid number")
                continue
Beispiel #26
0
def principal():
    numeroAspirantes = 0
    
    hombresSeleccionados = 0
    estaturaPromedio = 0
    
    opcion = messagebox.askyesno(message="¿Desea Registrar Un Aspirante?", title="Opcion de usuario")
    reporte = "Nombre\tMensaje\n"
    
    while opcion:
        nombre = simpledialog.askstring("Nombre Aspirante", "Escriba el nombre del Aspirante :")
        genero = simpledialog.askstring("Genero Aspirante", "Digite el genero del Aspirante (F-M) :")
        estatura = simpledialog.askfloat("Estatura Aspirante", "Ingrese la estatura del Aspirante :")
        edad = simpledialog.askinteger("Edad Aspirante", "Ingrese la edad del Aspirante :")
        
        mensaje = evaluarAspirante(genero, estatura, edad)
        
        if mensaje == "Aceptado" and generoAspirante.upper() == "M":
            hombresSeleccionados += 1
            estaturaPromedio = (estaturaPromedio + estatura) / hombresSeleccionados
            varPromedio.set(estaturaPromedio)
        
        numeroAspirantes += 1
        varCantidad.set(numeroAspirantes)
        
        reporte = reporte + nombre + "\t" + mensaje +"\n"
        opcion = messagebox.askyesno(message="¿Desea Registrar Un Aspirante?", title="Opcion de usuario")
    
    reporteT.config(state="normal")
    reporteT.insert(INSERT, reporte)
    reporteT.config(state="disable")
Beispiel #27
0
 def __ask_learning_rate(self):
     """
     Input the learning rate.
     """
     self.learning_rate = simple_dialog.askfloat("", "Input learning rate:")
     self.text_learning_rate.delete(0.0, tk.END)
     self.text_learning_rate.insert(0.0, self.learning_rate)
Beispiel #28
0
 def displayStatsHum( self ):
     '''
     method that used tkinter simpledialog module to get the float value of the humidity threshold from user with options: initialvalue = 0.0,minvalue=-200.0,maxvalue=200.
     call of the method get_Hum_CSV on ConnectTH object
     '''
     float_value = simpledialog.askfloat('humidity threshold','what is humidity threshold',initialvalue = 0.0,minvalue=0.0,maxvalue=200.0)
     self.ourSensor.get_Hum_CSV(float_value)        
Beispiel #29
0
 def setOffset(self):
     newOffset = askfloat(parent = self.interior(),
                          title = self['text'],
                          prompt = 'Start offset (seconds):')
     if newOffset != None:
         self.offset = newOffset
         self.updateDisplay()
Beispiel #30
0
 def setOffset(self):
     newOffset = askfloat(parent = self.interior(),
                          title = self['text'],
                          prompt = 'Start offset (seconds):')
     if newOffset is not None:
         self.offset = newOffset
         self.updateDisplay()
Beispiel #31
0
def set_sphereSize():
    global sphereSize,scalefactor

    sphereSize = tkd.askfloat('Star field size', 'enter maximal distance for center to farthest star')
    scalefactor = sphereSize

    drawStarfield(starField,fixField)
Beispiel #32
0
 def askstr(self, f):
     theta = sd.askfloat("test askinteger", "deg")
     if f == "sin":
         data = str(math.sin(math.radians(theta)))
     if f == "cos":
         data = str(math.cos(math.radians(theta)))
     self.set(data)
Beispiel #33
0
def value_entry():
    application_window = tk.Tk()

    answer = simpledialog.askstring("Input", "What is your first name?",
                                    parent=application_window)
    if answer is not None:
        print("Your first name is ", answer)
    else:
        print("You don't have a first name?")

    answer = simpledialog.askinteger("Input", "What is your age?",
                                     parent=application_window,
                                     minvalue=0, maxvalue=100)
    if answer is not None:
        print("Your age is ", answer)
    else:
        print("You don't have an age?")

    answer = simpledialog.askfloat("Input", "What is your salary?",
                                   parent=application_window,
                                   minvalue=0.0, maxvalue=100000.0)
    if answer is not None:
        print("Your salary is ", answer)
    else:
        print("You don't have a salary?")
Beispiel #34
0
def footprintCorrect(fullpaths=None):
    '''
    As a script, ask for filenames, load/stitch data, plot data,
    collect footprint range, calc footprint, and write .refl files.
    '''
    if fullpaths is None:
        fullpaths = get_files()
    path=os.path.split(fullpaths[0])[0]
    headers,angle,cps,dcps=stitch_data(fullpaths)

    wavelength=float(headers['wavelength'])
    q=q_from_angle(angle,wavelength)

    plt.plot(q,cps,'k-')
    plt.axis([min(q),q[np.argmax(cps)]*2,0,1.1*max(cps)])

    mymessage('Click the beginning and end of the footprint region')
    points=plt.ginput(2,timeout=100)
    if len(points)<2:
        raise ExitException('Point selection timeout, not an error')

#    cutoff=askfloat('Cutoff angle','A footprint cutoff angle in degrees',
#             initialvalue=1.0)
    Tk().withdraw()
    width=askfloat('Sample width','Average sample width in mm',initialvalue=24.5)
    if width is None:
        raise ExitException('Exiting, not an error')
    cutoff=np.arcsin(.4/width)/np.pi*180
    q_cut=q_from_angle(cutoff,wavelength)

    start,stop = points[0][0], points[1][0]
    keepers = q > start
    fit_range = np.logical_and(keepers, q < stop)
    p = np.polyfit(q[fit_range],cps[fit_range],1)

    q_correct = q[keepers]
    footprint = np.polyval(p, q_correct)
    fp_region = q_correct<q_cut
    footprint[np.logical_not(fp_region)]=np.polyval(p,q_cut)

    plt.plot(q_correct,footprint,'r--')
    plt.draw()

    refl_correct = cps[keepers]/footprint
    refl_correct = refl_correct/max(refl_correct)
    drefl_correct = dcps[keepers]/footprint/max(refl_correct)

    plt.figure()
    plt.semilogy(q,cps/max(cps),'k--')
    plt.semilogy(q_correct,footprint/max(cps),'r:')
    plt.semilogy(q_correct,refl_correct,'k-')
    mymessage('Resulting reflectivity')
    plt.draw()

    plt.show(block=False)

    write_refl(headers,q_correct,refl_correct,drefl_correct,path)
    return q_correct,refl_correct,drefl_correct
Beispiel #35
0
def BSetFreqs():
	global startFreq
	global stopFreq
	global measMode
	
	prompt = "Set the sweep starting frequency (MHz):"
	retVal = simpledialog.askfloat("Set Start Frequency", prompt, parent = root, initialvalue = startFreq/1000000, minvalue = 0, maxvalue = 72)
	if retVal is not None:
		startFreq = retVal*1000000
		
	prompt = "Set the sweep stopping frequency (MHz):"
	retVal = simpledialog.askfloat("Set Stop Frequency", prompt, parent = root, initialvalue = stopFreq/1000000, minvalue = 0, maxvalue = 72)
	if retVal is not None:
		stopFreq = retVal*1000000
	
	measMode = 0
	
	SetupArrays()
	UpdateGraph()
Beispiel #36
0
    def numinput(self, title, prompt, default=None, minval=None, maxval=None):
        """Pop up a dialog window for input of a number.

        Arguments: title is the title of the dialog window,
        prompt is a text mostly describing what numerical information to input.
        default: default value
        minval: minimum value for imput
        maxval: maximum value for input

        The number input must be in the range minval .. maxval if these are
        given. If not, a hint is issued and the dialog remains open for
        correction. Return the number input.
        If the dialog is canceled,  return None.

        Example (for a TurtleScreen instance named screen):
        >>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)

        """
        return simpledialog.askfloat(title, prompt, initialvalue=default,
                                     minvalue=minval, maxvalue=maxval)
Beispiel #37
0
#!/usr/bin/python3

from tkinter.filedialog import askopenfilename
from tkinter.colorchooser import askcolor
from tkinter.messagebox import askquestion, showerror
from tkinter.simpledialog import askfloat

demos = {
        'Open':askopenfilename,
        'Color':askcolor,
        'Query':lambda:askquestion('Warning', 'You typed "rm *"\nConfirm?'),
        'Error':lambda:showerror('Error!',"He's dead, Jim"),
        'Imput':lambda:askfloat('Entry', 'Entry credit card number')
        }

if __name__ == "__main__":
    print(demos)
Beispiel #38
0

"""MAIN"""
# Adjust these values

l_min = 0.01 #[mm] minimum segment length

#*************************************************
#os.chdir('C:/Users/Tom/Documents/Python Scripts')

#Prompt for a .gcode file with a Open File window
root = tk.Tk()
root.withdraw()
filename = filedialog.askopenfilename(title="Please select a gcode file")

l_min = askfloat("Input", "Minimum segment length (0.01 suggested):",
                                  parent=root, minvalue=0, maxvalue=1)

start = time.time()

f_out = open(filename[:-6] + '_shortened.gcode', 'w')

#print(str(len(lines)) + " lines at start")
prevline = ';';
strset0 = ';';
plB = 0; #previous line boolean
nlB = 0; #new line boolean, True when new line is an X or Y movement
x0 = 0;
x1 = 0;
y0 = 0;
y1 = 0;
lines_skipped=0;
Beispiel #39
0
# e.g. 8-8
from tkinter.filedialog import askopenfile
from tkinter.colorchooser import askcolor
from tkinter.messagebox import askquestion, showerror
from tkinter.simpledialog import askfloat


demos = {
    'Open': askopenfile,
    'Color': askcolor,
    'Query': lambda: askquestion('Warning', 'You typed "rm *"\nConfirm?'),
    'Error': lambda: showerror('Error!', "He's dead, Jim"),
    'Input': lambda: askfloat('Entry', 'Enter credit card number')
}
Beispiel #40
0
def set_minAbsMag():
    global sphereSize,scalefactor,minAbsMag

    minAbsMag = tkd.askfloat('Minimal absolute magnitude', 'enter minimal visible absolute magnitude (>100 to see all)')

    drawStarfield(starField,fixField)
Beispiel #41
0
from tkinter.filedialog import askopenfilename
from tkinter.colorchooser import askcolor
from tkinter.messagebox import askquestion,showerror
from tkinter.simpledialog import askfloat
from tkinter import *
#from quitter import Quitter

demos={
    'open':askopenfilename,
    'color':askcolor,
    'query':lambda:askquestion('warning','you typed "rm *"\nConfirm?'),
    'error':lambda:showerror('error','he\'s dead,jim'),
    'imput':lambda:askfloat('entry','enter credit card number')
}

class Demo(Frame):
    def __init__(self,parent=None,**options):
        Frame.__init__(self,parent,**options)
        self.pack()
        Label(self,text="basic demos").pack()
        for (key,value) in demos.items():
            Button(self,text=key,command=value).pack(side=TOP,fill=BOTH)
        #Quitter(self).pack(side=TOP,fill=BOTH)

Demo().mainloop()
Beispiel #42
0
def inputFloat():
    r = simpledialog.askfloat('Python Tkinter', 'Input Float')
    print(r)
Beispiel #43
0
from tkinter import *

# demoTable
from tkinter.colorchooser import askcolor
from tkinter.filedialog import askopenfile
from tkinter.messagebox import askquestion, showerror
from tkinter.simpledialog import askfloat

# QuitBtn中的确认退出功能
from tkinter.messagebox import askokcancel


demoTable = {
    "Color": askcolor,
    "Query": (lambda: askquestion("Warning", 'You typed "rm *"\nConfirm?')),
    "Input": (lambda: askfloat("Enrty", "Enter credit card number")),
    "Open": askopenfile,
    "Error": (lambda: showerror("Error!", "He's dead, Jim")),
}

demoModules = ["DemoDlg", "DemoCheck", "DemoRadio", "DemoScale"]
parts = []


# Quit按钮
class QuitBtn(Frame):
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.pack()
        widget = Button(self, text="Quit", command=self.quit)
        widget.pack(side=TOP, expand=YES, fill=BOTH)
Beispiel #44
0
 def setC(self):
     self.C = tksimdial.askfloat("C", "C", initialvalue=self.C)
     self.UpdateValues()
     pass
Beispiel #45
0
 def setD(self):
     self.D = tksimdial.askfloat("D", "D", initialvalue=self.D)
     self.UpdateValues()
     pass
Beispiel #46
0
 def sett0(self):
     self.te = tksimdial.askfloat("te", "te", initialvalue=self.te)
     self.UpdateValues()
     pass 
Beispiel #47
0
 def settmin(self):
     self.tmin = tksimdial.askfloat("t_min", "t_min", initialvalue=self.tmin)
     self.UpdateValues()
     pass
Beispiel #48
0
 def settmax(self):
     self.tmax = tksimdial.askfloat("t_max", "t_max", initialvalue=self.tmax)
     self.UpdateValues()
     pass    
Beispiel #49
0
 def ask_for_float(self):
     f=simpledialog.askfloat('My Dialog', 'Please enter a string')
     print ( f)
import os
import sys
import random
from tkinter import *
from tkinter import filedialog
from tkinter import simpledialog
from munkres import Munkres, print_matrix

mGui = Tk()
mGui.withdraw()
#myPath = simpledialog.askstring(mGui, '(path) Enter the path')
myPath = filedialog.askdirectory(initialdir = ".", title="Choose a file", mustexist=True)+"/";
alpha = simpledialog.askfloat(mGui, '(alpha) Enter a value between 0 and 1: ')
beta = simpledialog.askfloat(mGui, '(beta) Enter a value between 0 and 1: ')

matrix = []
pairs = []

def count_lines(filename):
	f = open(myPath+filename, 'rU')
	num_lines = 0
	for line in f:
		num_lines += 1
	f.close()
	return num_lines

def similarity(filename1, filename2):
	global pairs
	ifile = open(myPath+filename1, 'rU')
	ofile = open(myPath+filename2, 'rU')
Beispiel #51
0
#!/usr/bin/python3

from tkinter.filedialog import askopenfilename
from tkinter.colorchooser import askcolor
from tkinter.messagebox import askquestion, showerror
from tkinter.simpledialog import askfloat

demos = {
    "open": askopenfilename,
    "color": askcolor,
    "query": lambda: askquestion("Warning", "You typed rm *\n confirm"),
    "error": lambda: showerror("Error", "its dead"),
    "Input": lambda: askfloat("entry", "enter number"),
}
Beispiel #52
0
def askFloat(title, prompt, **kw):
	return simpledialog.askfloat(title, prompt, **kw)
Beispiel #53
0
from tkinter.filedialog import askopenfilename # get standard dialogs
from tkinter.colorchooser import askcolor # they live in Lib\tkinter
from tkinter.messagebox import askquestion, showerror, askokcancel
from tkinter.simpledialog import askfloat
from tkinter import * # get base widget set

import tkinter.messagebox

demos = {
    'Open': askopenfilename,
    'Color': askcolor,
    'Query': lambda: askquestion('Warning', 'You typed "DROP TABLES"\nConfirm?'),
    'Error': lambda: showerror('Error!', "System Overload!"),
    'Input': lambda: askfloat('Entry', 'Enter your ssn')
}

class Quitter(Frame): # subclass our GUI
    def __init__(self, parent=None): # constructor method
        Frame.__init__(self, parent)
        self.pack()
        widget = Button(self, text='Quit', command=self.quit)
        widget.pack(side=LEFT, expand=YES, fill=BOTH)

    def quit(self):
        ans = askokcancel('Verify exit', "Really quit?")
        if ans: Frame.quit(self)

class Demo(Frame):
    def __init__(self, parent=None, **options):
        Frame.__init__(self, parent, **options)
        self.pack()
Beispiel #54
0
 def setB(self):
     self.B = tksimdial.askfloat("B", "B", initialvalue=self.B)
     self.UpdateValues()
     pass
Beispiel #55
0
 def setA(self):
     self.A = tksimdial.askfloat("A", "A", initialvalue=self.A)
     self.UpdateValues()
     pass 
Beispiel #56
0
__author__ = 'tkessler'

#This table will be callable to access instances of the associated class instances...

from tkinter.filedialog import askopenfilename
from tkinter.colorchooser import askcolor
from tkinter.messagebox import askquestion, showerror
from tkinter.simpledialog import askfloat

demos = {
    'Open': askopenfilename,
    'Color': askcolor,
    'Query': lambda: askquestion('Warning', 'You typed "rm *"\nConfirm?'),
    'Error': lambda: showerror('Error!', "He's dead, Jim"),
    'Input': lambda: askfloat('Entry', 'Enter Credit Card Number'),
    'Number': lambda: askfloat('Entry', 'Enter another Number')
}

# define a name:callback demos table

from tkinter.filedialog   import askopenfilename        # get standard dialogs
from tkinter.colorchooser import askcolor               # they live in Lib\tkinter
from tkinter.messagebox   import askquestion, showerror
from tkinter.simpledialog import askfloat, askinteger, askstring

demos = {
    'Open':  askopenfilename,
    'Color': askcolor,
    'Query': lambda: askquestion('Warning', 'You typed "rm *"\nConfirm?'),
    'Error': lambda: showerror('Error!', "He's dead, Jim"),
    'Input 1': lambda: askinteger('Entry 1', 'Enter credit card number'),
    'Input 2': lambda: askfloat('Entry 2', 'Enter your fav pie'),
    'Input 3': lambda: askstring('Entry 3', 'Enter your fav SPAMSPAMSPAM')
}
# define a name:callback demos table

# Example 8-8

from tkinter.filedialog import askopenfilename  # get standard dialogs
from tkinter.colorchooser import askcolor  # they live in Lib\tkinter
from tkinter.messagebox import askquestion, showerror
from tkinter.simpledialog import askfloat

demos = {
    "Open": askopenfilename,
    "Color": askcolor,
    "Query": lambda: askquestion("Warning", 'You typed "rm *"\nConfirm?'),
    "Error": lambda: showerror("Error!", "He's dead, Jim"),
    "Input": lambda: askfloat("Entry", "Enter credit card number"),
}
Beispiel #59
0
 def settstep(self):
     self.tstep = tksimdial.askfloat("t_step", "t_step", initialvalue=self.tstep)
     self.UpdateValues()
     pass            
Beispiel #60
0
    def cmdReadFile(self):
        """ 
Method reads text file in format
time, relative length, error
Data is normalized to get proper scaling 
If no error is given, assume 1
        """
        # Clean if opening a new file
        #if self.filename != "": 
        self.ClearMe()
       #while self.strFileName.get()=="":
            #or not os.access(self.strFileName, os.W_OK):
        self.filename = tkFileDialog.askopenfilename(defaultextension=".dat", initialdir=".", multiple=False)
        #print self.strFileName, os.access(self.strFileName, os.W_OK)
            
        if self.DebugLevel > 1: print("Filename:" + self.filename)
        self.fp = open(self.filename,'r')
        self.lisDataFile = self.fp.readlines()
        self.fp.close()
        self._divisorL = tksimdial.askfloat("Input divisor L", "Divisor that makes the elongation data dimensionless and 1\n e.g. 10000 for micron/cm", initialvalue = str(10000))
        self._multiT = tksimdial.askfloat("Input time factor", "Factor that converts time scale into seconds\n e.g. 60 for if the time in the file is in minutes", initialvalue = str(60))
# initialize tmin and tmax, so we can catch proper values
        self.tmax = -1*self._multiT
        self.tmin = 100*self._multiT
        # process header or until we find [Data]
        for self._line in self.lisDataFile:
            # drop comments
            if self._line[0] == "#": continue
            
            for self._i,self._t in enumerate(self._line.split()):
                if len(self._line.split()) == 0: 
                    if self.DebugLevel >2: print("empty line")
                    continue
                self._error = 1
                if self._i == 0: 
                    #print("Time " + self._t)
                    self._time = self._multiT*float(self._t)
                    if self._time > self.tmax: self.tmax = self._time
                    if self._time < self.tmin: self.tmin = self._time
                    self.TimeExper.append(self._time)
                elif self._i == 1:
                    #print("Elong " + self._t)
                    self._elong = float(self._t)/self._divisorL
                    self.RelElExper.append(self._elong)
                else:
                    self._error = float(self._t)/self._divisorL
                    if self._error == 0: self._error = 0.000001
                    self.ErrorExper.append(self._error)
            self.DataTuples.append((self._time, self._elong, self._error))

        self.Npoints = len(self.DataTuples)
        if len(self.ErrorExper) == 0: self.ErrorExper = np.ones(self.Npoints)
        if self.DebugLevel >0: print("Number of data = ",len(self.DataTuples))
        if self.DebugLevel >2: print(self.DataTuples)
        
        if len(self.DataTuples)<=3:
            tkmb.askokcancel("No data found", "Check your input file")
            return
        self.TimeExper = np.array(self.TimeExper).astype(np.float64)
        self.RelElExper = np.array(self.RelElExper).astype(np.float64)
        self.ErrorExper = np.array(self.ErrorExper).astype(np.float64)
        if self.DebugLevel >2: print(self.TimeExper)
        if self.DebugLevel >2: print(self.RelElExper)
        if self.DebugLevel >2: print(self.ErrorExper)
        #print(self.TimeExper[0],self.RelElExper[0],self.ErrorExper[0] )
        self.UpdateValues()
        self.PlotMe()
        self.butPlot.config(state="normal")
        self.butEstim.config(state="normal")
        self.butA.config(state="normal")
        self.butB.config(state="normal")
        self.butC.config(state="normal")
        self.butD.config(state="normal")        
        self.butt0.config(state="normal")
        self.buttmax.config(state="normal")
        self.buttmin.config(state="normal")
        self.buttstep.config(state="normal")