Пример #1
0
def ask_integer(prompt, default=None, min=0,max=100, title=''):
	""" Get input from the user, validated to be an integer. default refers to the value which is initially in the field. By default, from 0 to 100; change this by setting max and min. Returns None on cancel."""
	import tkSimpleDialog
	if default:
		return tkSimpleDialog.askinteger(title, prompt, minvalue=min, maxvalue=max, initialvalue=default)
	else:
		return tkSimpleDialog.askinteger(title, prompt, minvalue=min, maxvalue=max)
Пример #2
0
    def resize_image(self):
        #File choosing dialog
        self.filename = tkFileDialog.askopenfilename(
            title="Select Image",
            filetypes=(("jpeg files", "*jpg"), ("all files", "*.*")))
        self.image = Image.open(self.filename)  #Opens image

        self.width_value = tkSimpleDialog.askinteger("Resize Width",
                                                     "New Width Value",
                                                     minvalue=16,
                                                     maxvalue=1280)

        self.height_value = tkSimpleDialog.askinteger("Resize Width",
                                                      "New Height Value",
                                                      minvalue=16,
                                                      maxvalue=1280)

        #Change filename to SaveAs instead of Open
        '''
        self.filename = tkFileDialog.asksaveasfilename(title="Save as",
                                                       filetypes=(("jpeg files", "*.jpg"),
                                                                  ("all files", "*.*")))
        '''
        #Resize
        self.new_image = self.image.resize(
            (self.width_value, self.height_value))
        self.new_image.save(self.filename)

        tkMessageBox.showinfo("Saved",
                              "Image saved")  #User feedback for saving
Пример #3
0
def main():
    root = Tk()

    info_dict = {}
    nr_fluors = tkSimpleDialog.askinteger(
        "Number",
        "Input the number of used FPs per control: ")  # fill with message
    nr_channels = tkSimpleDialog.askinteger(
        "Number",
        "Input the number of used channels per control: ")  # fill with message

    i = 0
    if nr_channels > 1:
        while i < nr_channels:
            channels_list.append(
                tkSimpleDialog.askstring(
                    "String", "Input the name of channel %s: " %
                    (i + 1)))  # fill with message
            i += 1
    else:
        channels_list.append(
            tkSimpleDialog.askstring(
                "String",
                "Input the name of the channel: "))  # fill with message

    while nr_fluors > 0:
        info_dict = combine_channels(info_dict)
        nr_fluors -= 1

    info_dict = calcu_ratio(info_dict)
    info_dict = make_avg(info_dict)
    ratio_matrix = make_matrix(info_dict)
    unmix_matrix_here = inv_matrix(ratio_matrix)
    save_unmix_matrix(unmix_matrix_here)
Пример #4
0
    def makerockingcurve(self):
        if self.startx==None:
            pass
        print(self.startx*self.zoom,self.endx*self.zoom)
        print(self.starty*self.zoom,self.endy*self.zoom)
        xl=int(min(self.startx,self.endx)) ; xh = int(max(self.startx,self.endx))
        yl=int(min(self.starty,self.endy)) ; yh = int(max(self.starty,self.endy))
        print("[",xl,":",xh,",",yl,":",yh,"]",self.data.shape)
        if xl!=xh and yl!=yh :
            print("ROI = ",xl,xh,yl,yh)
            stem = simpledialog.askstring("Filename stem?","Filename stem?",initialvalue=self.datafile[:-8])
            first = simpledialog.askinteger("First File to treat","First file to treat")
            last = simpledialog.askinteger("Last File to treat", "Last file to treat")
            extn=".edf"
            s='files %s%04d%s to %s%04d%s\nArea of interest %d %d %d %d'%(stem,first,extn,stem,last,extn,xl,xh,yl,yh)
            print("Making rocking curve for:",s)

            d = dialog.Dialog(None, {'title': 'Make a rocking curve',
                      'text':  "Sorry - this is not working yet!!!" ,
                      'bitmap': dialog.DIALOG_ICON,
                      'default': 0,
                      'strings': ('Do it now please!',
                                  """That's not what I meant!""")})
            return
            print(d.num)
            if d.num==0:
                import rocker
                line=rocker.rock(stem,first,last,extn,xl,xh,yl,yh)
                import twodplotml
                twodplotml.twodplot(parent=Toplevel(),data=line)
                print(line)
            else:
                print("What a waste of time that was!")
def nouveau(): 

    global zd_f,chemin,limage,sauv,n

    if tkMessageBox.askokcancel("Fichier","Nouveau projet ?"):

        fermer()

        zd_h=tkSimpleDialog.askinteger("Nouveau projet", "Largeur ?") 

        zd_l=tkSimpleDialog.askinteger("Nouveau projet", "Longueur ?") 

        zd_f=TK.Canvas(fen,height=abs(zd_h),width=abs(zd_l),bg="white",bd=0, highlightthickness=0)

        limage=[]

        for i in range(abs(zd_h)):

            limage.append([])

        for k in limage:    

            for j in range(abs(zd_l)):

                k.append(255)

        sauv=[]

        sauv.append(limage)

        chemin="initiale.gif" #désactiver pour test image

        actu()
Пример #6
0
def save_image(root):
    frame = cv2.imread('face_buff.jpg')
    name = tkSimpleDialog.askstring("String", "Who is this guy?")
    if name :
        dir_path = 'database/'+name

        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
            ispatient = tkSimpleDialog.askinteger("Interger","Is this guy a patient? input 0 or 1")
            ischild = tkSimpleDialog.askinteger("Interger","Is this guy a child? input 0 or 1")
            add_this_guy(name,ispatient,ischild)
            print 'batabase for %s created'%name

        path, dirs, files = os.walk(dir_path).next()
        num_of_image_exits = len(files)
        print '%i images for %s'%(num_of_image_exits+1,name)
        for i in range(num_of_image_exits+1):
            if '%s_%i.jpg'%(name,i) in files:
                continue
            else:
                cv2.imwrite('%s/%s_%i.jpg'%(dir_path,name,i), frame)
                break
        try:
            os.remove('temp.jpg')
        except:
            pass
    raspi_icon()
