コード例 #1
0
ファイル: gui.py プロジェクト: samuelleblanc/flight_planning
    def gui_addfigure(self,ll_lat=None,ll_lon=None,ur_lat=None,ur_lon=None):
        'GUI handler for adding figures forecast maps to basemap plot'
        import tkSimpleDialog
        try:
            from scipy.misc import imread
            import PIL
            filename = self.gui_file_select(ext='.png',ftype=[('All files','*.*'),
                                                          ('PNG','*.png'),
							  ('JPEG','*.jpg'),
							  ('GIF','*.gif')])
            if not filename:
                print 'Cancelled, no file selected'
                return
            print 'Opening png File: %s' %filename
            img = imread(filename)
        except:
            import tkMessageBox
            tkMessageBox.showwarning('Sorry','Error occurred unable to load file')
            return
	# get the corners
	if not ll_lat:
	    ll_lat = tkSimpleDialog.askfloat('Lower left lat','Lower left lat? [deg]')
	    ll_lon = tkSimpleDialog.askfloat('Lower left lon','Lower left lon? [deg]')
	    ur_lat = tkSimpleDialog.askfloat('Upper right lat','Upper right lat? [deg]')
	    ur_lon = tkSimpleDialog.askfloat('Upper right lon','Upper right lon? [deg]')
	self.line.addfigure_under(img,ll_lat,ll_lon,ur_lat,ur_lon)
コード例 #2
0
def ask_float(prompt, default=None, min=0.0,max=100.0, title=''):
	""" Get input from the user, validated to be an float (decimal number). default refers to the value which is initially in the field. By default, from 0.0 to 100.0; change this by setting max and min. Returns None on cancel."""
	import tkSimpleDialog
	if default:
		return tkSimpleDialog.askfloat(title, prompt, minvalue=min, maxvalue=max, initialvalue=default)
	else:
		return tkSimpleDialog.askfloat(title, prompt, minvalue=min, maxvalue=max)
コード例 #3
0
ファイル: stackProcessing.py プロジェクト: Splo0sh/3DCT
	def getfiles():
		files = tkFileDialog.askopenfilenames(parent=root,title='Choose image stack files')
		if not files: return
		filenames = []
		for fname in files:
			filenames.append(os.path.split(fname)[1])
		if len(files) > 10:
			filenames = filenames[0:10]
			filenames.append("...")
		ss_in = tkSimpleDialog.askfloat(
			parent=root, title='Enter ORIGINAL focus step size',
			prompt='Enter ORIGINAL focus step size for:\n'+'\n'.join('{}'.format(k) for k in filenames))
		if not ss_in: return
		pixelsize = pxSize(files[0])
		if pixelsize is None: pixelsize = 0
		ss_out = tkSimpleDialog.askfloat(
			parent=root, title='Enter INTERPOLATED focus step size',
			prompt='Enter INTERPOLATED focus step size for:\n'+'\n'.join('{}'.format(k) for k in filenames), initialvalue=pixelsize*1000)
		if not ss_out: return
		print "Selected files: {0}\n".format(files), "\n", "Focus step size in: {0} | out: {1}\n".format(ss_in,ss_out),\
			"Interpolation method: {0}\n".format(int_method.get())
		for filename in files:
			main(filename,ss_in, ss_out, saveorigstack=False, interpolationmethod=int_method.get(), showgraph=bool(showgraph.get()))
		print "Finished interpolation."
		print "="*40
コード例 #4
0
ファイル: __Assignment1_bak1.py プロジェクト: iamthad/SSC374E
 def addIso(self):
   isovalue=tkSimpleDialog.askfloat("Isosurface Level","What function value should the isosurface be at?")
   isocolor = tkColorChooser.askcolor(title="Isosurface Color")
   isoopacity = tkSimpleDialog.askfloat("Isosurface Opacity","What opacity should the isosurface have? 0 = transparent.")
   surf = isosurface(self.reader.GetOutputPort(),isovalue,isocolor[0][0],isocolor[0][1],isocolor[0][2],isoopacity) 
   self.isosurfaces.append(surf)
   self.isolist.insert(Tkinter.END,str(surf))
   self.ren.AddActor(surf.actor)
コード例 #5
0
ファイル: __Assignment1_bak1.py プロジェクト: iamthad/SSC374E
 def editIso(self,i):
   isovalue=tkSimpleDialog.askfloat("Isosurface Level","What function value should the isosurface be at?",initialvalue=self.isosurfaces[i].value)
   isocolor = tkColorChooser.askcolor(initialcolor=(self.isosurfaces[i].R,self.isosurfaces[i].G,self.isosurfaces[i].B),title="Isosurface Color")
   isoopacity = tkSimpleDialog.askfloat("Isosurface Opacity","What opacity should the isosurface have? 0 = transparent.",initialvalue=self.isosurfaces[i].opacity)
   surf = isosurface(self.reader.GetOutputPort(),isovalue,isocolor[0][0],isocolor[0][1],isocolor[0][2],isoopacity)
   self.delIso(i)
   self.isosurfaces.append(surf)
   self.isolist.insert(Tkinter.END,str(surf))
   self.ren.AddActor(surf.actor)
コード例 #6
0
ファイル: register.py プロジェクト: ddavedd/Register
 def get_weight(self):
     """Get weight from scale or if not connected from dialog"""
     if self.scale is None: 
         weight = tkSimpleDialog.askfloat("Weight Entry", "Weight (lbs):")
     else:
         try:
             weight = self.scale.get_weight()
         except ScaleError.ScaleError:
             print "Error reading scale, enter weight manually"
             weight = tkSimpleDialog.askfloat("Weight Entry", "Weight (lbs):")
     return weight
コード例 #7
0
ファイル: askfloat.py プロジェクト: anondroid5/Tkinter
	def askstr(self, f):
		theta=tkSimpleDialog.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)
コード例 #8
0
ファイル: GUI.py プロジェクト: samkohn/Geiger-Counter
    def getCountRateHist(self):
        '''Plots a histogram of the count rate.  The number of bins is 
        for the histogram, and the sample length is how long the count rate
        is averaged over (equivalent to "sample length" for the count rate
        vs. time graph.'''

        #check if data has been imported. if not, give a warning
        if self.dataSet:

            #ask for number of bins for histogram
            labelText = "Enter the number of bins"
            numBins = tksd.askinteger("Count Rate Histogram", labelText, parent=self.root, minvalue=1)
            if not numBins:
                return

            #ask for length of sample to calculate count rate
            labelText = "Enter the sample length (seconds)"
            sampleLength = tksd.askfloat("Sample Length", labelText, parent=self.root, minvalue=0)
            if not sampleLength:
                return

            #plot histogram in matplotlib
            pd.plotHistOfCountRates(self.dataSet, sampleLength, numBins)

        else:
            self.showImportAlert()
コード例 #9
0
ファイル: AnimPanel.py プロジェクト: Toonerz/TTRInjector
 def setOffset(self):
     newOffset = askfloat(parent = self.interior(),
                          title = self['text'],
                          prompt = 'Start offset (seconds):')
     if newOffset != None:
         self.offset = newOffset
         self.updateDisplay()
コード例 #10
0
ファイル: gui.py プロジェクト: evhub/rabbit
def popup(which, message, title=None):
    """Displays A Pop-Up Message."""
    if title is None:
        title = which
    which = superformat(which)
    if which == "info":
        return tkMessageBox.showinfo(str(title), str(message))
    elif which == "warning":
        return tkMessageBox.showwarning(str(title), str(message))
    elif which == "error":
        return tkMessageBox.showerror(str(title), str(message))
    elif which == "question":
        return tkMessageBox.askquestion(str(title), str(message))
    elif which == "proceed":
        return tkMessageBox.askokcancel(str(title), str(message))
    elif which == "yesorno":
        return tkMessageBox.askyesno(str(title), str(message))
    elif which == "retry":
        return tkMessageBox.askretrycancel(str(title), str(message))
    elif which == "entry":
        return tkSimpleDialog.askstring(str(title), str(message))
    elif which == "integer":
        return tkSimpleDialog.askinteger(str(title), str(message))
    elif which == "float":
        return tkSimpleDialog.askfloat(str(title), str(message))
コード例 #11
0
def demagnetize():
	max_field = float(F1.get())
	steps = int(F2.get())
	kepcoInit()

	while (field2curr(max_field) >= 3.0):
		max_field = tkSimpleDialog.askfloat('MAGNET OVERLOAD','Choose a new value for the field or decrease the gap!')
	step_field = max_field/(steps+1)
	list_fields = r_[max_field:step_field/2-step_field/10:-step_field]

	for my_field in list_fields:
		my_write_curr = field2curr(my_field)
		kepco.write("CURR %f"%(my_write_curr))
		#print "FIELD++ = ",my_val
		time.sleep(0.2)
		my_read_curr = float(kepco.ask("MEAS:CURR?"))
		my_read_field = curr2field(my_read_curr)
		print "MEASURED FIELD:  ",my_read_field
		my_back_field = my_field-step_field/2
		my_back_write_curr = field2curr(my_back_field)
		kepco.write("CURR %f"%(-my_back_write_curr))
		#print "FIELD-- = ",-my_val_back
		time.sleep(0.2)
		my_read_curr = float(kepco.ask("MEAS:CURR?"))
		my_read_field = curr2field(my_read_curr)
		print "MEASURED FIELD:  ",my_read_field
	kepco.write("CURR 0.0")
	kepco.write("OUTP OFF")
	print "sample demagnetized!"
	del my_write_curr
	del my_read_curr
	del my_read_field
	del my_field
コード例 #12
0
ファイル: SFG_Analysis.py プロジェクト: cmthompson/SFGMe
def go():

    
    root = Tk()
    name_list = DisplaySpectrum(root)
    
    if name_list !='':
        normalize = True
        if normalize == True:
            kNorm = tkSimpleDialog.askfloat('normalization constant', 'norms')
            if kNorm == '':
                kNorm = 1
        else:
            kNorm = 1
               
        view_only = False
        if view_only:
            ConsolidateFiles(name_list, smooth = False)
            i = 5
            plot(arange(2800,3605,5),x[1], 'ks')
        
            plot(arange(2800,3605,5),SG_Smooth(x[1], width = 11,plot = False))
        else:
            
            ConsolidateFiles(name_list, smooth = True)
            SaveSpectrum(root, name_list, x)
    root.destroy()
    
    
    
    root.mainloop()   
    return None
コード例 #13
0
def align_images(im1, im2):

	# Convert images to grayscale
	im1_gray = cv2.cvtColor(im1,cv2.COLOR_BGR2GRAY)
	im2_gray = cv2.cvtColor(im2,cv2.COLOR_BGR2GRAY)
 
	# Find size of image1
	sz = im1.shape

	# Define the motion model
	warp_mode = cv2.MOTION_HOMOGRAPHY
	
	#Define the warp matrix
	warp_matrix = np.eye(3, 3, dtype=np.float32)

	#Define the number of iterations
	number_of_iterations = askinteger("Iterations", "Enter a number between 5 andd 5000",initialvalue=500,minvalue=5,maxvalue=5000)

	#Define correllation coefficient threshold
	#Specify the threshold of the increment in the correlation coefficient between two iterations
	termination_eps = askfloat("Threshold", "Enter a number between 1e-10 and 1e-50",initialvalue=1e-10,minvalue=1e-50,maxvalue=1e-10)

	#Define termination criteria
	criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, number_of_iterations,  termination_eps)
 
	#Run the ECC algorithm. The results are stored in warp_matrix.
	(cc, warp_matrix) = cv2.findTransformECC (im1_gray,im2_gray,warp_matrix, warp_mode, criteria)

	#Use warpPerspective for Homography 
	im_aligned = cv2.warpPerspective (im2, warp_matrix, (sz[1],sz[0]), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)
	
	save1 = asksaveasfilename(defaultextension=".jpg", title="Save aligned image")
	cv2.imwrite(save1,im_aligned)
コード例 #14
0
ファイル: plot_vlbi.py プロジェクト: sma-wideband/phringes_sw
def update_integration_time():
    cur_itime = server.get_integration_time()
    itime = askfloat('Set integration time', 'Seconds: ', parent=root, initialvalue=cur_itime)
    if itime:
        server.stop_correlator()
        server.set_integration_time(itime)
        server.start_correlator()
コード例 #15
0
ファイル: register.py プロジェクト: ddavedd/Register
 def change_cart_amount(self, cart_row):
     """Change the amount of a product entry in a cart"""
     print 'Changing amount of item in cart'
     self.simple_lock()
     if self.cart[cart_row].product.is_by_weight:
         amount = tkSimpleDialog.askfloat("Enter new weight", "Weight:")
     elif self.cart[cart_row].product.is_premarked:
         amount = tkSimpleDialog.askfloat("Enter new amount", "Amount:")
     else:
         amount = tkSimpleDialog.askinteger("Enter new amount", "Amount:")
     self.simple_unlock()
         
     if amount is None:
         print "Canceled"
     elif amount == 0:
         print "Can't update amount to 0, use delete key instead"
     else:
         print "Updated amount " + str(amount)
         self.cart[cart_row].change_amount(amount)
     self.update_cart()
コード例 #16
0
ファイル: gui.py プロジェクト: vdumoulin/pyplanck
 def count(self, *args):
     # TODO: implement a proper register count
     # TODO: add dialog box telling how register count went
     count = askfloat(title="Enter register count", prompt="Register count")
     if count is not None:
         try:
             self.register.count_register(count)
         except CredentialException:
             self.logger.warning("insufficient privileges to count " +
                                 "register")
     # Put focus in barcode field
     self.barcode_field.focus()
コード例 #17
0
ファイル: gui.py プロジェクト: vdumoulin/pyplanck
 def adjust(self, *args):
     amount = askfloat(title="Enter adjustment amount",
                       prompt="Adjustment amount")
     if amount is not None:
         try:
             self.register.adjust(amount)
         except CredentialException:
             self.logger.warning("insufficient privileges to adjust " +
                                 "register count")
         except ValueError as e:
             self.logger.warning("invalid adjustment amount: " + e)
     # Put focus in barcode field
     self.barcode_field.focus()
コード例 #18
0
ファイル: stackProcessing.py プロジェクト: Splo0sh/3DCT
	def getdirint():
		directory = tkFileDialog.askdirectory(parent=root,title='Choose directory with image sequence stack files')
		if not directory: return
		ss_in = tkSimpleDialog.askfloat(
			parent=root, title='Enter ORIGINAL focus step size',
			prompt='Enter ORIGINAL focus step size for:\n{0}'.format(os.path.split(directory)[1]))
		if not ss_in: return
		try:
			pixelsize = pxSize(os.path.join(directory,'Tile_001-001-000_0-000.tif'))
			if pixelsize is None: pixelsize = 0
		except:
			pixelsize = 0
			pass
		ss_out = tkSimpleDialog.askfloat(
			parent=root, title='Enter INTERPOLATED focus step size',
			prompt='Enter INTERPOLATED focus step size for:\n{0}'.format(os.path.split(directory)[1]), initialvalue=pixelsize*1000)
		if not ss_out: return
		saveorigstack = tkMessageBox.askyesno("Save single stack file option", "Do you also want to save single stack file with original focus step size?")
		print "directory: {0}\n".format(directory), "Focus step size in: {0} | out: {1}\n".format(ss_in,ss_out),\
			"Also save single stack file for original spacing?: {0}\n".format(saveorigstack), "Interpolation method: {0}\n".format(int_method.get())
		main(directory,ss_in, ss_out, saveorigstack=saveorigstack, interpolationmethod=int_method.get(), showgraph=bool(showgraph.get()))
		print "Finished interpolation."
		print "="*40
コード例 #19
0
ファイル: dojotimer.py プロジェクト: flavioamieiro/dojotimer
 def set_time(self):
     """
     Gets user input from a dialog and updates
     self.default_time according to it
     """
     try:
         self.default_time = tkSimpleDialog.askfloat(
             'Set time',
             'Specify the time (in minutes)',
             parent=self.top
         )
         self.reset()
     except TypeError:
         pass
コード例 #20
0
ファイル: gui.py プロジェクト: ranic/Circuit-Solver
def addResistorToGrid(x,y):
    canvas.data.clickedResistor = x,y
    canvas.data.draggingResistor = False
    rPrompt = ("Resistance Entry","Enter resistance in Ohms")
    resistance = 0
    while resistance <= 0:
        resistance = tkSimpleDialog.askfloat(rPrompt[0],rPrompt[1])
        # If the user cancels the resistance selection, the resistor disappears
        # and is not added to the circuit
        if resistance == None:
            canvas.data.clickedResistor = -50,-50
            break
    if resistance != None:
        b = Resistor((x-40,y),(x + 40,y), resistance)
        canvas.data.circuit.addElement(b)
コード例 #21
0
 def pack_residue(self, res, chain):
     """
     Packs an individual residue.  Scores before and after.
     """
     
     res = self.pose.pdb_info().pdb2pose(chain, int(res))
     task = TaskFactory.create_packer_task(self.pose)
     task.restrict_to_repacking()
     #task = self._get_set_pack_neighbors(res, task)
     pack_radius = tkSimpleDialog.askfloat(title="Pack radius", prompt = "Please enter the desired neighbor packing radius (A)", initialvalue=5.0)
     if not pack_radius: return;
     restrict_non_nbrs_from_repacking(self.pose, res, task, pack_radius)
     pack_mover = PackRotamersMover(self.score_class.score, task)
     print self.score_class.score(self.pose)
     pack_mover.apply(self.pose)
     print self.score_class.score(self.pose)
コード例 #22
0
 def add_custom(self, *args):
     name = askstring(title="Enter item name", prompt="Item name")
     if name is not None:
         price = askfloat(title="Enter item price", prompt="Item price")
         if price is not None:
             try:
                 self.register.add_custom(name, price)
             except CredentialException:
                 self.logger.warning("insufficient privileges to add " +
                                     "a custom item")
             except ValueError as e:
                 self.logger.warning(e.__str__)
             finally:
                 self.update_order()
     # Put focus in barcode field
     self.barcode_field.focus()