Пример #7
0
def survey():
    tkMessageBox.showinfo(title="SURVEY", message="Please rate each of the following statements on a scale from 1 to 7, with 1 being absolutely not, and 7 being absolutely yes.\n [1|2|3|4|5|6|7]")

    one = tkSimpleDialog.askinteger(title="enjoyment", prompt="I enjoyed playing Tetris.")


    two = tkSimpleDialog.askinteger(title="time", prompt="Time seemed to stand still or stop.")


    three = tkSimpleDialog.askinteger(title="tired", prompt="I couldn't tell if I was getting tired.")

    four = tkSimpleDialog.askinteger(title="drive", prompt="I felt like I couldn't stop playing.")


    five = tkSimpleDialog.askinteger(title="stress", prompt="I got wound up.")

    six = tkSimpleDialog.askinteger(title="auto", prompt="Playing seemed automatic.")

    seven = tkSimpleDialog.askinteger(title="thought", prompt="I played without thinking how to play.")

    eight = tkSimpleDialog.askinteger(title="calm", prompt="Playing made me feel calm.")



    nine = tkSimpleDialog.askinteger(title="time", prompt="I lost track of time.")

    ten = tkSimpleDialog.askinteger(title="involvement", prompt="I really got into the game.")

    return([one, two, three, four, five, six, seven, eight, nine, ten])
Пример #8
0
 def store_subjects(self):
     #Making Dict2 for Storing Subjects of the class
     self.stream = tkSimpleDialog.askstring(
         self.ct_name + "\'s Profile~",
         "Enter the stream of the class you teach - \n(Eg: Science, Medical Science, Humanities, Commerce,etc..)"
     )
     self.no_subs = tkSimpleDialog.askinteger(
         self.ct_name + "\'s Profile~",
         "Enter number of subjects in the stream - ")
     pop = tkMessageBox.showinfo(
         "NOTICE!",
         "Now values will be inputed in python instead of GUI Boxes for convienence!"
     )
     self.subs = []
     self.dsubs = {}
     self.dsubs_roll = []
     self.u = ['st', 'nd', 'rd']
     self.a = 'th'
     self.c = len(self.u)
     print "\t", "----------------------------------------------------------------"
     print "\n", "\t", "KINDLY ENTER THE SUBJECTS IN THE %s STREAM - " % self.stream.upper(
     )
     time.sleep(1)
     for i in range(self.no_subs):  #ENTERING SUBJECTS
         if self.c < self.no_subs:
             self.u += [
                 self.a,
             ]
             self.c += 1
         self.subjects = raw_input("Kindly enter name of %s%s subject - " %
                                   (str((i + 1)), self.u[i]))
         self.subs += [
             self.subjects,
         ]
         self.dsubs[i + 1] = self.subs[i]
         self.dsubs_roll += [
             str(i + 1),
         ]
         self.dsubs_roll.sort()
     self.subject = list()
     self.subject += self.subs
     self.m_subs = []
     sp = " "
     self.maxi = tkSimpleDialog.askinteger(
         self.ct_name + "\'s Profile~",
         "Enter MAXIMUM marks attainable on the test - ")
     self.outf = []
     raw = []
     for i in range(
             self.no_subs):  #CREATING MAIN LIST FOR SUBJECTS AND OUT OF
         self.outf += [
             str(self.maxi),
         ]
         while len(self.subs[i]) != 15:
             self.subs[i] += sp
         self.m_subs += [
             self.subs[i],
         ]
     self.marks_entry()
Пример #9
0
	def addView(self):
		newCamNum = tkSimpleDialog.askinteger("New camera", "New camera number:", initialvalue = 1001)
		newCamPreset = tkSimpleDialog.askinteger("New camera", "New preset number:", initialvalue = 1)
		if newCamNum == None or newCamPreset == None:
			return
		self.fov.append(fieldOfView([self.canvas.canvasx(0)+100,+self.canvas.canvasy(0)+100]))
		self.fov[-1].cam_num = newCamNum
		self.fov[-1].preset = newCamPreset
		self.selectView(len(self.fov)-1)
def couleur():

    global coul

    coul=tkSimpleDialog.askinteger("Niveau de gris 0 à 255", "Valeur couleur:")

    while coul<0 or coul>255:    

        coul=tkSimpleDialog.askinteger("Erreur valeur couleur", "entre 0 et 255:")

    coulap()
Пример #11
0
 def changeDimension(self):
     global dimensionX
     dimensionX = tkSimpleDialog.askinteger("Change Dimension!",
                                            "Enter x value:")
     global dimensionY
     dimensionY = tkSimpleDialog.askinteger("Change Dimension!",
                                            "Enter y value:")
     self.result += '\n'
     self.result += "Changed Dimension to " + str(dimensionX) + "x" + str(
         dimensionY)
     self.loadText()
Пример #12
0
def getBlocks():
	"""
    GUI to ask for block settings
    :return: Nothing
	"""
	def addBlock():
		global BlockTimes
		global BlockDoW
		BlockTimes = []
		BlockDoW = []
		for x in range(0,BlockCount):
			BlockTimes.append(Times[x].get())
			BlockDoW.append(DayStructure[x].get())

		slave2.destroy()
		getSubjects()

	"""End Sub"""

	global BlockCount
	global LunchBlock
	global BlockDoW
	Times = []
	DayStructure = []
	BlockCount = tkSimpleDialog.askinteger("bCount", "How Many Blocks in a day?", initialvalue=BlockCount)
	LunchBlock = tkSimpleDialog.askinteger("lunch", "Which block is lunch?", initialvalue=LunchBlock)
	while LunchBlock > BlockCount-1:
		showinfo("Error", "Lunch must be Less than Blocks in a day - 1")
		LunchBlock = tkSimpleDialog.askinteger("lunch", "Which block is lunch?")

	#Pad BlockTimes / BlockDoW for prepop if less than block cound
	while len(BlockTimes) < BlockCount:
		BlockTimes.append("")
		BlockDoW.append("")

	#Get block Times, slave2 = new window
	slave2 = Tk()
	for x in range(0,BlockCount):
		Label(slave2,text="Block " + str(x+1) +" Time: ").grid(row=x, column=0)
		prepop = Entry(slave2)
		prepop.insert(0, BlockTimes[x])
		Times.append(prepop)
		Times[x].grid(row=x, column=1)


		Label(slave2,text="Structure (Separate with /):").grid(row=x, column=2)
		prepop = Entry(slave2)
		prepop.insert(0, BlockDoW[x])
		DayStructure.append(prepop)
		DayStructure[x].grid(row=x, column=3)

	sub = Button(slave2, text="Submit", command=addBlock)
	sub.grid(row=BlockCount+1, column=1)
def ask_integer(prompt, default=None, min=0, max=100, title=''):
    """ Get input from the user, validated to be an integer. default refers to the value which is initially in the field. By default, from 0 to 100; change this by setting max and min. Returns None on cancel."""
    if default:
        return tkSimpleDialog.askinteger(title,
                                         prompt,
                                         minvalue=min,
                                         maxvalue=max,
                                         initialvalue=default)
    else:
        return tkSimpleDialog.askinteger(title,
                                         prompt,
                                         minvalue=min,
                                         maxvalue=max)
Пример #14
0
 def obtener_entero(self, mensaje, titulo="", intervalo=[]):
     """
     Pide al usuario que ingrese un numero entero, mostrando el mensaje pasado por parametro. Si se recibe un 
     intervalo, el numero debe pertenecer al mismo.
     :param mensaje: Mensaje a mostrar en la ventana al pedir el numero.
     :param titulo: Titulo de la ventana.
     :param intervalo: Lista de dos numeros, de la forma [min, max]. Si se recibe, el numero que se pida debe ser 
                       mayor o igual a min y menor o igual a max. Se seguira pidiendo al usuario que ingrese un 
                       numero hasta que se cumplan las condiciones.
     :return: Numero entero ingresado por el usuario.
     """
     if not intervalo:
         return tkSimpleDialog.askinteger(titulo, mensaje, parent=self.tk_window)
     return tkSimpleDialog.askinteger(titulo, mensaje, parent=self.tk_window, minvalue=intervalo[0],
                                      maxvalue=intervalo[1])
Пример #15
0
 def PrintLabel(self):
     lps = self._CreateLojeProductGenerator()
     barcode = tkSimpleDialog.askinteger(self.MSG_TITLE, self.MSG_TYPE_BARCODE, parent=self)
     if not (lps and barcode): return
     ident = tkSimpleDialog.askstring(self.MSG_TITLE, self.MSG_IDENT_CODE, parent=self)
     if not ident: return
     count = tkSimpleDialog.askinteger(
         self.MSG_TITLE, self.MSG_LABEL_COUNT, initialvalue=1, parent=self
         )
     if not count: return
     try:
         sheet = lps.GenerateLojeProductSheet([ident] * count, barcode)
     except ProductCodeError, exc:
         tkMessageBox.showerror(self.MSG_TITLE, exc)
         return
Пример #16
0
def setCustomSize():
    global customsizes
    #r = tkinter.simpledialog.askinteger("Custom size", "Enter amount of rows")
    #c = tkinter.simpledialog.askinteger("Custom size", "Enter amount of columns")
    #m = tkinter.simpledialog.askinteger("Custom size", "Enter amount of mines")
    r = tkSimpleDialog.askinteger("Custom size", "Enter amount of rows")
    c = tkSimpleDialog.askinteger("Custom size", "Enter amount of columns")
    m = tkSimpleDialog.askinteger("Custom size", "Enter amount of mines")
    while m > r*c:
        #m = tkinter.simpledialog.askinteger("Custom size", "Maximum mines for this dimension is: " + str(r*c) + "\nEnter amount of mines")
        m = tkSimpleDialog.askinteger("Custom size", "Maximum mines for this dimension is: " + str(r*c) + "\nEnter amount of mines")
    customsizes.insert(0, (r,c,m))
    customsizes = customsizes[0:5]
    setSize(r,c,m)
    createMenu()
Пример #17
0
    def open_new (self):
        n_col = tkSimpleDialog.askinteger ("N_Colors", "Enter the number "\
                                           "of colors in new lookup table.",
                                           initialvalue=16, 
                                           minvalue=0,
                                           maxvalue=LUT_EDITOR_MAX_COLORS,
                                           parent=self.root)
        if n_col is None:
            return None

        cur_col = ((0,0,255), '#0000fe')
        ans = tkMessageBox.askyesno ("Choose color?", 
                                     "Choose individual colors? "\
                                     "Answer no to choose one color only.")
        if ans == 1:        
            for i in range (0, n_col):
                col = tkColorChooser.askcolor (title="Color number %d"%(i),
                                               initialcolor=cur_col[1])
                if col[1] is not None:
                    self.lut.append (tk_2_lut_color (col[0]))
                    cur_col = col
                else:
                    self.lut.append (tk_2_lut_color (cur_col[0]))
        else:
            col = tkColorChooser.askcolor (title="Choose default color", 
                                           initialcolor=cur_col[1])
            if col[1] is None:
                col = cur_col
            for i in range (0, n_col):
                self.lut.append (tk_2_lut_color (col[0]))
            
        self.lut_changed = 1
        self.initialize ()