コード例 #23
0
def hyst():
    fileName = h1.get()
    field = float(h2.get())
    step = float(h3.get())
    OUT = []
    FIELDS = []
    kepcoInit()
    dataPathLoc = dataPath()
    try:
        os.stat(dataPathLoc)
    except:
        os.mkdir(dataPathLoc)
    while (field2curr(field) >= 3.0):
        field = tkSimpleDialog.askfloat(
            'MAGNET OVERLOAD',
            'Choose a new value for the field or decrease the gap!')

    steps1 = r_[0.0:field:step]
    steps2 = r_[field:-field:-step]
    steps3 = r_[-field:field + step / 10:step]
    steps = list(steps1) + list(steps2) + list(steps3)
    print "FIELDS ARE: ", steps
    with open(dataPathLoc + '\\' + fileName + '.txt', 'w') as outFile:
        outFile.writelines("Hyst started @ %s\n" % (time.ctime()))
        outFile.writelines("Magnet config. is: pole %s and gap %s\n\n" %
                           (pole_type.get(), gap_value.get()))
        for my_field in steps:
            my_write_curr = field2curr(my_field)
            kepco.write("CURR %f" % (my_write_curr))
            time.sleep(0.1)
            outx_tmp, tt = LockIn_measure()
            outx = outx_tmp
            my_read_curr = float(kepco.ask("MEAS:CURR?"))
            my_read_field = curr2field(my_read_curr)
            print "MEASURED FIELD:   ", my_read_field
            FIELDS.append(my_read_field)
            OUT.append(outx)
            plot_update(FIELDS, OUT)
            outFile.writelines(str(my_read_field) + ' ' + str(outx) + '\n')
            time.sleep(0.01)
    kepco.write("CURR 0.0")
    kepco.write("OUTP OFF")
    print "FINISHED!!!"
    del my_write_curr
    del my_read_curr
    del my_read_field
    del my_field
コード例 #24
0
ファイル: DesignProtocols.py プロジェクト: minghao2016/Jade
 def mutateRes(self, res, chain, new_res):
     new_res = new_res.split(":")
     new_res = new_res[2]
     res = self.pose.pdb_info().pdb2pose(chain, int(res))
     pack_radius = tkSimpleDialog.askfloat(
         title="Pack radius",
         prompt="Please enter the desired neighbor packing radius (A)",
         initialvalue=5.0)
     if pack_radius == None: return
     #print radius
     print self.score_class.score(self.pose)
     print "Mutating to " + new_res
     mutate_residue(self.pose, res, new_res, pack_radius,
                    self.score_class.score)
     print self.score_class.score(self.pose)
     print "Mutagenesis Complete."
     return self.pose
コード例 #25
0
ファイル: cg3_extract.py プロジェクト: imclab/Earth_Tides
def done_cb(*e):
  elevation = 0.0
  out_name = tkFileDialog.asksaveasfilename(title="Save data as...", initialdir=".", initialfile="data.plt")
  try:
    file = open(out_name, "wt")
  except:
    tkMessageBox.showerror("File Error!", "Cannot open %s for writing. Try again.", parent=root)
    return
  if buttons.tetc.query() == 1:
    # get elevation of file
    elevation = tkSimpleDialog.askfloat("Station Elevation", "Enter Station Elevation (in meters)", parent=root, initialvalue=0.0)
  # write header line
  write_header(file, buttons)
  # write data
  write_data(file, data, buttons, start_jul_day, elevation)
  file.close()
  root.quit()
コード例 #26
0
ファイル: gui.py プロジェクト: vdumoulin/pyplanck
 def add_custom(self, *args):
     name = askstring(title="Enter item name", prompt="Item name")
     if name is not None:
         price = askfloat(title="Enter item price",
                          prompt="Item price")
         if price is not None:
             try:
                 self.register.add_custom(name, price)
             except CredentialException:
                 self.logger.warning("insufficient privileges to add " +
                                     "a custom item")
             except ValueError as e:
                 self.logger.warning(e.__str__)
             finally:
                 self.update_order()
     # Put focus in barcode field
     self.barcode_field.focus()
コード例 #27
0
ファイル: display.py プロジェクト: 6/CS-Projects
    def handleCmd5(self):
        # Loading
        load = self.canvas.create_text(430, 10, text="Loading...")
        if self.dataSet == False:
            print "No data set loaded"
            self.canvas.delete(load)
            return
        # Create ARFF file
        toArff = self.dataSet.select([0, 2, 8])
        location = toArff[0]
        time = toArff[1]
        userAgentIndices = toArff[2]

        arffData = []

        for i in range(location.shape[0]):
            uaIdx = userAgentIndices[i]

            # Get the (non-numeric) user agent string
            UA = self.dataSet.nonNum[uaIdx]
            browser = self.dataSet.getBrowser(UA)
            OS = self.dataSet.getOS(UA)
            arffData.append([OS, browser, location[i], time[i]])

        relation = "csweblogs"
        attrs = [
            ["os", ["windows", "linux", "mac", "mobilemac", "sunos", "bsd", "other"]],
            ["browser", ["firefox", "opera", "chrome", "ie", "mobilesafari", "safari", "konqueror", "other"]],
            ["location", [0, 1]],
            ["time", "NUMERIC"],
        ]

        percent = tkSimpleDialog.askfloat(
            "Percentage Subset of Data", "Please specify the percentage of data you would like to write to an arff: "
        )  # 0.01         #[1.0 = 100%]

        if percent == None or percent == False:
            print "User did not select a variable"
            return

        self.arff = arff.ARFF(relation, attrs, arffData, percent)
        filename = "cslogdata.arff"
        self.arff.toFile(filename)
        print "Wrote arff file to " + filename
        self.canvas.delete(load)
コード例 #28
0
ファイル: description_dialog.py プロジェクト: anddrrw/maskgen
def promptForParameter(parent,dir,argumentTuple,filetypes, initialvalue):
    """
     argumentTuple is (name,dict(values, type,descriptipn))
     type is list, imagefile, donor, float, int, time.  float and int have a range in the follow format: [-80:80]
      
    """
    res = None
    if argumentTuple[1]['type'] == 'imagefile':
       val = tkFileDialog.askopenfilename(initialdir = dir, title = "Select " + argumentTuple[0],filetypes = filetypes)
       if (val != None and len(val)> 0):
           res=val
    elif argumentTuple[1]['type'] == 'xmpfile':
       val = tkFileDialog.askopenfilename(initialdir = dir, title = "Select " + argumentTuple[0],filetypes = [('XMP','*.xmp')])
       if (val != None and len(val)> 0):
           res=val
    elif argumentTuple[1]['type'].startswith('donor'):
       d = ImageNodeCaptureDialog(parent, parent.scModel)
       res = d.selectedImage
    elif argumentTuple[1]['type'].startswith('float'):
       v = argumentTuple[1]['type']
       vals = [float(x) for x in v[v.rfind('[')+1:-1].split(':')]
       res = tkSimpleDialog.askfloat("Set Parameter " + argumentTuple[0], argumentTuple[1]['description'],minvalue=vals[0],maxvalue=vals[1], \
          parent=parent, initialvalue=initialvalue)
    elif argumentTuple[1]['type'].startswith('int'):
       v = argumentTuple[1]['type']
       vals = [int(x) for x in v[v.rfind('[')+1:-1].split(':')]
       res = tkSimpleDialog.askinteger("Set Parameter " + argumentTuple[0], argumentTuple[1]['description'],minvalue=vals[0],maxvalue=vals[1], \
         parent=parent,initialvalue=initialvalue)
    elif argumentTuple[1]['type'] == 'list':
       d = SelectDialog(parent,"Set Parameter " + argumentTuple[0],argumentTuple[1]['description'],argumentTuple[1]['values'])
       res = d.choice
    elif argumentTuple[1]['type'] == 'yesno':
       d = SelectDialog(parent,"Set Parameter " + argumentTuple[0],argumentTuple[1]['description'],['yes','no'])
       res = d.choice
    elif argumentTuple[1]['type'] == 'time':
       d = EntryDialog(parent,"Set Parameter " + argumentTuple[0],argumentTuple[1]['description'],validateTimeString,initialvalue=initialvalue)
       res = d.choice
    elif argumentTuple[1]['type'] == 'coordinates':
       d = EntryDialog(parent,"Set Parameter " + argumentTuple[0],argumentTuple[1]['description'],validateCoordinates,initialvalue=initialvalue)
       res = d.choice
    else:
       d = EntryDialog(parent,"Set Parameter " + argumentTuple[0],argumentTuple[1]['description'],None,initialvalue=initialvalue)
       res = d.choice
    return res
コード例 #29
0
ファイル: register.py プロジェクト: ddavedd/Register
 def add_to_cart(self, product):
     """Add a product entry into cart"""
     if len(self.cart) == 0:
         self.start_time = time.time()
             
     product_price = self.get_product_price(product.id)
     print "Added a %s" % product.name
     print "Price: %.2f" % product_price
     if product.is_by_weight:
         #print "Bought by weight, must pop up or read scale"
         weight = self.get_weight()
         if weight is not None:
             cart_entry = CartEntry.ProductCartEntry(product, product_price, weight)
             self.cart.append(cart_entry)
     elif product.is_premarked:
         # get price
         premarked_price = tkSimpleDialog.askfloat("Premarked Price", "Price:")
         if premarked_price is not None:
             cart_entry = CartEntry.ProductCartEntry(product, 1, premarked_price )
             self.cart.append(cart_entry)
     else:
         # """Product not by weight"""
         if self._shift_is_pressed:
            amount = tkSimpleDialog.askinteger("Adding how many?", "Amount:")
            if amount is None:
               print "Tried to add nothing, returning"
               return
         else:
            amount = 1
            
         found = False
         for cart_index in range(len(self.cart)):
             if isinstance(self.cart[cart_index], CartEntry.ProductCartEntry):
                 if self.cart[cart_index].product.id == product.id:
                     found = True
                     self.cart[cart_index].add_some(amount)
         if not found: 
             cart_entry = CartEntry.ProductCartEntry(product, product_price, amount)
             self.cart.append(cart_entry)
             #if self.is_shift_pressed():
             #    self.change_cart_amount(len(self.cart) - 1)
             #print "Added cart item"
             
     self.update_cart()