Пример #18
0
 def checkIn(self):
     tkMessageBox.showwarning(title="SESSION ENDED",
                              message ="Score: %7d\tLevel: %d\n Ready to move on?" % ( self.score, self.level), parent=self.parent)
     self.enjoyNoSpeed = tkSimpleDialog.askinteger(title='Question', prompt="On a scale from 1 to 7 with 1 being not enjoyable at all, and 7 being as enjoyable as possible, how fun was this?")
     survey_ans = survey.survey.survey()
     self.writeData(BOOK, SHEET,SHEETNAME, SESSION)
     excel_data.survey_ans.write_survey_ans(BOOK, SHEET, SHEETNAME, survey_ans, SESSION)
Пример #19
0
def pricevar(variclass):
    '''行情var'''
    sdate = tkSimpleDialog.askstring(u'华泰期货',
                                     u'历史数据从哪天开始?',
                                     initialvalue='2015-09-01')
    delta = tkSimpleDialog.askinteger(u'华泰期货', u'连续几天行情?', initialvalue=6)
    #variclass=data['variclass']
    data2, allpch, adt = stress.getfu(sdate, delta, variclass)
    td = {}
    r = [0.9, 0.95, 0.99]
    colname = [u'涨90%', u'涨95%', u'涨99%', u'跌90%', u'跌95%', u'跌99%']
    for i in range(len(colname)):
        colname[i] = str(delta) + u'天连续行情' + colname[i]
    colname = [u'品种'] + colname
    for x in variclass:
        td[x] = []
        ylist = []
        for y in allpch:
            ylist.append(y[x])
        templist = copy.copy(ylist)
        ylist.sort(reverse=False)  #从小到大
        for y in r:
            k = int(math.ceil(y * len(ylist)))
            v = round(ylist[k], 4)
            td[x].append(v)
        ylist.sort(reverse=True)  #从大到小
        for y in r:
            k = int(math.ceil(y * len(ylist)))
            v = round(ylist[k], 4)
            td[x].append(v)
    return td, colname
def change_total():
    global stats,attributes,app
    new_total=tkSimpleDialog.askinteger("Change Total","Enter a new total:")
    if new_total==None: return False
    if new_total<0: new_total=0
    stats=statdist.StatDist(attributes,new_total)
    app.update_values()
Пример #21
0
    def get_top_scoring_by_number(self,
                                  top_number=False,
                                  ask_copy_results=True):
        """
        Gets top scoring poses - Sets self.top_scoring_by_number_map.  Runs copy_results
        """
        if not self.score_pairs:
            print "Please load scores."
            return
        if not top_number:
            top_number = tkSimpleDialog.askinteger(
                title="Cutoff",
                prompt="Please enter how many top scoring poses you would like",
                initialvalue=10)
            if not top_number: return

        print repr(top_number)
        for i in range(0, top_number):
            score = self.score_pairs[i][0]
            fullpath = self.score_pairs[i][1]
            print "%.2f" % score + " " + fullpath
            self.top_scoring_by_number_map[fullpath] = score

        if ask_copy_results:
            self.copy_results(self.top_scoring_by_number_map,
                              "TOP_" + str(top_number))
        else:
            return self.top_scoring_by_number_map
Пример #22
0
    def process_files(self):
        if self.inputname.get() != "" and self.list.get() != "":
            self.rank = self.list.get()
            self.status = True

            if self.rank == "Admin":
                passadmin = simpledialog.askinteger("Key", "Key Admin")
                if passadmin is not None:
                    if passadmin == 810198:
                        self.name = self.inputname.get()
                        self.image_path = "./database/admin/"
                    else:
                        messagebox.showerror("Error", "Key fails")
            else:
                self.name = self.inputname.get()
                self.image_path = "./database/users/" + self.name + "/"
                try:
                    os.makedirs(self.image_path)
                    self.ids = format(len(self.listuser) + 2)
                    print(self.ids)
                except:
                    messagebox.showinfo("Notice - Author : ThanhQuangLong",
                                        "Your name already exists ")
            self.cmd = "python3 client.py " + "register " + self.name + " " + self.image_path + " " + self.rank + " " + self.ids
            ### Start Detect#####################################################
            os.system(self.cmd)
        else:
            messagebox.showinfo("Notice - Author : ThanhQuangLong",
                                "Pls input your username or select your rank")
            self.loading.pack(side=LEFT, padx=5, pady=50)
Пример #23
0
 def History(self):
     length = tkSimpleDialog.askinteger("Tracking History",
                                        "Please input the history length",
                                        parent=self.root,
                                        minvalue=0,
                                        initialvalue=5)
     self.Hlength = length
Пример #24
0
    def input(self):
        value = None
        edited = False
        print "getting input!!"
        """
        self.text.config(state="normal")
        self.text.insert(END, ">>> ")
        start = self.text.index("current")
        def back(self, event=None):
            current = self.text.index("current")
            ln, col = current.split(".")
            col_s = start.split(".")[1]
            if int(col) < int(col_s):
                self.text.delete(current, END)

        def validate(self, event=None):
            current = self.text.index("current")
            value = self.text.get(start, current)
            edited = True
            self.text.insert(END, "\n")
            return value
        self.bind("<BackSpace>", back)
        self.text.config(state="disable")
        self.text.bin("<Return>", validate)
        return value
        """
        res = simpledialog.askinteger("Input", "Enter an integer!")
        #dia = simpledialog.SimpleDialog(self, "input a value", title="yes")
        return res
Пример #25
0
 def changeMotorID(self):
     oldid = self.getSelectedMotor()
     if oldid < 0:
         tkMessageBox.showerror("Selection Error",
                                "Please select a motor first")
     else:
         newid = tkSimpleDialog.askinteger(
             "Change ID", "Please provide new ID for motor %d" % oldid)
         if newid == None:
             return
         if oldid == newid:
             return
         if newid < 1 or newid > Dxl.BROADCAST:
             tkMessageBox.showerror(
                 "Range Error",
                 "ID should be between 1 and %d" % (Dxl.BROADCAST - 1))
         else:
             do = True
             if newid in self.chain.motors.keys():
                 answer = tkMessageBox.askyesno(
                     "ID Conflict",
                     "Warning: the motor ID %d is already attributed on your chain, are you sure you want to proceed?"
                     % (newid))
                 if not answer:
                     do = False
             if do:
                 self.chain.set_reg(oldid, "id", newid)
                 self.connect()
Пример #26
0
 def _AskInitialBarcode(self, lpg):
     initial_barcode = tkSimpleDialog.askinteger(
         self.MSG_TITLE, 
         self.MSG_TYPE_BARCODE + "Inicial", 
         initialvalue=lpg.AcquireInitialBarcode(),
         parent=self)
     return initial_barcode
Пример #27
0
def addText():
    global check_to_replace
    #name of button
    button_text = tkSimpleDialog.askstring("Input Text", "Enter Text")
    print button_text
    victim = findObject()

    #size of text    delete(victim)

    text_size = tkSimpleDialog.askinteger("Input Text", "Size of text")
    text_family = tkSimpleDialog.askstring("Input Text", "font family")
    text_color = tkSimpleDialog.askstring("Input Text", "Text color")
    #  text_family = tkSimpleDialog.Radiobutton.
    # print var
    search_text1 = "font-size:;"
    rep_text1 = "\t\t\tfont-size: " + str(text_size) + "px;\n"

    search_text2 = "font-family:;"
    rep_text2 = "\t\t\tfont-family: " + text_family + ";\n"

    search_text3 = "color:;"
    rep_text3 = "\t\t\tcolor: " + text_color + ";\n"
    w.create_text((shapeObjArr[victim][0] + shapeObjArr[victim][2]) / 2,
                  shapeObjArr[victim][1] + 10,
                  fill=text_color,
                  text=button_text)
    alterCSSFile(victim, search_text1, rep_text1, check_to_replace)
    alterCSSFile(victim, search_text2, rep_text2, check_to_replace)
    alterCSSFile(victim, search_text3, rep_text3, check_to_replace)
    #print "%"+check_to_replace
    if (check_to_replace == "anchor"):
        replace_text(victim, "<!--anchor text-->", button_text)
    elif (check_to_replace == "paragraph"):
        replace_text(victim, "<!--paragraph text-->", button_text)
Пример #28
0
 def set_top_n_combined(self):
     top = tkSimpleDialog.askinteger(
         title="Top N Combined",
         prompt="Number of top scoring Combined",
         initialvalue=self.compare_designs.top_n_combined.get())
     if not top: return
     self.compare_designs.top_n_combined.set(top)
def display_4():
    # Ask Integer Window (Title, Prompt)
    # Returned value is an int
    ans = askinteger('Enter Integer', 'Please enter an integer')
    # If the user clicks cancel, None is returned
    if ans is not None:
        print(ans)
Пример #30
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")
Пример #31
0
 def _AskInitialBarcode(self, lpg):
     initial_barcode = tkSimpleDialog.askinteger(
         self.MSG_TITLE,
         self.MSG_TYPE_BARCODE + "Inicial",
         initialvalue=lpg.AcquireInitialBarcode(),
         parent=self)
     return initial_barcode
Пример #32
0
 def set_max_clustal_procs(self):
     max = tkSimpleDialog.askinteger(
         title="Max P",
         prompt="Max NP.  Clustal by default uses all.",
         initialvalue=self.main_gui.clustal_procs.get())
     if not max: return
     self.main_gui.clustal_procs.set(max)
Пример #33
0
    def run_program(self, controller):
        number = msg.askinteger("Derived Number", "Enter Derived Number")
        title = tk.Label(self, text="Derived Key", font=font_title)
        title.grid(row=0, column=0)

        nkey = tk.Label(self, text=number)
        nkey.grid(row=1, column=0)

        wallet = HD_Wallet_Details.HD_wallet_details(key1)
        (key, chain, depth, fingerprint, Child_number,
         Private) = wallet.CKDpriv(number)
        derived = HD_Wallet_Details.HD_wallet_details(
            HD_Wallet_Details.serialize_Wallet(key, chain, depth, fingerprint,
                                               Child_number, Private))

        string = derived.dump_string()

        info1 = tk.Text(self, width=165, height=15)
        info1.insert(tk.INSERT, string)
        info1.config(state=tk.DISABLED)
        info1.grid(row=2, column=0)

        button1 = ttk.Button(self,
                             text='Return Home',
                             command=lambda: controller.show_frame(Master_key))
        button1.grid(row=3, sticky='e', padx=450)

        button2 = ttk.Button(
            self,
            text='Address Details',
            command=lambda: run_address_details(controller, derived))
        button2.grid(row=3, sticky='w', padx=450)