コード例 #30
0
def hyst():
	fileName = h1.get()
	field = float(h2.get())
	step = float(h3.get())
	OUT=[]
	FIELDS=[]
	kepcoInit()
	dataPathLoc = dataPath()
	try:
		os.stat(dataPathLoc)
	except:
		os.mkdir(dataPathLoc)
	while (field2curr(field) >= 3.0):
		field = tkSimpleDialog.askfloat('MAGNET OVERLOAD','Choose a new value for the field or decrease the gap!')

	steps1 = r_[0.0:field:step]
	steps2 = r_[field:-field:-step]
	steps3 = r_[-field:field+step/10:step]
	steps = list(steps1)+list(steps2)+list(steps3)
	print "FIELDS ARE: ", steps
	with open(dataPathLoc+'\\'+fileName+'.txt','w') as outFile:
		outFile.writelines("Hyst started @ %s\n"%(time.ctime()))
		outFile.writelines("Magnet config. is: pole %s and gap %s\n\n"%(pole_type.get(),gap_value.get()))
		for my_field in steps:
			my_write_curr = field2curr(my_field)
			kepco.write("CURR %f"%(my_write_curr))
			time.sleep(0.1)
			outx_tmp,tt = LockIn_measure()
			outx = outx_tmp
			my_read_curr = float(kepco.ask("MEAS:CURR?"))
			my_read_field = curr2field(my_read_curr)
			print "MEASURED FIELD:   ",my_read_field
			FIELDS.append(my_read_field)
			OUT.append(outx)
			plot_update(FIELDS,OUT)
			outFile.writelines(str(my_read_field)+' '+str(outx)+'\n')
			time.sleep(0.01)
	kepco.write("CURR 0.0")
	kepco.write("OUTP OFF")
	print "FINISHED!!!"
	del my_write_curr
	del my_read_curr
	del my_read_field
	del my_field
コード例 #31
0
ファイル: DesignProtocols.py プロジェクト: minghao2016/Jade
    def _get_set_pack_neighbors(self, res, task):
        """
        Asks for packing radius.  Sets task to prevent repacking for all but within that radius.
        Original Author: Evan H. Baugh, Johns Hopkins University. from mutants.py.
        Somehow not working with task
        """
        radius = tkSimpleDialog.askfloat(
            title="Pack radius",
            prompt="Please enter the desired neighbor packing radius (A)",
            initialvalue=0.0)

        center = self.pose.residue(res).nbr_atom_xyz()
        for i in range(1, self.pose.total_residue() + 1):
            # only pack the mutating residue and any within the pack_radius
            if not i == res or center.distance_squared(
                    self.pose.residue(i).nbr_atom_xyz()) > radius**2:
                task.nonconst_residue_task(i).prevent_repacking()

        return task
コード例 #32
0
def Pressed_Change_MMD():
    global list_of_objects
    print "Pressed_Change_MMD"
    newMMD = tkSimpleDialog.askfloat('MMD ', 'Select new MMD value.')
    try:
        if float(newMMD) > 0:
            print "MMD ok"
            if set_all_var.get() == 0:  #Selected volume
                global selected_volume_index
                list_of_objects[selected_volume_index].VolumeMMD = newMMD
            else:  #All volumes
                for i in list_of_objects:
                    i.VolumeMMD = newMMD
        else:
            tkMessageBox.showinfo("Error", "MMD must be greater than 0.")
            print "Chosen value <= 0"
    except:
        tkMessageBox.showinfo("Error", "Value not a float.")
        print "Not a float or < 0"
コード例 #33
0
ファイル: gui.py プロジェクト: ranic/Circuit-Solver
def addVoltageToGrid(x,y):
    canvas.data.clickedVoltage = (x,y)
    canvas.data.draggingVoltage = False
    vPrompt = ("Voltage Entry","Enter voltage in Volts")
    voltValue = 0
    # waits till a user selects a non-zero voltage value
    while voltValue == 0:
        voltValue = tkSimpleDialog.askfloat(vPrompt[0],vPrompt[1])
        # If the user cancels, remove the voltage source
        if voltValue == None:
            canvas.data.clickedVoltage = (-50,-50)
            break
    # Otherwise, create the connection object for the voltage
    if voltValue != None:
        a = VoltageSource((x,y + 40),(x,y-40), voltValue)
        canvas.data.circuit.addElement(a)
    # adds ground to the bottom of the first voltage source
    if len(canvas.data.circuit.voltageSources()) == 1 and voltValue != None:
        canvas.data.circuit.addGround((x,y + 40))
コード例 #34
0
ファイル: GUI.py プロジェクト: samkohn/Geiger-Counter
    def getCountRate(self):
        '''Plots the count rate as a function of time. The rates are calculated
        for each "bin" (i.e. independent sample)'''

        #Check if data has been imported. if not, give a warning
        if self.dataSet:

            #prompt for desired bin spacing
            labelText = "Enter the desired sample length in seconds"
            binSpacing = tksd.askfloat("Count Rate", labelText, parent=self.root, minvalue=0, initialvalue=1)
            if not binSpacing:
                return

            #plot the count rate in matplotlib
            pd.plotCountRate(self.dataSet, binSpacing)
            
        else:
            #say that you need to import data first
            self.showImportAlert()
コード例 #35
0
ファイル: DesignProtocols.py プロジェクト: minghao2016/Jade
 def design_residue(self, res, chain):
     """
     Designs a residue by task not restricting to repacking.
     """
     res = self.pose.pdb_info().pdb2pose(chain, int(res))
     pack_radius = tkSimpleDialog.askfloat(
         title="Pack radius",
         prompt="Please enter the desired neighbor packing radius (A)",
         initialvalue=5.0)
     if not pack_radius: return
     task = TaskFactory.create_packer_task(self.pose)
     for i in range(1, self.pose.total_residue() + 1):
         if i != res:
             task.nonconst_residue_task(i).restrict_to_repacking()
     restrict_non_nbrs_from_repacking(self.pose, res, task, pack_radius)
     pack_mover = PackRotamersMover(self.score_class.score, task)
     print self.score_class.score(self.pose)
     pack_mover.apply(self.pose)
     print self.score_class.score(self.pose)
コード例 #36
0
def set_field():
	field = float(F1.get())
	kepco.write("*RST")
	kepco.write("FUNC:MODE CURR")
	kepco.write("VOLT 5.0e1")
	kepco.write("OUTP ON")

	while (field2curr(field) >= 3.0):
		field = tkSimpleDialog.askfloat('MAGNET OVERLOAD','Choose a new value for the field or decrease the gap!')

	my_write_curr = field2curr(field)
	kepco.write("CURR %f"%(my_write_curr))
	time.sleep(0.1)
	my_read_curr = float(kepco.ask("MEAS:CURR?"))
	my_read_field = curr2field(my_read_curr)
	print "FIELD SET TO: ",my_read_field
	del my_write_curr
	del my_read_curr
	del my_read_field
コード例 #37
0
def test_motor():
	acc_deg = float(accEntry.get())
	dec_deg = float(decEntry.get())
	vel_deg = float(velEntry.get())
	my_deg = 16.66666667
	acc = acc_deg*my_deg**2
	dec = dec_deg*my_deg**2
	vel = vel_deg*my_deg
	motor.write('svo 1 1')
	motor.write('ron 1 0')
	motor.write('acc 1 %f'%(acc))
	motor.write('dec 1 %f'%(dec))
	motor.write('vel 1 %f'%(vel))
	motor.write('vel?'); print motor.read()
	motor.write('acc?'); print motor.read()
	motor.write('ron?'); print 'RON = ',motor.read()
	motor.write('svo?'); print 'SVO = ',motor.read()
	my_range = tkSimpleDialog.askfloat('MOVE RANGE (degree)','Enter a range value for your move in degrees!')
	print 'asked angular range:',my_range
	motor.write('mvr 1 %f'%(my_range*my_deg))
コード例 #38
0
    def calcRunTime(self):
        """
        Calculates approximate runtime, graphs it if numpy and matplotlib can be imported.
        """

        time = tkSimpleDialog.askfloat(title="Time",
                                       prompt="Approx Time(min) per Pose: ")
        try:
            import matplotlib.pyplot as plt
            import numpy as np
            #totalNodes=tkSimpleDialog.askinteger(title = "Nodes", prompt = "Total Nodes on cluster")
            totalNodes = 100
            x_axes = []
            y_axes = []
            m = ((time / 60) * self.calcTotal())
            for x in range(1, totalNodes + 1):
                y = (((time / 60) * self.calcTotal()) / x) / 24
                x_axes.append(x), y_axes.append(y)
            plt.xlabel('Nodes')
            plt.ylabel('Days')
            plt.plot(x_axes, y_axes, 'o')
            plt.grid(True)
            plt.show()
            return

        except ImportError:
            self.textHelp.delete(1.0, END)
            nodes = tkSimpleDialog.askinteger(
                title="Nodes", prompt="Approx Number of Nodes: ")

            time = time / 60
            TotalCpuTime = self.calcTotal() * time
            TotalCpuTimeDays = TotalCpuTime / 24
            self.textHelp.insert(
                1.0, "Total CPU time is: " + repr(TotalCpuTime) +
                " Hours or " + repr(TotalCpuTimeDays) + " Days")
            TotalTime = TotalCpuTime / nodes
            TotalTimeDays = TotalTime / 24
            self.textHelp.insert(
                1.0, "Total Time is: " + repr(TotalTime) + " Hours or " +
                repr(TotalTimeDays) + " Days" + "\n")