Пример #34
0
def ask_for_value(app, caller):
    """Show an input windows asking for a value
    uses tkSimpleDialog
    """
    title_d = _("Enter A Value")
    switch = {
        "S1": ("Step1", "step", 0.001, 100.0),
        "S2": ("Step2", "step", 0.001, 100.0),
        "S3": ("Step3", "step", 0.001, 100.0),
        "ZS1": ("Z Step1", "step", 0.001, 25.0),
        "ZS2": ("Z Step2", "step", 0.001, 25.0),
        "ZS3": ("Z Step3", "step", 0.001, 25.0),
        "ZS4": ("Z Step4", "step", 0.001, 25.0),
        "ZS4": ("Z Step4", "step", 0.001, 25.0),
        "TD": (_("Enter Target Depth :"), "depth", -35.0, 0.0),
        "MN": (_("Enter Memory Number :"), "mem_num", 2, OCV.WK_mem_num),
        "ME": (_("Enter Memory {0} Description :"), "mem_desc", 0, 0),
        }

    choiche = switch.get(
        caller, (_("Enter a float Value :"), "gen_float", 0.001, 100.0))

    if choiche[1] in ("step", "depth", "gen_float"):
        if choiche[1] == "step":
            title_c = _("Enter Value for {0} :").format(choiche[0])
        else:
            title_c = choiche[0]

        prompt = "{0}\n (min: {1:.04f} max: {2:.04f})".format(
            title_c,
            choiche[2],
            choiche[3])

        retval = tkSimpleDialog.askfloat(
            title_d, prompt, parent=app,
            minvalue=choiche[2],
            maxvalue=choiche[3])

    elif choiche[1] == "mem_num":
        prompt = "{0}\n (min: {1:d} max: {2:d})".format(
            choiche[0],
            choiche[2],
            choiche[3])

        retval = tkSimpleDialog.askinteger(
            title_d, prompt, parent=app,
            minvalue=choiche[2],
            maxvalue=choiche[3])

    elif choiche[1] == "mem_desc":
        prompt = choiche[0].format(OCV.WK_mem)
        retval = tkSimpleDialog.askstring(title_d, prompt, parent=app)

    else:
        retval = None

    if retval is None:
        return None
    else:
        return retval
def contour():

    global limage

    lbrute=limage

    coupage=tkSimpleDialog.askinteger("Sensibilité: 0 à 255", "Valeur recommandée 3: ")

    lbrute=coup(abs(coupage),limage)

    #mise en place du contour   

    for i in range(1,len(lbrute)-1):

        l=lbrute[i]

        for j in range(1,len(l)-1):

            if (l[j]<>l[j-1] and l[j]<>l[j+1]) or (lbrute[i-1][j]<>lbrute[i][j] and lbrute[i+1][j]<>lbrute[i][j]):

                l[j]=255

            else:

                l[j]=0   

    #print "contour fait"

    limage=lbrute

    sauvauto()

    actu()#permet d'actualiser la zone dessin
Пример #36
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)
Пример #37
0
    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()
Пример #38
0
 def keybdGoToSite(self, event):
     import tkSimpleDialog
     answer = tkSimpleDialog.askinteger('Go to site','Enter site (0 or larger)',minvalue=0)      
     if answer is not None:
         self.site = answer
         self.setTitle()
         self.plotter.repaint()
Пример #39
0
    def __init__(self, env, title = 'Progra IA', cellwidth=50):

        # Initialize window

        super(EnvFrame, self).__init__()
        self.title(title)        
        self.withdraw()
        # Create components
        self.customFont = tkFont.Font(family="Calibri", size=11)
        self.option_add('*Label*font', self.customFont)        
        
        size=tkSimpleDialog.askinteger("Crear Ambiente","Ingrese el tamaño del tablero",parent=self)
        env = VacuumEnvironment(size+2);
        #env = VacuumEnvironment();
        self.update()
        self.deiconify()
        self.configure(background='white')
        self.canvas = EnvCanvas(self, env, cellwidth)
        toolbar = EnvToolbar(self, env, self.canvas)
        for w in [self.canvas, toolbar]:
            w.pack(side="bottom", fill="x", padx="3", pady="3")

        Ventana = self
        Canvas = self.canvas
        self.canvas.pack()
        toolbar.pack()
        tk.mainloop()
def takeInput():
    global Name
    global Id

    faceDetect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    cam = cv2.VideoCapture(0)

    Name = tkSimpleDialog.askstring("Name", "Enter Name: ")
    Id = tkSimpleDialog.askinteger("Age", "Enter Age: ")
    print(Name + " " + str(Id))

    insertOrUpdate(Id, Name)

    sampleNum = 0
    while (True):
        ret, img = cam.read()
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = faceDetect.detectMultiScale(gray, 1.3, 5)
        for (x, y, w, h) in faces:
            sampleNum = sampleNum + 1
            cv2.imwrite(
                "dataSet/User." + str(Id) + "." + str(sampleNum) + ".jpg",
                gray[y:y + h, x:x + h])
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
            cv2.waitKey(100)
        cv2.imshow("Faces", img)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        elif sampleNum > 20:
            break

    cam.release()
    cv2.destroyAllWindows()
Пример #41
0
def getSubjects():
	"""
	GUI to get subject lists
	:return: Nothing
	"""
	def addSubject():
		global Subjects
		Subjects = []
		for x in range(0,SubCount):
			Subjects.append(Subs[x].get())
		slave3.destroy()
		Generate()
	"""End Sub"""

	global SubCount
	global Subjects
	Subs = []

	SubCount = tkSimpleDialog.askinteger("Sub", "How Many Subjects do we Have?", initialvalue= SubCount)

	#pad Subject[] for prepop and adding subjects
	while len(Subjects) < SubCount:
		Subjects.append("")

	slave3 = Tk()
	Label(slave3,text="Subjects:").grid(row=0, column=0)
	for x in range(0,SubCount):
		prepop = Entry(slave3)
		prepop.insert(0, Subjects[x])
		Subs.append(prepop)
		Subs[x].grid(row=x+1, column=0)

	sub = Button(slave3, text="Submit", command=lambda : addSubject())
	sub.grid(row=SubCount+1, column=1)
Пример #42
0
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))
Пример #43
0
def genXML():

    try:
        maxnodes = tkSimpleDialog.askinteger(parent = root, title = 'Number of nodes', prompt = 'Input an integer greater than one')
        if maxnodes < 2: return
        filename = tkFileDialog.asksaveasfilename(parent = root, initialfile = "autogen.xml")
        from random import randint
        closes = 1; nodes = 1
        f = open(filename, 'w')
        last = '<Node Id="NoLabel" HG="%s">\n' % ','.join(['x' for i in range(randint(0,12))])
        f.write(last)
        while nodes < (maxnodes - 1): # closes > sqrt(maxnodes)*0.75
            nl = randint(-5000,5000) if closes > 10 and last[-3] == '/' \
                 else (randint(-2,1) if last[-3] == '"' \
                       else (randint(-2,6) if closes > 1 \
                             else 1))
            if nl <= 0:
                last = '\t' * closes + '<Node Id="NoLabel" HG="%s" />\n' % ','.join(['x' for i in range(randint(0,6))])
                nodes += 1
            elif nl in [1,2,3]:
                last = '\t' * closes + '<Node Id="NoLabel" HG="%s">\n' % ','.join(['x' for i in range(randint(0,6))])
                closes += 1; nodes += 1
            else:
                closes -= 1
                last = '\t' * closes + '</Node>\n'
            f.write(last)
        if last[-3] == '"':
            f.write('\t' * closes + '<Node Id="NoLabel" HG="%s" />\n' % ','.join(['x' for i in range(randint(0,6))]))
        while closes > 0:
            f.write('\t' * (closes-1) + '</Node>\n')
            closes -= 1
        f.close()
    except: sys.stdout.write('\n')
Пример #44
0
	def m_createNewTable(self):
		"""
		Starts a new table.
		"""
		number = askinteger('COLUMNS','Enter number of Columns\nfor data')
		if number == None: return 
		if number < 2 or number > 8: 
			showwarning("Error","Choose at least two but no more than 8 columns")
			return 
		g1 = ['GRAPH_LABELS']
		u1 = ['GRAPH_UNITS']
		for i in range(number):
			g1.append(' NAME%d' % i)
			u1.append(' UNIT%d' % i)
		glbls = "".join(g1)
		gunit = "".join(u1)
		lineNumber = 1
		ilo = pLineObject('TABLE')
		self.satorpvtparms.parseLine(ilo)
		ilo = pLineObject(glbls)
		self.satorpvtparms.parseLine(ilo)
		ilo = pLineObject(gunit)
		self.satorpvtparms.parseLine(ilo)
		ilo = pLineObject('ENDTABLE')
		self.satorpvtparms.parseLine(ilo)
		self.m_resetTable()
Пример #45
0
 def run_graft(self):
     anchor_start = self.pose.pdb_info().pdb2pose(self.scaffold_chain.get(), int(self.scaffold_start.get()))
     anchor_end = self.pose.pdb_info().pdb2pose(self.scaffold_chain.get(), int(self.scaffold_end.get()))
     
     graftmover = graft.AnchoredGraftMover(anchor_start, anchor_end)
     
     insert_start = self.from_pose.pdb_info().pdb2pose(self.insert_chain.get(), int(self.insert_start.get()))
     insert_end = self.from_pose.pdb_info().pdb2pose(self.insert_chain.get(), int(self.insert_end.get()))
     
     if re.search("Double Loop", self.graft_type.get()):
         nter_overhang = tkSimpleDialog.askinteger(title='N-terminal Overhang', prompt='Please enter the number of residues N-terminal from insert_start to use for superposition', initialvalue=3)
         if not nter_overhang:return
         cter_overhang = tkSimpleDialog.askinteger(title='C-terminal Overhang', prompt='Please enter the number of residues C-terminal from insert_end to use for superposition', initialvalue=3)
         insert = graft.return_region(self.from_pose, insert_start-nter_overhang, insert_end+cter_overhang)
         if not cter_overhang:return
         print "Insert with overhang:"
         print insert
         graftmover.set_piece(insert, nter_overhang, cter_overhang)
         graftmover.superimpose_overhangs_heavy(self.pose, False, False)
     else:
         insert = graft.return_region(self.from_pose, insert_start, insert_end)
         print "Insert: "
         print insert
         graftmover.set_piece(insert, 0, 0)
     
     if self.graft_type.get()=="Double Arm":
         graftmover.set_use_single_loop_double_CCD_arms(True)
     elif self.graft_type.get()=="Double Loop Double Arm":
         graftmover.set_use_double_loop_double_CCD_arms(True)
     elif self.graft_type.get()=="Double Loop Quad Arm":
         graftmover.set_use_double_loop_quad_CCD_arms(True)
     else:
         print "Using default graft type"
         
     if self.randomize_first.get():
         graftmover.set_test_control_mode(True)
         
     graftmover.set_cycles(self.cycles.get())
     graftmover.set_scaffold_flexibility(self.scaffold_nter_flex.get(), self.scaffold_cter_flex.get())
     graftmover.set_insert_flexibility(self.insert_nter_flex.get(), self.insert_cter_flex.get())
     
     new_graftmover = GraftMover(graftmover)
     new_graftmover.set_repack_connection(self.repack_connection.get(), self.score_class.score)
     new_graftmover.set_repack_connection_and_insert(self.repack_connection_and_piece.get(), self.score_class.score)
     
     self.run_protocol(new_graftmover)
     self.main.destroy()
Пример #46
0
    def ask_address(self):
        host = askstring('Server', 'Type the server address.', initialvalue='freechess.org')
        if not host: return

        port = askinteger('Port', 'Type the port.', initialvalue=5000)
        if not port: return

        return host, int(port)