コード例 #39
0
def set_field():
    field = float(F1.get())
    kepco.write("*RST")
    kepco.write("FUNC:MODE CURR")
    kepco.write("VOLT 5.0e1")
    kepco.write("OUTP ON")

    while (field2curr(field) >= 3.0):
        field = tkSimpleDialog.askfloat(
            'MAGNET OVERLOAD',
            'Choose a new value for the field or decrease the gap!')

    my_write_curr = field2curr(field)
    kepco.write("CURR %f" % (my_write_curr))
    time.sleep(0.1)
    my_read_curr = float(kepco.ask("MEAS:CURR?"))
    my_read_field = curr2field(my_read_curr)
    print "FIELD SET TO: ", my_read_field
    del my_write_curr
    del my_read_curr
    del my_read_field
コード例 #40
0
    def get_top_scoring_by_percent(self, percent=False, ask_copy_results=True):
        """
        Gets top percent of poses - sets self.top_scoring_by_percent.  Runs copy_results
        """
        if not self.score_pairs:print "Please load scores.";return
        if not percent:

            percent = tkSimpleDialog.askfloat(title="Cutoff", prompt="Please enter a percent for top cutoff", initialvalue=.05)
            if not percent:return
        if percent>1.0:
            percent = percent/float(100)
        total_num = round(percent*len(self.score_pairs))
        print repr(percent)
        for i in range(0, int(total_num)):
            score = self.score_pairs[i][0]; fullpath = self.score_pairs[i][1]
            print "%.2f"%score+" "+fullpath
            self.top_scoring_by_percent_map[fullpath]=score

        if ask_copy_results:
            self.copy_results(self.top_scoring_by_percent_map, "TOP_%.2f"%percent+"_PERCENT")
        else:
            return self.top_scoring_by_percent_map
コード例 #41
0
    def TopUp(self):
        print "topup"
        self.amt = tkSimpleDialog.askfloat(
            "Balance Top Up (US Dollars)",
            "How much are you willing to top up?")
        self.balance += self.amt
        self.f = open(Logwin.U.get() + ".txt")
        self.templist = self.f.readlines()
        self.f.close()
        self.templist.pop(2)
        self.templist.insert(2, "USDbal=" + str(self.balance) + "\n")
        self.g = open(Logwin.U.get() + ".txt", "w")
        self.g.writelines(self.templist)
        self.g.write("@" +
                     datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") +
                     "@" + "Top Up" + "@" + str(self.amt) + "\n")
        self.g.close()
        self.logs.append(
            ("@" + datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") +
             "@" + "Top Up" + "@" +
             str(self.amt)).split("@"))  #Inaccurate only on a slow computer

        self.refresh()
コード例 #42
0
ファイル: target2.py プロジェクト: rjonnal/looky_old
 def toggleSettingScale(self, x, y):
     #         print 'toggle',self.settingScale
     if not self.settingScale:
         self.settingScale = True
         self.xstart = x
         self.ystart = y
     else:
         self.xstop = x
         self.ystop = y
         dx = x - self.xstart
         dy = y - self.ystart
         dpx = math.sqrt(dx**2.0 + dy**2.0)
         self.partScreen()
         ddeg = tkSimpleDialog.askfloat(
             'Enter degrees', 'Please enter corresponding degrees:')
         self.fullScreen()
         self.pxPerDeg = float(dpx) / float(ddeg)
         self.logger.logThis(
             'setting fundus image scale, %0.0f pixels / %0.1f deg =  %0.1f px/deg'
             % (dpx, ddeg, self.pxPerDeg))
         self.scaleSet = True
         self.settingScale = False
         self.makeGrid()
コード例 #43
0
def MakeNewFile():
    freq_array = array('f', [])
    #    entries=input("How Many Entries?  ")
    entries = tkSimpleDialog.askinteger('entries',
                                        'How many entries?',
                                        parent=root)
    #x<11
    #print ("Enter frequencies in Hz, with no decimal points")
    #fout = open("freq.dat", "a")
    #while True:
    for i in range(0, entries):
        #        print i
        #      freq=input("Frequency ")
        freq = tkSimpleDialog.askfloat('entry',
                                       'enter frequency ' + str(i + 1),
                                       parent=root)
        freq_array = array("f", [freq])
        #fout.write(freq)
        #         frq=float(freq)
        with open("freqtest.dat", "ab") as x:
            #                 pickle.dump(frq, x)p
            freq_array.tofile(x)
    x.close()
    DisplayFreqs()
コード例 #44
0
def XTGaussFiltering(aImarisId):
    # Create an ImarisLib object
    vImarisLib = ImarisLib.ImarisLib()

    # Get an imaris object with id aImarisId
    vImaris = vImarisLib.GetApplication(aImarisId)

    # Initialize and launch Tk window
    vRootTkWindow = Tk()
    # Hide the default Tk root window
    vRootTkWindow.withdraw()

    # Check if the object is valid
    if vImaris is None:
        print('Could not connect to Imaris!')
        tkMessageBox.showwarning("connection failed",
                                 "Could not connect to Imaris!")
        time.sleep(2)
        return

    # Get the dataset
    vDataSet = vImaris.GetDataSet()
    if vDataSet is None:
        print('An image must be loaded to run this XTension!')
        tkMessageBox.showwarning(
            "Image needed", "An image must be loaded to run this XTension!")
        time.sleep(2)
        return

    vChannelIndex = 0
    vNumberOfChannels = vDataSet.GetSizeC()
    # Get the channel index from the user if there are multiple channels
    if vNumberOfChannels > 1:
        # Create and display the channel selection window
        vChannelTkWindow = Toplevel()
        vChannelTkWindow.title("Channel")

        Label(vChannelTkWindow,
              text="""Choose the channel to be smoothed:""",
              justify=LEFT,
              padx=5).pack()

        vChannelRadioButton = IntVar()
        # Set default value
        vChannelRadioButton.set(-1)
        for vIndice in range(vNumberOfChannels):
            # Add a radio button for each channel
            vRadioButton = Radiobutton(vChannelTkWindow,
                                       text=str(vIndice + 1) + " - " +
                                       vDataSet.GetChannelName(vIndice),
                                       padx=20,
                                       pady=5,
                                       variable=vChannelRadioButton,
                                       value=vIndice)
            # Set the layout
            vRadioButton.pack(anchor=W)
        vValidationButton = Button(vChannelTkWindow,
                                   text="OK",
                                   command=vChannelTkWindow.destroy)
        vValidationButton.pack(expand=1, fill=BOTH)
        # Wait for the answer of the channel selection window
        vRootTkWindow.wait_window(vChannelTkWindow)

        # Get the selected value
        vChannelIndex = vChannelRadioButton.get()
        # If the window is closed without any channel selected
        if vChannelIndex is -1:
            return

    vSigma = tkSimpleDialog.askfloat("Smoothing value",
                                     "Specify the smoothing value: ")
    # If a click on "Cancel" occured
    if vSigma is None:
        return

    # The GUI windows are not needed anymore
    vRootTkWindow.destroy

    vIP = vImaris.GetImageProcessing()
    vIP.GaussFilterChannel(vDataSet, vChannelIndex, vSigma)
コード例 #45
0
ファイル: dialogTable.py プロジェクト: thanggc/libros
# define a name:callback demos table

from tkFileDialog import askopenfilename  # get standard dialogs
from tkColorChooser import askcolor  # they live in Lib/lib-tk
from tkMessageBox import askquestion, showerror
from tkSimpleDialog 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')
}
コード例 #46
0
ファイル: recording.py プロジェクト: xichen11/FM_location
__author__ = 'Xi Chen'

import subprocess
import os
import time
import sys
import tkSimpleDialog
import Tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
    root.withdraw()
    file_name = tkSimpleDialog.askstring(title='Name of the record',
                                         prompt='Enter here: ')
    if file_name is None:
        sys.exit(0)
    measure_time = tkSimpleDialog.askfloat(title='Duration in seconds',
                                           prompt='Enter here: ')
    if measure_time is None:
        sys.exit(0)

    time.sleep(0.5)
    # home_path = os.path.expanduser('~')
    os.chdir(os.getcwd() + '/grc/')
    cmd_str = '--command=python fm_recv.py ' + file_name
    subprocess.Popen(['gnome-terminal', cmd_str])
    time.sleep(measure_time + 2)
    os.system("sudo pkill python")
コード例 #47
0
def getProtocolLists(LisBox):
    VarItem = LisBox.get(LisBox.curselection())
    x = len(DicProtocol)
    x += 1
    #Creates Dictionaries to tie them all together
    p = "p" + repr(x)
    print p
    #OLD WAY: DicProtocol[p] = [VarItem, int(VarRounds.get()), int(Varcheck_button_Cen.get()), int(VarPym.get()), int(VarFragLen.get())]
    DicProtocol[p] = dict()
    #NEW WAY: LOAD INTO DICTofDICT
    #NEWNEW way is to have a class hold all of these in an object!!!
    #[name] = VarItem(name)
    #[rounds] = Rounds (integer)
    #[centroid]= Centroid (integer) 0 or 1
    #[obs] = PyMOL Observer (integer) 0 or 1

    #[shear] = Shear Settings
    #[lisloops] = Loop Settings
    #[score] = Score Function!!! (Literally)
    #Accessory Files
    #[frag] = Fragment Length (int) 9 or 3.  Should be context dependendant.
    #[fragfile] = Accessory File - Will be actual frag file soon.
    #Vaccinity:
    #[neighborcuttoff] = Neighbor Distance for vaccinity measure
    #[onlyaround] = 0 or 1.  1 means only around vaccinity, not including residues
    #[fixloopbb] = 0 or 1.  1 indicates to keep bb of loop fixed during Relax Vaccinity
    #[fixvacbb] = 0 or 1.  1 indicates to keep bb of vaccinity fixed during Relax Vaccinity.
    #Interface
    #[interfacecutoff] = Interface Cuttoff distance

    #[interfacefixed] = Chains to keep fixed in Interface Protocols: (A-B-C)
    #[interfacepack] = Chains to only allow repacking for Relax Protocols

    #Only Around Combinations: (onlyaround, fixloopbb, fixvacbb)
    #0, 0, 0: Relax All
    #0, 1, 0: Relax Vaccinity, Keep Loop chi open
    #0, 0, 1: Relax Loop, Keep vaccinity chi open
    #1, 0, 0: Relax Vaccinity, Keep Loop chi closed
    #Other : All default to Pack Vaccinity - So we change the name to Pack Vaccinity.

    DicProtocol[p] = dict()

    #Asks User to input the number of Rounds Desired.
    rounds = tkSimpleDialog.askinteger(
        title='rounds',
        prompt='Please enter the number of rounds desired: ',
        initialvalue=1)
    VarRounds.set(repr(rounds))
    DicProtocol[p]['name'] = VarItem
    #OLD: DicProtocol[p]['rounds'] = int(VarRounds.get())
    DicProtocol[p]['rounds'] = rounds
    DicProtocol[p]['centroid'] = int(Varcheck_button_Cen.get())
    DicProtocol[p]['obs'] = int(VarPym.get())
    #DicProtocol[p]['frag'] = int(VarFraglen.get())
    #DicProtocol[p]['score] = Get Currently Set Score
    DicProtocol[p]['score'] = score

    #Adds the LisLoop - Python has references too, so be careful!
    DicProtocol[p]['lisloops'] = LisLoop[:]
    #This handles protocol specific data
    #Shear Data
    VarItemSplit = VarItem.split()

    #Peudofix for the rest of the code where it tests itemsplit[1] etc.
    if len(VarItemSplit) == 1:
        VarItemSplit[1:4] = "0"

    #if "Frag":
    #Prompt for FragLength and Choose FragFile
    #This Needs to be protocol specific prompting.
    #Sets ShearSettings from WINDOW Prompt
    if (VarItemSplit[0] == "Shear" and VarItemSplit[1] == "Custom"):
        print "Appending Custom Shear Protocol"
        ShearSettings = [
            int(Shear1.get()),
            int(Shear2.get()),
            int(Shear3.get()),
            int(Shear4.get()),
            ShearKT.get(),
            shearAnneal.get()
        ]

        DicProtocol[p]['shearsettings'] = ShearSettings[:]
    elif (VarItemSplit[0] == "Shear" and VarItemSplit[1] == "CustomFile"):
        print "Appending Accessory Shear File"
    elif (VarItemSplit[0] == "Shear"):
        print "Appending default shear settings..."
        ShearSettings = []
        for i in range(0, 4):
            ShearSettings.append(VarItemSplit[1])
        ShearSettings.append(ShearKT.get())
        ShearSettings.append(shearAnneal.get())
        DicProtocol[p]['shearsettings'] = ShearSettings[:]
        #OLD: DicProtocol[p].append(ShearSettings)

    #Asks user for Cutoff Length and Vaccinity Settings for each protocol.
    if VarItemSplit[1] == "Vaccinity":

        length = tkSimpleDialog.askfloat(
            title="vaccinity",
            prompt="entry_er Vaccinity Cuttoff (A)",
            initialvalue=5.0)
        DicProtocol[p]['neighborcutoff'] = length
        if VarItemSplit[0] == "Pack" and VarItemSplit[1] == "Vaccinity":
            onlyaround = tkMessageBox.askquestion(
                title="onlyaround",
                message="Pack/Relax Given residues in addition to vaccinity?",
                default=tkMessageBox.YES)
            if onlyaround == "yes":
                print "Packing Vaccinity and residues chosen..."
                DicProtocol[p]['onlyaround'] = 0
            else:
                print "Only packing Vaccinity...."
                DicProtocol[p]['onlyaround'] = 1

        #Relax and Minimize Vaccinity Prompts
    if VarItem == "Relax Vaccinity" or VarItem == "Minimize Vaccinity":
        #OLD: fixBB = tkMessageBox.askquestion(title = "fix surrounding", message = "Fix Backbone of Vaccinity?", default = tkMessageBox.YES)
        #OLD: if fixBB == 'yes':
        #OLD: DicProtocol[p]['fixvacbb'] = 1
        #OLD: else:
        #OLD: DicProtocol[p]['fixvacbb'] = 0
        #OLD: if onlyaround == "yes":
        #OLD: fixBBLoop = tkMessageBox.askquestion(title = 'Loop', message = "Fix Backbone of Loop Residues?", default = tkMessageBox.NO)
        #OLD: if fixBBLoop == 'yes':
        #OLD: DicProtocol[p]['fixloopbb'] = 1
        #OLD: else:
        #OLD: DicProtocol[p]['fixloopbb'] = 0
        #OLD: if (onlyaround == "no" and fixBB == 'yes'):
        #OLD: tkMessageBox.showinfo(message = "BB vaccinity fixed, no packing of loop residues - Runnng Rosetta Pack Residues instead of relax.")
        #OLD: DicProtocol[p]['name']="Pack Vaccinity"
        #OLD: if onlyaround == 'yes' and fixBB =='yes' and fixBBLoop == 'yes':
        #OLD: tkMessageBox.showinfo(message = "BB vaccinity fixed for loop and surrounding residues - Running Rosetta Pack Residues instead of relax.")
        #OLD: DicProtocol[p]['name']="Pack Vaccinity"

        vacwindow = vaccinityrelaxwindow(c)
        #c.wait_window(vacwindow)

        if vacwindow.result == None:
            print "Canceled.  Using Default settings for protocol."
            FixTarget = "Open"
            FixVaccinity = "Open"
            FixBoth = "UnSet"
        else:
            (FixTarget, FixVaccinity, FixBoth) = vacwindow.result
        #Here, we translate what each of these mean (Hopefully):

        target = [0, 0]
        #(BB, Chi) 0 means to keep; 1 means to fix
        vaccinity = [0, 0]

        #BOTH
        if FixBoth == "Vaccinity":
            vaccinity = [1, 1]
            print "Only Relaxing Target.  You Should run Loop Relax instead."
        elif FixBoth == "Target":
            target = [1, 1]
            print "Only Relaxing Vaccinity"

        #TARGET

        if FixTarget == "Open":
            print "Opening Target"
            target = [0, 0]
        elif FixTarget == "Fix":
            print "Fixing all atoms of Target"
            target = [1, 1]
        elif FixTarget == "Fix BB":
            print "Fixing backbone of Target"
            target[0] = 1
        elif FixTarget == "Fix Chi":
            print "Fixing rotamers of Target"
            target[1] = 1

        #VACCINITY
        if FixVaccinity == "Open":
            print "Opening Vaccinity"
            vaccinity = [0, 0]
        elif FixVaccinity == "Fix":
            print "Fixing all atoms of Vaccinity"
            vaccinity = [1, 1]
        elif FixVaccinity == "Fix BB":
            print "Fixing backbone of Target"
            vaccinity[0] = 1
        elif FixVaccinity == "Fix Chi":
            vaccinity[1] = 1

        print vaccinity
        print target
        print "Final Settings for Relax Protocol:\n"
        #TARGET
        if target[0] == 1 and target[1] == 1:
            print "Fixing Target Completely"
        elif target[0] == 0 and target[1] == 0:
            print "Relaxing Target Completely"
        elif target[0] == 0:
            print "Relaxing BackBone of Target"
        elif target[1] == 0:
            print "Repacking Rotamers of Target"

        #VACCINITY
        if vaccinity[0] == 1 and vaccinity[1] == 1:
            print "Fixing Vaccinity Completely"
        elif vaccinity[0] == 0 and target[1] == 0:
            print "Relaxing Vaccinity Completely"
        elif vaccinity[0] == 0:
            print "Relaxing BackBone of Vaccinity"
        elif vaccinity[1] == 0:
            print "Repacking Rotamers of Vaccinity"

        print "\n\n"
        print "Switching Protocols as Needed:"
        if vaccinity == [1, 1] and target == [1, 1]:
            tkMessageBox.showerror(
                message="Everything is fixed!  Remove Protocol and Try Again!")
            return

        if vaccinity[0] == 1 and target[0] == 1:
            print "Only running Side Chain Packing Protocol..."

        DicProtocol[p]['vaccinity'] = vaccinity
        DicProtocol[p]['target'] = target
        #print FixBB
        #print FixChi
        #print FixBoth
        #return
    #Interface Prompts
    print VarItem
    print VarItemSplit[1]
    if VarItemSplit[1] == "Interface":
        #Chain Cutoff Distance
        length = tkSimpleDialog.askfloat(
            title="interface",
            prompt="entry_er Interface Cuttoff (A)",
            initialvalue=6.0)
        interface = tkSimpleDialog.askstring(
            title="interface", prompt="entry_er Interface (A:CD / AB:CD:F)")
        #Options if you are specifically looking for interfaces between multiple chains.
        #Handles Fully Restricking some chains
        intopt = tkMessageBox.askquestion(title="interface",
                                          message="Fix any Interface Chains?",
                                          default=tkMessageBox.NO)
        if intopt == "yes":
            interfaceKeep = tkSimpleDialog.askstring(
                title="interface",
                prompt="entry_er chains to keep fixed (A-B-C) :",
                initialvalue="0")
            DicProtocol[p]['interfacefixed'] = interfaceKeep
        else:
            DicProtocol[p]['interfacefixed'] = 0
        #Handles Restricting some chains to repacking
        if VarItem == "Relax Interface":
            intopt2 = tkMessageBox.askquestion(
                title='interface',
                message="Restrict any Interface Chains to rePacking?",
                default=tkMessageBox.NO)
            if intopt2 == "yes":
                interfacePack = tkSimpleDialog.askstring(
                    title="interface",
                    prompt="Enter chains to only allow repacking (A:B:C)")
                DicProtocol[p]['interfacepack'] = interfacePack
            else:
                DicProtocol[p]['interfacepack'] = 0
        DicProtocol[p]['interfacecutoff'] = length
        DicProtocol[p]['interface'] = interface
    #Asks for Tolerance and Type for minmimization
    if VarItemSplit[1] == "Minimize" or VarItemSplit[0] == "Minimize":
        tol = tkSimpleDialog.askfloat(title="tolerance",
                                      prompt="Please Enter Tolerance",
                                      initialvalue=.1)
        DicProtocol[p]['tolerance'] = tol