Пример #47
0
 def page_prompt(self=None, event=None):
     newpage = tkSimpleDialog.askinteger("Select page", "Enter new page:",
                     initialvalue=(self.current_page + 1),
                     minvalue=1,
                     maxvalue=len(self.book.pages))
     if newpage:
         self.current_page = newpage - 1
         self.draw_page()
Пример #48
0
 def set_clustal_soft_wrap(self):
     wrap = tkSimpleDialog.askinteger(
         title="Wrap",
         prompt="Set Soft Wrap",
         initialvalue=self.compare_designs.clustal_soft_wrap.get())
     if not wrap:
         return
     self.compare_designs.clustal_soft_wrap.set(wrap)
Пример #49
0
 def maxFrameChanged(self):
     number = tkSimpleDialog.askinteger("Edit Motion Correct Properties",
                                        "Last Frame")
     if number >= 0:
         self.maxframe = number
         self.maxframe_label.configure(text="Ending Frame Number: " +
                                       str(self.maxframe))
         self.watcher.setLastFrame(self.maxframe)
Пример #50
0
 def GoToSlice():
     sliceIndex = tkSimpleDialog.askinteger("GoTo Slice", " Index : ")
     if not sliceIndex: return
     smin, smax = Globals.imagePipeline.GetAxisExtent()
     sliceIndex = min(smax, sliceIndex)
     sliceIndex = max(smin, sliceIndex)
     self.SetSlice(sliceIndex)
     self.scaleSlice.set(sliceIndex)
Пример #51
0
	def newGame(self):
		if self.game!=None:
			self.game.deregisterCallBacks()
		lowBlind = askinteger("Table Options", "Small Blind", initialvalue="5")
		if lowBlind==None:
			lowBlind=5
		highBlind = askinteger("Table Options", "Large Blind", initialvalue="10")
		if highBlind==None:
			highBlind=10
		self.game = Holdem(lowBlind,highBlind, debug=True, manual = self.manual)
		print self.game.stage
		self.game.registerCallBack(HoldemGUI.toggleButtons, self)
		self.game.registerCallBack(HoldemGUI.updateAction, self)
		self.cleanUpCards()
		self.displayPocketCards(2)
		self.toggleButtons()
		self.playHand()
Пример #52
0
 def GoToSlice():
     sliceIndex = tkSimpleDialog.askinteger("GoTo Slice"," Index : ")
     if not sliceIndex: return
     smin,smax = Globals.imagePipeline.GetAxisExtent()
     sliceIndex = min(smax, sliceIndex)
     sliceIndex = max(smin, sliceIndex)
     self.SetSlice(sliceIndex)
     self.scaleSlice.set(sliceIndex)
Пример #53
0
def print_top_stems():
	"""Queries user for number and calls get_top_stems."""
	global global_model
	num = tkSimpleDialog.askinteger("Number", "Number of most common stems to print:")
	if num:
		tkMessageBox.showinfo("Summary",\
				"Top " + str(num) + " stems that appeared in the text:\n" + \
				get_top_stems(global_model, num))
Пример #54
0
def rand_board():
    global board
    global step
    global openfile
    density = tkd.askinteger('Density', 'enter a cell density between 0 and 100')
    create_random_board(density)
    step = 1
    openfile = 'empty_board.gol'
    display_board(board)
Пример #55
0
 def goto_line_event(self, event):
     lineno = tkSimpleDialog.askinteger("Goto", "Go to line number:", parent=self)
     if lineno is None:
         return "break"
     if lineno <= 0:
         self.bell()
         return "break"
     self.mark_set("insert", "%d.0" % lineno)
     self.see("insert")
Пример #56
0
   def jump(self,event=None):
      """Present a dialog to the user where they can enter a specific source
         number to jump to."""

      num = askinteger('Jump','Enter source number to jump to',\
         parent=self,minvalue=1,maxvalue=(self.n))
      if num:
        self.scl.set(num)
        self.report()
Пример #57
0
	def clickCallback(self,event):
		print (event.x,event.y)
		depth = tkSimpleDialog.askinteger("Depth", "Please enter the depth.")
		if depth != None:
	         	print depth
			self.canvas.create_rectangle(event.x-1,event.y-1,event.x+1,event.y+1)
			self.currentLst.append(np.array([event.x, event.y, depth]))
			if len(self.currentLst)>1:
				self.canvas.create_line(self.currentLst[-2][0], self.currentLst[-2][1],self.currentLst[-1][0],self.currentLst[-1][1])
Пример #58
0
 def onEditTurn(self, event):
     new_turn = tkSimpleDialog.askinteger(
         "Edit turn", "Enter new turn", parent=self.UI.root, initialvalue=self.turn, minvalue=1, maxvalue=100
     )
     if new_turn is not None:
         self.UI.fadeActions()
         self.cached_actions = None
         self.UI.setTurn(new_turn)
         self.turn = new_turn
Пример #59
0
    def addTerm(self):
	newterm = tkSimpleDialog.askinteger("Add Term", "Term start date")
	if newterm:
	    newterm = str(newterm)
	    if doc.xpath("//term[@date='"+newterm+"']"):
		tkMessageBox.showwarning("Add Term", "Term "+newterm+" already exists.")
		return
	    etree.SubElement(doc.getroot(),"term").set("date",newterm)
	    self.refreshTerms()
Пример #60
0
 def value(self, row,  col):
     ''' Takes in a row and column and returns the data value.'''
     
     #check if valid row value
     while (row < 0 or row >= self.size()):
         ok = tkSimpleDialog.askinteger('Error: Invalid row', 'Specify a new row here:')
         if (ok != None):
             row = ok
         else:
             row = -1
     
     while (col < 0 or col >= self.cols()):
         ok = tkSimpleDialog.askinteger('Error: Invalid column', 'Specify a new column here:')
         if (ok != None):
             col = ok
         else:
             col = -1
     return self.matrix[row][col]