コード例 #48
0
    def isWrong(self):
        print(
            "Coordinates are wrong, enter correct location data:                  "
            + self.unknown_locations[0]['unknown_loc']['loc_name'])
        print("Leaving location in database for secondary verification")

        self.undo.config(state="normal")
        self.lastAction = "WRONG"
        self.lastLocation = copy.deepcopy(self.unknown_locations[0])

        # Prompt user to correct the coordinates
        # User can `cancel` or fill out prompts
        latitude = tkSimpleDialog.askfloat(
            "Latitude",
            "Enter latitude value:",
            initialvalue=self.unknown_locations[0]['db_loc']['loc_latitude'],
            minvalue=34.05,
            maxvalue=34.08)
        longitude = tkSimpleDialog.askfloat(
            "Longitude",
            "Enter longitude value:",
            initialvalue=self.unknown_locations[0]['db_loc']['loc_longitude'],
            minvalue=-118.46,
            maxvalue=-118.43)
        name = tkSimpleDialog.askstring(
            "Alternate Name", "Enter alternate name or click cancel:")

        # If any changes were made then update original location object
        updated = False
        if latitude and latitude != self.unknown_locations[0]['db_loc'][
                'loc_latitude']:
            print("New latitude: " + str(latitude))
            self.unknown_locations[0]['db_loc']['loc_latitude'] = latitude
            updated = True
        if longitude and longitude != self.unknown_locations[0]['db_loc'][
                'loc_longitude']:
            print("New longitude: " + str(longitude))
            self.unknown_locations[0]['db_loc']['loc_longitude'] = longitude
            updated = True
        if name and name.lower() not in (alt.lower()
                                         for alt in self.unknown_locations[0]
                                         ['db_loc']['loc_alt_names']):
            print("New name: " + name)
            self.unknown_locations[0]['db_loc']['loc_alt_names'].append(name)
            updated = True

        # If updated, update location in database
        # TODO: update locations database
        if updated:
            print("Updating location in database...")
            self.unknown_locations[0]['updated_location'] = True
            self.unknown_locations[0]['db_loc'][
                'map_url'] = "https://www.google.com/maps/place/" + str(
                    self.unknown_locations[0]['db_loc']
                    ['loc_latitude']) + "," + str(
                        self.unknown_locations[0]['db_loc']['loc_longitude'])
            tkinter_unknown_collection.replace_one(
                {'_id': self.unknown_locations[0]['_id']},
                self.unknown_locations[0])
        else:
            print("Nothing changed, event is left unmodified...")

        self.focus()
        # Move on to next location, update all displays
        self.changeText()
コード例 #49
0
 def ask_float(self):
     x = tkSimpleDialog.askfloat('Float Asker', 'Give me your float:')
     print(x)
コード例 #50
0
def m_hyst():
    root_fileName = h1.get()
    Hmax = float(h2.get())
    step = float(h3.get())
    mm = int(h4.get())
    OUT = []
    FIELDS = []
    dataPathLoc = dataPath()
    m_Path = dataPathLoc + "\\" + root_fileName
    try:
        os.stat(m_Path)
    except:
        os.mkdir(m_Path)
    while (field2curr(Hmax) >= 3.0):
        Hmax = tkSimpleDialog.askfloat(
            'MAGNET OVERLOAD',
            'Choose a new value for the field or decrease the gap!')
    steps1 = ['%.8f' % elem for elem in r_[0:Hmax + step / 10:step]]
    steps2 = ['%.8f' % elem for elem in r_[Hmax:-Hmax:-step]]
    steps3 = ['%.8f' % elem for elem in r_[-Hmax:Hmax + step / 10:step]]
    steps = list(steps1) + list(steps2) + list(steps3)
    kepcoInit()
    #	with open(m_Path+'\\'+root_fileName+'.txt','w') as outFile:
    #		for my_field in steps:
    #			my_write_curr = field2curr(float(my_field))
    #			kepco.write("CURR %f"%(my_write_curr))
    #			outx_tmp,tt = LockIn_measure()
    #			outx = outx_tmp
    #			my_read_curr = float(kepco.ask("MEAS:CURR?"))
    #			my_read_field = curr2field(my_read_curr)
    #			print "MEASURED FIELD:   ",my_read_field
    #			FIELDS.append(my_read_field)
    #			OUT.append(outx)
    #			plot_update(FIELDS,OUT)
    #			outFile.writelines(str(my_read_field)+" "+str(outx)+"\n")
    #			time.sleep(0.01)
    #		del my_field
    #		del my_write_curr
    #		del my_read_curr
    #		del my_read_field
    for val in steps1:
        my_write_curr = field2curr(float(val))
        kepco.write("CURR %f" % (my_write_curr))
        time.sleep(0.1)
    del my_write_curr
    NN = len(list(steps2) + list(steps3))
    YY = zeros((mm, len(steps)), float)
    yy_LIN = zeros((mm, NN), float)
    for scan in range(mm):
        del FIELDS
        del OUT
        FIELDS = []
        OUT = []
        with open(m_Path + "\\" + "hyst_" + str(scan + 1).zfill(4) + ".txt",
                  "w") as outFile:
            for index, my_field in enumerate(list(steps2) + list(steps3)):
                my_write_curr = field2curr(float(my_field))
                kepco.write("CURR %f" % (my_write_curr))
                outx_tmp, tt = LockIn_measure()
                outx = outx_tmp
                YY[scan][index] = outx
                my_read_curr = float(kepco.ask("MEAS:CURR?"))
                my_read_field = curr2field(my_read_curr)
                print "MEASURED FIELD:   ", my_read_field
                FIELDS.append(my_read_field)
                OUT.append(outx)
                plot_update_multi(FIELDS, OUT, scan + 1)
                outFile.writelines(str(my_read_field) + " " + str(outx) + "\n")
            del my_field
            del my_write_curr
            del my_read_curr
            del my_read_field
        with open(
                m_Path + "\\" + "hyst_" + str(scan + 1).zfill(4) + "_LIN.txt",
                "w") as outFile:
            NN = len(list(steps2) + list(steps3))
            yyN = YY[scan][NN - 1]
            yy0 = YY[scan][0]
            delta_yy = yyN - yy0
            for ii in range(NN):
                yy_LIN[scan][ii] = YY[scan][ii] - delta_yy / (NN - 1) * ii
                outFile.writelines(
                    str(FIELDS[ii]) + " " + str(yy_LIN[scan][ii]) + "\n")
        print "FINISHED HYST NO. >>> ", scan + 1
        YY_sum = zeros(len(steps), float)
        YY_mean = zeros(len(list(steps2) + list(steps3)), float)
        if scan != 0:
            for index in range(scan):
                YY_sum = [(YY_sum[ii] + yy_LIN[index][ii])
                          for ii in range(len(list(steps2) + list(steps3)))]
            YY_mean = [(YY_sum[ii] / scan)
                       for ii in range(len(list(steps2) + list(steps3)))]
            plot_update_mean(FIELDS, YY_mean)
        time.sleep(1)
    set_field_zero()
    del index
    #	del YY_mean
    #	del YY_sum
    #	YY_sum = zeros(len(steps),float)
    #	for index in range(mm):
    #		YY_sum = [(YY_sum[ii]+YY[index][ii]) for ii in range(len(list(steps2)+list(steps3)))]
    #	YY_mean = [(YY_sum[ii]/mm) for ii in range(len(list(steps2)+list(steps3)))]
    #	plot_update(FIELDS,OUT,'Current [Amp]',FIELDS,YY_mean,'Current [Amp]')
    with open(m_Path + "\\" + root_fileName + "_MEAN.txt", "w") as outFile:
        for index, my_field in enumerate(list(steps2) + list(steps3)):
            outFile.writelines(
                str(my_field) + " " + str(YY_mean[index]) + "\n")
        del my_field
    print "SEQUENCE FINISHED ! CHECK YOUR FILES!!!!!!!!!"
コード例 #51
0
    def click_canvas(self, evt):
        ''' Gestionnaire d'evenement click sur la video
			Si mode enregistrement,
				- enregistre la position du point
				- trace un point
			Si mode mesure,
				-
				-
		'''
        # MODE CAPTURE
        if self.app.capture != None and self.app.videos[
                self.app.capture] == self and self.video:
            #Ajoute les données au tableau
            frame_time = int(round(self.get_relative_time()))
            self.app.datas.add(frame_time, [0, 0] * self.datas_pos +
                               self.get_coordonnes(evt))
            #Ajoute une marques
            self.marques[frame_time] = Marque(self, evt.x, evt.y)
            self.last_capture = (evt.x, evt.y)
            # Avance d'un frame (dans le fps de la video maitre)
            if self.datas_pos != 0:  # Si pas video maitre : on avance jusque la frame précédente correspondant au temps de la video 0
                self.video.goto_time(self.app.videos[0].get_relative_time() +
                                     self.offset +
                                     (self.video.get_time(self.start_frame)
                                      if self.start_frame else 0) -
                                     1000.0 / self.video.get_virtual_fps())
            self.update_video()
            #rend active la PiVideo suivante qui a une video ouverte
            self.app.capture += 1
            self.app.capture %= len(self.app.videos)
            while not self.app.videos[self.app.capture].video:
                self.app.capture += 1
                self.app.capture %= len(self.app.videos)
            self.canvas.config(cursor="")
            self.app.videos[self.app.capture].move_mouse_at_last_capture()
        # MODE MESURE
        if self.app.mode == 'mesure':
            if not self.line_mesure:
                #1er point de la mesure
                self.line_mesure = self.canvas.create_line(evt.x,
                                                           evt.y,
                                                           evt.x + 1,
                                                           evt.y + 1,
                                                           arrow='both')
                self.canvas.bind('<Motion>', self.on_motion_mesure)
                #TODO : faire bind sur echap pour annuler le mode
            else:
                #2nd point de la mesure
                [x0, y0, x1, y1] = self.canvas.coords(self.line_mesure)
                distance_px = ((x0 - x1)**2 + (y0 - y1)**2)**0.5
                distance_mm = tkSimpleDialog.askfloat(
                    "Convertir des pixels en mm",
                    "La distance mesurée est de %d pixels.\n Quelle est la distance réelle en mm?"
                    % distance_px,
                    minvalue=0)
                if distance_mm:
                    self.set_ratio_px_mm(distance_mm / distance_px)
                self.app.stop_mode()
        #MODE SELECTION CENTRE COORDONNES POLAIRE
        if self.app.mode == 'centre' and self.coordonnes.get(
        ) == Pivideo.types_coordonnes[1]:
            self.centre = (evt.x, evt.y)
            self.draw_coordonnes()
            self.app.datas.change_datas(self.datas_pos,
                                        callback=self.to_polar,
                                        col_names=self.get_col_names())
            self.app.stop_mode()
            self.canvas.config(cursor="")
コード例 #52
0
ファイル: iztc_dem.py プロジェクト: inkenbrandt/Earth_Tides
        if not BatchMode:
            tkMessageBox.showerror("Data File Error",
                                   "Error processing data file %s!" % raw_file)
        sys.exit()
    write("--> Processed gravity data file '%s' with %d stations\n" %
          (raw_file, len(data)))

    options["raw_file"] = raw_file

    # get maximum distance
    if BatchMode:
        maxDist = options["max_dist"]
    else:
        title = "Maximum Distance for Correction"
        msg = "Maximum distance for corrections, in km"
        maxDist = tkSimpleDialog.askfloat(title, msg, parent=root)

    if not maxDist:
        write("!!! must have a maximum distance > 0!\n")
        if not BatchMode:
            tkMessageBox.showerror("Max Distance too small",
                                   "Must have a maximum distance >0 km!")
        sys.exit(1)

    options["max_dist"] = maxDist

    # get DEM file - FloatDEM-compatible format
    if BatchMode:
        dem_file = options["dem_file"]
    else:
        dem_file = tkFileDialog.askopenfilename(parent=root,
コード例 #53
0
ファイル: VasoTracker.py プロジェクト: kaelome/VasoTracker
 def get_scale(self):
     scale = tkSimpleDialog.askfloat("Input", "How many um per pixel?")
     if scale is None:
         scale = 1
     return(scale)
コード例 #54
0
ファイル: 4.py プロジェクト: israelcode/CG
    # for Python2
    import Tkinter as tk
    import tkSimpleDialog as tksd
except:
    # for Python3
    import tkinter as tk
    import tkinter.simpledialog as tksd

#2-2-0
global q
global w
global e

root = tk.Tk()
q = tksd.askfloat("Parametr 2 (Float)",
                  "Введите параметр освещения(x):",
                  parent=root,
                  minvalue=0)
w = tksd.askfloat("Parametr 2 (Float)",
                  "Введите параметр освещения(y):",
                  parent=root,
                  minvalue=0)
e = tksd.askfloat("Parametr 2 (Float)",
                  "Введите параметр освещения(z):",
                  parent=root,
                  minvalue=0)

#Параметры освещения и отражающие свойства материала задаются пользователем в диалоговом режиме.
#print('Введите параметры освещение(x,y,z)')
#a=float(input())
#b=float(input())
#c=float(input())
コード例 #55
0
ファイル: GUIOutput.py プロジェクト: ZeroDesigner/pyRosetta
 def set_temperature(self):
     self.kT = tkSimpleDialog.askfloat(title="kT",
                                       prompt="Set Temperature",
                                       initialvalue=self.kT)
コード例 #56
0
def callback():
    askfloat('Entry', 'Input field')
コード例 #57
0
def ask_float(prompt, default=None, min=0.0,max=100.0, title=''):
    """ Get input from the user, validated to be an float (decimal number). default refers to the value which is initially in the field. By default, from 0.0 to 100.0; change this by setting max and min. Returns None on cancel."""
    if default:
        return tkSimpleDialog.askfloat(title, prompt, minvalue=min, maxvalue=max, initialvalue=default)
    else:
        return tkSimpleDialog.askfloat(title, prompt, minvalue=min, maxvalue=max)
コード例 #58
0
from tkFileDialog   import askopenfilename
from tkColorChooser import askcolor
from tkMessageBox   import askquestion, showerror
from tkSimpleDialog import askfloat
dialogs = { 
	'Open': askopenfilename,
	'Color': askcolor,
	'Query': lambda: askquestion('Uwaga', 'Potwierdzasz?'),
	'Error': lambda: showerror('Blad!', 'Paskudztwo!'),
	'Input': lambda: askfloat('Podaj', 'Podaj ile zarabiasz:)')
}

from Tkinter import *

class Dialogi(Frame):
	def __init__(self, parent=None):
		Frame.__init__(self, parent)
		self.pack()
		Label(self, text='Dialogi').pack()
		for (klucz, wartosc) in dialogs.items():
			wrap = (lambda klucz=klucz: self.drukuj(klucz))
			Button(self, text=klucz, command=wrap).pack(side=TOP,
				fill=BOTH)
	def drukuj(self, klucz):
		value = dialogs[klucz]()
		print klucz, 'zwraca =>' , value, 'typu =>', type(value)

if __name__ == '__main__': Dialogi().mainloop()
コード例 #59
0
 def askValue(text='', initialvalue=0.0):
     return tkSimpleDialog.askfloat(text,
                                    'Value:',
                                    initialvalue=initialvalue)
コード例 #60
0
ファイル: dialog_table.py プロジェクト: theo-l/material_app
# encoding: utf-8

import tkinter as tk
from tkFileDialog import askopenfilename
from tkColorChooser import askcolor
from tkMessageBox import askquestion, showerror, askokcancel
from tkSimpleDialog import askfloat

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


class Quitter(tk.Frame):

    def __init__(self, parent=None):
        tk.Frame.__init__(self, parent)
        self.pack()
        widget = tk.Button(self, text="Quit", command=self.quit)
        widget.pack(side=tk.LEFT, expand=tk.YES, fill=tk.BOTH)

    def quit(self):
        ans = askokcancel("Verify Exit", "Really Quit?")
        if ans:
            tk.Frame.quit(self)