예제 #1
0
def ask(prompt, default=None, title=''):
	""" Get input from the user. default refers to the value which is initially in the field. Returns None on cancel."""
	import tkSimpleDialog
	if default:
		return tkSimpleDialog.askstring(title, prompt, initialvalue=default)
	else:
		return tkSimpleDialog.askstring(title, prompt)
    def opponent_pick_logic(self, opponent_id):
        pick_made = False

        pick = tkSimpleDialog.askstring(
            "Opponent's pick",
            "Who did your opponent pick?\nCurrent Pick: Round {0}: Pick {1}"
            .format(self.game.current_round, self.game.current_position))

        while not pick_made:
            try:
                if utils.get_player_position(pick, self.game.cursor) is not None:
                    position = utils.get_player_position(pick, self.game.cursor).rstrip('0123456789 ').upper()
                    if utils.get_player_from_table(pick, position, self.game.cursor) is not None:
                        utils.remove_player_from_possible_players(pick, self.game.connection, self.game.cursor)
                        opponent = [opponent for opponent in self.game.opponents if opponent_id == opponent.id][0]
                        opponent.team.append(pick)
                        pick_made = True
                    else:
                        pick = tkSimpleDialog.askstring(
                            "Opponent's pick",
                            "NOT A VALID PICK: please select again\nCurrent Pick: Round {0}: Pick {1}"
                            .format(self.game.current_round, self.game.current_position))

                else:
                    pick = tkSimpleDialog.askstring(
                        "Opponent's pick",
                        "NOT A VALID PICK: please select again\nCurrent Pick: Round {0}: Pick {1}"
                        .format(self.game.current_round, self.game.current_position))
            except AttributeError:
                tkMessageBox.showinfo("Error", "Opponent must pick a valid player")
                pick = tkSimpleDialog.askstring(
                    "Opponent's pick",
                    "NOT A VALID PICK: please select again\nCurrent Pick: Round {0}: Pick {1}"
                    .format(self.game.current_round, self.game.current_position))
예제 #3
0
파일: viper41.py 프로젝트: icyflame/VIPER41
    def changeMastKey(self):

        self.checkpoint()

        attempt1 = tkSimpleDialog.askstring('new master key','Enter the new master key:',show='*')

        if len(attempt1) < 4:
            tkMessageBox.showinfo('failure','minimum length of master key is 4 charachters')
            self.initFrameAndButtons()
            return

        attempt2 = tkSimpleDialog.askstring('confirm new master key','Re-enter the new master key:',show='*')

        if not attempt1 == attempt2:

            tkMessageBox.showinfo('Failure','The two master keys you entered are not the same. \
\nThe master key was not changed. \nTry again.')

            self.initFrameAndButtons()
            return False

        inFile = open('mast','w')

        attempt1 = attempt1 + salt

        att = sha1(attempt1)
        att = att.hexdigest()

        inFile.write(att)

        inFile.close()

        self.initFrameAndButtons() 
예제 #4
0
def userInput():
    #Ask creator of demo/sandbox information for first name, last name, and email address:
    first = tkSimpleDialog.askstring("First Name", "What is the person's first name?")
    last = tkSimpleDialog.askstring("Last Name", "What is the person's last name?")
    mail = tkSimpleDialog.askstring("Email", "What is the person's email address (omit @centurylink.com)?")
    
    #Take the data from inputs and assign them to other variables.
    master = first + "." + last + ".sandbox"
    inbox = mail + "@centurylink.com"
    
    #Authenication API call for CLC in CCTS.
    clc.v1.SetCredentials("a89492344bc24fccb1f8bfd8033d28ed","iI_P:Hc`ylb1sLma")
    
    #Create User API call for CLC in CCTS.
    clc.v1.User.CreateUser(user=master,email=inbox,first_name=first,last_name=last,roles=["ServerAdministrator","NetworkManager","AccountViewer"],alias="CCTS")

    #Create additional variables to the display the information back to the creator of the demo account.
    output = "Demo account successfully created in CCTS."
    output1 = """{0} is the person's first name.""" .format(first)
    output2 = """{0} is the person's last name.""" .format(last)
    output3 = """Persons username is {0}.""" .format(master)
    output4 = """{0} is the person's email address.""" .format(inbox)
    output5 = "The user's permissions are Server Administrator, Network Manager, and Account Viewer."
    
    #Display output back to the creator.
    tkMessageBox.showinfo("Results", output)
    tkMessageBox.showinfo("Results", output1)
    tkMessageBox.showinfo("Results", output2)
    tkMessageBox.showinfo("Results", output3)
    tkMessageBox.showinfo("Results", output4)
    tkMessageBox.showinfo("Results", output5)
    return
예제 #5
0
def getShortestDistance(self):
    '''
    # Function to get call SSSP after asking user for source and destination cities
    :return:
    '''
    source_name = tkSimpleDialog.askstring("City name", "Please enter source city name")
    if source_name is None or self.g.getVertexByName(source_name) is None:
        if source_name is not None: tkMessageBox.showwarning("Name invalid", "City name is not valid")
        return
    dest_name = tkSimpleDialog.askstring("City name", "Please enter destination city name")
    if dest_name is None or self.g.getVertexByName(dest_name) is None:
        if dest_name is not None: tkMessageBox.showwarning("Name invalid", "City name is not valid")
        return

    source = self.g.getVertexByName(source_name)
    dest = self.g.getVertexByName(dest_name)

    self.g.findSSSP(source)
    list = []
    current_vertex = dest
    while current_vertex is not source:
        list.append(current_vertex.name)
        current_vertex = current_vertex.pred
    list.append(current_vertex.name)
    # then we reverse the list
    list.reverse()
    # DEGGING
    print list
    # DEBUGGING
    self.g.getRouteInfoFromList(list)
예제 #6
0
    def promptSession(self):
        ''' Prompts the experimenter for the Subject ID, Session ID,
            and the number of repetitions
        '''

        while (True):
            self.setRepetitions()
            self.specifySequence()

            participantId = askstring(' ','Please enter Subject ID:')
            if participantId == None:
                sys.exit()
            sessionId = askstring(' ','Please enter Session ID:')
            if sessionId == None:
                sys.exit()
            
            sequence = self.sequenceName if self.sequenceType == 'LOADED' else self.sequenceType

            answer = askquestion(' ','Subject: ' + participantId + ', Session: ' + sessionId +
                                 ', Repetitions: ' + str(self.repetitions) +
                                 ', Sequence: ' + sequence + '\n\nIs this correct? ' +
                                 '\n\n(reference CONFIG.yml file for options)')
            if answer == "yes":
                break

        self.data = Data(participantId, sessionId) # Data collection object
예제 #7
0
파일: app.py 프로젝트: iogf/steinitz
    def setup_engine(self):
        self.stockfish_depth = askstring('Stockfish Depth', 'Depth:', initialvalue=self.stockfish_depth)
        self.stockfish_path = askstring('Engine Path', 'Engine Path:', initialvalue=self.stockfish_path)

        setting = shelve.open(os.path.join(os.path.expanduser('~'), '.snz'))
        setting['depth'] = self.stockfish_depth
        setting['path'] = self.stockfish_path
        setting.close()
예제 #8
0
	def __init__(self, parent, qm):
		self.qm = qm
		keywords = [k['ID'] for k in self.qm]
		self.parent = parent
		self.value = []
		print keywords		
		self.value.append(tkSimpleDialog.askstring("","Enter the question ID for which you would like to enter a default response (see terminal for question IDs)."))
		self.value.append(tkSimpleDialog.askstring("", "Enter the default response to the question: %s"%self.value[0]))		
예제 #9
0
    def lookup(self,str_name_list):
        if type(str_name_list) == tuple:
            str_name_list = list(str_name_list)
            print str_name_list
        elif type(str_name_list) == unicode:
            str_name_list = str_name_list.encode('unicode_escape')
            
            str_name_list = re.split('} {',str_name_list)
            
            for x in range(len(str_name_list)):
                str_name_list[x] = str_name_list[x].replace('{','')
                str_name_list[x] = str_name_list[x].replace('}','')
                
            
        else:
            print 'error in open string'
            
        self.bibliography = list()
            
        for name in str_name_list:
            
            
            docstring = convert_pdf_to_txt(name)
            if docstring != -1:
                doi = return_doi(docstring)
                if doi== -1:

                    doi = tkSimpleDialog.askstring("Enter DOI","PDF not properly converted.  Enter DOI. Enter nothing to skip.")
                    if doi == ''or doi==None:
                        ref = Reference('skip___'+name,'','','', '', '' ,'')
                else:
                    html = citation_search(doi)
                    if html!=-1:
                        ref = create_reference(html)
                    else:
                        print "citation search failed", name
                         # (authors,title,journal,year,volume,issue,pages)
                        ref = Reference('unknown___'+name,'','','', '', '' ,'')
                        
            else:
                doi = tkSimpleDialog.askstring("Enter DOI","DOI not found in PDF.  Enter DOI. Enter nothing to skip.")
                if doi == '' or doi == None:
                    ref = Reference('unknown___'+name,'','','', '', '' ,'')
                else:
                    html = citation_search(doi)
                    if html!=-1:
                        ref = create_reference(html)
                    else:
                        print "citation search failed", name
                        ref = Reference('','skip___'+name,'','', '', '' ,'')

            ref.filepath = name
            ref.url = name
            self.bibliography += [ref]

            self.list.insert(END,ref['title'])
        print "done"
        return 0
예제 #10
0
    def getOpener(self, values):
        opener_handlers = [urllib2.HTTPHandler(debuglevel = values.debug)]
        if hasattr(httplib, 'HTTPS'):
            opener_handlers.append(urllib2.HTTPSHandler(debuglevel = values.debug))
        include = None if values.include else self.log
        pSwitches = [values.post301, values.post302, values.post303]
#         opener_handlers = [LogHandler(values.url)] 
#         opener_handlers.append(netHTTPRedirectHandler(location = values.location, include = include, postSwitches = pSwitches))
        opener_handlers.append(netHTTPRedirectHandler(location = values.location, include = include, postSwitches = pSwitches))
    
        cookie_val = None
        if values.cookie_jar: cookie_val = values.cookie_jar
        if values.cookie: cookie_val = values.cookie 

        if cookie_val != None:
            cj = cookielib.LWPCookieJar()
            if os.path.isfile(cookie_val): cj.load(cookie_val)
            opener_handlers.append(urllib2.HTTPCookieProcessor(cj))
 
        passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm()           
        if values.user:
            user, password = values.user.partition(':')[0:3:2]
            if not password:
                try:
                    password = tkSimpleDialog.askstring("Enter password for " + user, "Enter password:"******"Enter password for " + user)
            passwordManager.add_password(None, values.url, user, password)
            opener_handlers.append(urllib2.HTTPBasicAuthHandler(passwordManager))
            if values.auth_method == 'digest':
                opener_handlers.append(urllib2.HTTPDigestAuthHandler(passwordManager))
            pass
        
        if values.proxy:            
            proxyStr = values.proxy
            protocol, user, password, proxyhost = urllib2._parse_proxy(proxyStr)
            protocol = protocol or 'http'
            proxy_handler = urllib2.ProxyHandler({protocol:proxyhost})
            opener_handlers.append(proxy_handler)
            if not user:
                if values.proxy_user:
                    user, password = values.proxy_user.partition(':')[0:3:2]
            if user and not password:
                try:
                    password = tkSimpleDialog.askstring("Enter proxy password for " + user, "Enter password:"******"Enter proxy password for " + user)
                passwordManager.add_password(None, proxyhost, user, password)
                opener_handlers.append(urllib2.ProxyBasicAuthHandler(passwordManager))
                if values.proxy_auth == 'digest':
                    opener_handlers.append(urllib2.ProxyDigestAuthHandler(passwordManager))
            pass
        

        opener = urllib2.build_opener(*opener_handlers)
        return opener
def get_constants():
	mass = None
	csArea = None
	airD = None
	
	# Loads the presets from the file
	data = pickle.load(open("constants.p", "rb"))
	pNames = [str(i[0]) for i in data]
	
	# Prompt for preset or new preset
	preset = tkSimpleDialog.askstring("Load Preset", "Please type a preset name or new")
	if preset == 'new':
		# Prompts for the object's mass
		mass = tkSimpleDialog.askstring("Mass", "Type value of the object's mass(kg)")
		if mass != None:
			# Prompts for the object's Cross-Sectional Area
			csArea = tkSimpleDialog.askstring("Cross-Sectional Area", "Type value of the object's cross-sectional area(m^2)")
			if csArea != None:
				# Prompts for the room's air density
				airD = tkSimpleDialog.askstring("Air Density", "Type value of the room's Air Density(kg/m^3)")
				if airD != None:
					try: # If any of the data entered was not a number, it will throw an error
						mass = float(mass)
						csArea = float(csArea)
						airD = float(airD)
						
						# Asks for a name for the preset. If no name is entered, it will assign it "Temp"
						name = tkSimpleDialog.askstring("Name New Preset", "What would you like to name the new preset?")
						if name == None:
							name = "Temp"
						
						# If the name is already in the file, it will overwrite it
						if name in pNames:
							temp = pNames.index(name)
							data.pop(temp)
							
						# Adds the new preset and rewrites the file
						data.append((name,[mass,csArea,airD]))
						file = open("constants.p", "wb")
						pickle.dump(data, file)
						file.close()
					except ValueError:
						mass = None
						print "ERROR: Values entered invalid"
	else:
		# If it is a preset, it will load the constants. Otherwise, it will throw an error.
		if preset in pNames:
			temp = data[pNames.index(preset)]
			temp2 = temp[1]
			mass = temp2[0]
			csArea = temp2[1]
			airD = temp2[2]
		else:
			if preset != None:
				print "ERROR: ",preset,"has not been defined as a preset"
	return mass, csArea, airD
예제 #12
0
 def gmail(self): # asks for email id and password and saves them 
   userName = tkSimpleDialog.askstring(root,'enter email id')
   password = tkSimpleDialog.askstring(root,'enter password') 
   
   file1 = open('username.txt','w')
   file1.write(userName)
   file2 = open('password.txt','w')
   file2.write(password)
 
   self.enable_imap()
예제 #13
0
def getPassword(prompt="", confirm=0):
    while 1:
        try1 = tkSimpleDialog.askstring("Password Dialog", prompt, show="*")
        if not confirm:
            return try1
        try2 = tkSimpleDialog.askstring("Password Dialog", "Confirm Password", show="*")
        if try1 == try2:
            return try1
        else:
            tkMessageBox.showerror("Password Mismatch", "Passwords did not match, starting over")
예제 #14
0
def getPassword(prompt = '', confirm = 0):
	while 1:
		try1 = tkSimpleDialog.askstring('Password Dialog', prompt, show='*')
		if not confirm:
			return try1
		try2 = tkSimpleDialog.askstring('Password Dialog', 'Confirm Password', show='*')
		if try1 == try2:
			return try1
		else:
			tkMessageBox.showerror('Password Mismatch', 'Passwords did not match, starting over')
예제 #15
0
파일: videoEdit.py 프로젝트: Congren/PYEdit
def specialOne(event):
    canvas = event.widget.canvas
    try:
        message = "What would you like the new width to be?"
        title = "Resize Video"
        width = float(tkSimpleDialog.askstring(title,message))
        message = "What would you like the new height to be?"
        height = float(tkSimpleDialog.askstring(title,message))
        resizeClip(event,width,height)
    except:
        canvas.create_text(canvas.width/2,10,text='Try Again')
예제 #16
0
 def MenuKick(Self):
   target=tkSimpleDialog.askstring("Kick User", "Enter victim's nick:")
   if len(target) == 0:
     return
   reason=tkSimpleDialog.askstring("Kick Reason", "Enter reason (if any):")
   try:
     if len(reason) == 0:
       reason=""
     server.kick(Self.ChannelName, target, reason)
   except:
     pass
예제 #17
0
	def __init__(self, parent, qm):
		self.qm = qm
		keywords = [k['ID'] for k in self.qm]
		self.parent = parent
		self.value = []
		self.value.append(tkSimpleDialog.askstring("","Enter a new question."))
		self.value.append(tkSimpleDialog.askstring("", self.value[0]))
		newkeyword = tkSimpleDialog.askstring("", "Enter a new keyword to identify this question.")
		while newkeyword in keywords:
			newkeyword = tkSimpleDialog.askstring("", "The keyword "+newkeyword+" is already in use. Please enter a new keyword to identify this question.")
			
		self.value.append(newkeyword)
예제 #18
0
 def goToAnglesPlan(self,arm):
     ret=tkSimpleDialog.askstring("GoTo Angles Plan","Angles:")
     if not ret: return
     angles=loadAngles(ret)
     planname=tkSimpleDialog.askstring("GoTo Angles Plan","Plan:")
     if not planname: return
     print "Planning to angles"
     print angles
     plan=arm.goToAngles_plan(angles,joint_tolerance_plan=self.joint_tolerance_plan.get())
     savePlan(planname,plan)
     print plan
     print "Saved plan as "+planname
예제 #19
0
파일: HydroBond.py 프로젝트: rasbt/BondPack
def fetch_bonds_dialog(app):
    protein_obj = tkSimpleDialog.askstring('Object selection',
            'Please enter the name of a protein object loaded in PyMOL: ',
                           parent=app.root) 
    ligand_obj = tkSimpleDialog.askstring('Object selection',
            'Please enter the name of a ligand object loaded in PyMOL: ',
                           parent=app.root)
    distance = tkSimpleDialog.askstring('Distance selection',
            'Please enter a distance in Angstrom (e.g., 3.2): ',
                           parent=app.root)

    draw_bonds(protein_obj, ligand_obj, distance)
예제 #20
0
    def add_to_repertoire(self):

        nextmove = tksd.askstring("Next Move","Enter next move:")
        comments = tksd.askstring("Comments","Enter comments:")
        try:
            self.myrep.AddToDict(self.chessboard.export(),nextmove,comments)
        except repertoire.RepertoireException as e:
            print 'Exception! ', e.value
            tkmb_result = tkmb.askquestion('Warning!','Do you want to overwrite this position in your repertoire?',icon='warning')
            print "tkmb_result is ",tkmb_result
            if tkmb_result == 'yes':
                self.myrep.AddToDict(self.chessboard.export(),nextmove,comments,forceoverwrite=True)
예제 #21
0
파일: videoEdit.py 프로젝트: Congren/PYEdit
def specialThree(event):
    #asks about when user wants filter to be appplied and applies it
    canvas = event.widget.canvas
    try:    
        message = "What time would you like the filter to begin??"
        title = "Insert Filter"
        start = float(tkSimpleDialog.askstring(title,message))
        message = "What time would you like the filter to stop?"
        end = float(tkSimpleDialog.askstring(title,message))
        applyFilter(event,start,end)
    except:
        canvas.create_text(canvas.width/2,10,text='Try Again')
def create_grade():
    name = tkSimpleDialog.askstring("Create an Entry", "Please enter the student's name")
    name = name.capitalize()
    if name in student_grades:
        tkMessageBox.showinfo("Sorry", "Student already exists. Please choose a different option !!!")
    else:
        score = tkSimpleDialog.askstring("Create an Entry", "Please enter the student's score")
        if int(score) not in range(0, 101):
            tkMessageBox.showinfo("Sorry", "Only score from 0 to 100 is acceptable. Please do it again !!!")
        else:
            student_grades[name] = int(score)
            tkMessageBox.showinfo("Congratulation", "You created the grade book successfully")
def BScreensetup():
    global GRWN
    global GRW
    global GRHN
    global GRH
    global STOREtrace
    global Vdiv
    
    if (STOREtrace == True):
        showwarning("WARNING","Clear stored trace first")
        return()

    s = askstring("Screensize", "Give number:\n(1, 2 or 3)")

    # if (s == None):         # If Cancel pressed, then None
    #     return()

    try:                    # Error if for example no numeric characters or OK pressed without input (s = "")
        v = int(s)
    except:
        s = "error"

    if s != "error":
        if v == 1:
            GRW = int(GRWN / 4)
            GRH = int(GRHN / 4)
        if v == 2:
            GRW = int(GRWN / 2)
            GRH = int(GRHN / 2)
        if v == 3:
            GRW = int(GRWN)
            GRH = int(GRHN)

    s = askstring("Divisions", "Value: " + str(Vdiv) + "\n\nNew value:\n(4-100)")

    if (s == None):         # If Cancel pressed, then None
        return()

    try:                    # Error if for example no numeric characters or OK pressed without input (s = "")
        v = int(s)
    except:
        s = "error"

    if s != "error":
        Vdiv = v

    if Vdiv < 4:
        Vdiv = 4

    if Vdiv > 100:
        Vdiv = 100
    UpdateTrace()
예제 #24
0
def main():
    idir = getcwd()
    OOT_ROM_NAME = askopenfilename(title="OoT Debug ROM",filetypes=[('N64 ROM files','*.z64')],initialdir = idir)
    if(not OOT_ROM_NAME):
        return
    MM_ROM_NAME = askopenfilename(title="Decompressed MM ROM",filetypes=[('N64 ROM files','*.z64')],initialdir = idir)
    if(not MM_ROM_NAME):
        return
    mmtmp = open(MM_ROM_NAME,"rb")
    mmtmp.seek(0,2)
    if ( mmtmp.tell() == 0x2000000 ):
        showerror(title = "uh lol", message = "Decompressed MM ROM, dummy!\nAborting port!")
        sys.exit(-1)
    argv__ = ['z64porter.py', OOT_ROM_NAME, MM_ROM_NAME]
    askaddress = True
    port_en = None
    while 1:
        argv_ = argv__[:]
        argv_ .append( askstring(title = "OoT scene", prompt = "Scene to replace in OoT (use 0x if hex):" ))
        if(not argv_[-1]):
            return
        argv_ .append( askstring(title = "MM scene", prompt = "Scene to port from MM (use 0x if hex):" ))
        if(not argv_[-1]):
            return
        if (askaddress):
            if (askyesno(title = "Address", message = "Insert at your own address?" )):
                argv_.append( "-o" )
                addr_msg = "Address (hex) to insert port at:"
                if (port_en != None):
                    addr_msg += "\nReccomended: %08X"%( port_en )
                argv_.append( "0x%s" % (askstring(title = "Address", prompt = addr_msg )))
            else:
                askaddress = False
        else:
            argv_.append("-o")
            argv_.append("0x%08X" % port_en)
        if (askyesno(title = "Safe mode", message = "Port in safe mode?" )):
            argv_.append( "-s" )
        if (askyesno(title = "Music", message = "Use your own music value?" )):
            argv_.append( "-m" )
            argv_.append(askstring(title = "Music", prompt = "Music value (use 0x if hex):" ))
        argv_.append("-q")
        try:
            port_st,port_en = port_scene( argv_ )
            showinfo(title="Success", message="Scene ported successfully\nPort offsets:\n%08X - %08X"%(port_st,port_en))
        except:
            showerror(title="Uhoh!", message="Failure :(.\nIf you opened this from a shell,\nplease report the error message from." )
            break
        if not (askyesno(title = "Another", message = "Port another scene?" )):
            break
예제 #25
0
def MenuKick2():
  chan=tkSimpleDialog.askstring("Channel Name", "Enter channel name:")
  if chan == None:
    return
  target=tkSimpleDialog.askstring("Kick User", "Enter victim's nick:")
  if target == None:
    return
  reason=tkSimpleDialog.askstring("Kick Reason", "Enter reason (if any):")
  try:
    if reason == None:
      reason=""
    server.kick(chan, target, reason)
  except:
    pass
예제 #26
0
 def findAndReplaceInText(self):
     # finds and replaces a word
     title = "Find and replace"
     message = "Enter string to remove"
     stringToRemove = tkSimpleDialog.askstring(title,message)
     if(stringToRemove == None): return
     message = "Enter string to add"
     stringToReplace = tkSimpleDialog.askstring(title, message)
     if(stringToReplace == None): return
     self.currentText = self.currentText.replace(
         stringToRemove, stringToReplace)
     self.textWidget.delete(1.0, END)
     self.textWidget.insert(1.0, self.currentText)
     self.highlightString(stringToReplace)
def get_datestr(ui):
    import tkSimpleDialog
    from datetime import datetime
    import re
    ui.datestr = tkSimpleDialog.askstring('Flight Date','Flight Date (yyyy-mm-dd):')
    if not ui.datestr:
        ui.datestr = datetime.utcnow().strftime('%Y-%m-%d')
    else:
        while not re.match('[0-9]{4}-[0-9]{2}-[0-9]{2}',ui.datestr):
            ui.datestr = tkSimpleDialog.askstring('Flight Date',
                                                  'Bad format, please retry!\nFlight Date (yyyy-mm-dd):')
            if not ui.datestr:
                ui.datestr = datetime.utcnow().strftime('%Y-%m-%d')
    ui.ax1.set_title(ui.datestr)
예제 #28
0
파일: cafwin.py 프로젝트: VanDeng95/WaveSyn
 def onLoadClick(self):
     dialogParam = {'filetypes':[('Matlab', '.mat')]}
     filename = askopenfilename(**dialogParam)
     if not filename:
         return
     matData = loadmat(filename)
     xName = askstring('Variable Name', 'Enter the name of the 1st sequence:')
     self.__paramX.entry_text = xName
     x = matData[xName].flatten()
     yName = askstring('Variable Name', 'Enter the name of the 2nd sequence:')
     y = matData[yName].flatten()
     self.__paramY.entry_text = yName
     dcaf = np.abs(ambiguityfunction.discaf(x, y))
     self.__topwin.figure_book[0].show_image(dcaf)
     self.__topwin.caf   = dcaf
예제 #29
0
import skimage.measure
import PIL
import time
import sys
import scipy.misc
import pylab as pl

import tkMessageBox
import tkFileDialog
import tkSimpleDialog
import Tkinter as tk
# hides ugly empty TK window
root = tk.Tk()
root.withdraw()

plate_name = tkSimpleDialog.askstring('File', 'Plate Name:')

sys.path.append("C:\Program Files\Micro-Manager-1.4")
sys.path.append("C:\Users\ng\Desktop\ColonyPicker\Printrun-master")

# Imports the modules for the filterwheel, camera and shutters
import MMCorePy
core = MMCorePy.CMMCore()
core.unloadAllDevices()
# makes sure there isn't anything previously loaded

# Loads Camera
core.loadDevice("Camera", "PrincetonInstruments", "Camera-1")

core.initializeAllDevices()
예제 #30
0
import Tkinter, tkSimpleDialog

root = Tkinter.Tk()
root.withdraw()

numero = tkSimpleDialog.askinteger("Entero", "Intoduce un entero")
print numero
texto = tkSimpleDialog.askstring("String", "Intoduce un String")
print texto
예제 #31
0
    global bankfile_name, plotly_code, saldo

    Tk().withdraw()
    # Read bankfile csv.
    try:
        bankfile_name = askopenfilename(filetypes=[("CSV File", "*.csv")])
        bankfile_name = bankfile_name[:-4]
        read_bank_file(bankfile_name)
    except:
        messagebox.showinfo("Error", "Invalid csv file")
        sys.exit(1)
    # Read plotly file.
    try:
        plotlyfile_name = open(os.path.join(curr_dir, 'plotly-basic.min.js'))
        plotly_code = "<script> " + plotlyfile_name.read() + " </script>"
    except:
        messagebox.showinfo("Error", "Invalid Plotly file")
        sys.exit(1)
    # Ask user for current saldo.
    try:
        u_saldo = askstring(
            "Saldo", "Huidig saldo (of op laatst beschikbare datum)")
        saldo = float(u_saldo.replace(",", "."))
    except:
        saldo = 0.0

    read_categories()
    check_bankfile()
    get_first_last_date()
    create_output()
예제 #32
0
    def __init__(self, app):
        import os
        jobid = tkSimpleDialog.askstring(
            'PDB Loader',
            'Enter the Job ID given to you by the CASTp web server\nThe Job ID is case sensitive!',
            parent=app.root)
        pdbfile = urllib.urlretrieve(CASTP_URL_BASE + '/working/' + jobid +
                                     '.pdb')[0]
        if (os.path.getsize(pdbfile) > 400):
            pocfile = urllib.urlretrieve(CASTP_URL_BASE + '/working/' + jobid +
                                         '.poc')[0]
            pocInfofile = urllib.urlretrieve(CASTP_URL_BASE + '/working/' +
                                             jobid + '.pocInfo')[0]
        # mouthfile = urllib.urlretrieve(CASTP_URL_BASE + '/working/' + jobid + '.mouth')[0]
        # mouthInfofile = urllib.urlretrieve(CASTP_URL_BASE + '/working/' + jobid + '.mouthInfo')[0]

        else:
            os.remove(pdbfile)
            pdbfile = urllib.urlretrieve(CASTP_URL_BASE + '/uploads/' + jobid +
                                         '.pdb')[0]
            pocfile = urllib.urlretrieve(CASTP_URL_BASE + '/uploads/' + jobid +
                                         '.poc')[0]
            pocInfofile = urllib.urlretrieve(CASTP_URL_BASE + '/uploads/' +
                                             jobid + '.pocInfo')[0]
        # mouthfile = urllib.urlretrieve(CASTP_URL_BASE + '/uploads/' + jobid + '.mouth')[0]
        # mouthInfofile = urllib.urlretrieve(CASTP_URL_BASE + '/uploads/' + jobid + '.mouthInfo')[0]

        if (os.path.getsize(pdbfile) < 400):
            tkMessageBox.showerror(
                'Oops!',
                'Could not retrieve ' + jobid +
                '\nMake sure you entered it in correctly, the Job ID is case sensitive',
                parent=app.root)

        pdbin = open(pdbfile, 'r')
        pdbout = os.path.dirname(pdbfile) + os.sep + jobid + '.pdb'
        fpout = open(pdbout, 'w')
        fpout.write(pdbin.read())
        pdbin.close()
        fpout.close()
        os.remove(pdbfile)
        cmd.load(pdbout)
        pocNums = {}
        pocDict = {}
        pocin = open(pocInfofile, "r")

        for line in pocin:
            stuff = line[12:16]
            stuff = stuff.strip()
            if (stuff.isdigit()):
                pocDict[stuff] = ''
                idp = int(stuff)
                pocNums[stuff] = idp
        pocin.close()

        pocin = open(pocfile, "r")
        for line in pocin:
            atmnum = line[6:11]
            atmnum = atmnum.strip()
            pocid = line[67:70]
            pocid = pocid.strip()
            if (atmnum.isdigit()):
                if len(pocDict[pocid]) == 0:
                    pocDict[pocid] = atmnum
                else:
                    pocDict[pocid] = pocDict[pocid] + '+' + atmnum
        pocin.close()

        os.remove(pocfile)
        os.remove(pocInfofile)
        os.remove(pdbout)
        pids = list(pocNums.values())

        pids.sort()
        pids.reverse()
        counter = 0
        for idp in pids:
            pid = str(idp)
            vls = pocDict[pid].split('+')
            currAtms = {}
            counter = 0
            for vl in vls:
                ivl = int(vl)
                currAtms[counter] = ivl
                counter = counter + 1

            atms = list(currAtms.values())
            atms.sort()

            newsel = ''
            beg = ''
            currSelections = {}
            SelectionCntr = 0
            for i in range(len(atms)):
                if i == 0:
                    newsel = str(atms[i])
                else:
                    newsel = newsel + "+" + str(atms[i])

                if i % 50 == 0 and i != 0:
                    Scntr = str(SelectionCntr)
                    tempPocket = "Pocket_" + pid + "_" + Scntr
                    currSelections[SelectionCntr] = tempPocket
                    SelectionCntr = SelectionCntr + 1
                    cmd.do("select " + tempPocket + ", id " + newsel + ",1,1")
                    newsel = ""

            if newsel != "":
                Scntr = str(SelectionCntr)
                tempPocket = "Pocket_" + pid + "_" + Scntr
                currSelections[SelectionCntr] = tempPocket
                SelectionCntr = SelectionCntr + 1
                cmd.do("select " + tempPocket + ", id " + newsel + ",0,1")
                #                cmd.do("select " + tempPocket + ", id " + newsel + ",1,1")
                newsel = ""

            generalSelect = "select Pocket_" + pid + ", "

            for i in range(len(currSelections)):
                if i == 0:
                    generalSelect = generalSelect + currSelections[i]
                else:
                    generalSelect = generalSelect + " or " + currSelections[i]

            generalSelect = generalSelect + ",1,1"
            cmd.do(generalSelect)
            for i in range(len(currSelections)):
                remove = "delete " + currSelections[i]
                cmd.do(remove)
            cmd.do("refresh")
            counter = counter + 1
예제 #33
0
    def __init__(self, app):
        import os
        remote_file = tkSimpleDialog.askstring(
            'PDB Loader',
            'Enter the PDB or Job ID\n\nFor PDB id\'s, you may also enter the chain.\ni.e. 1a2zA for PDB 1a2z Chain A ',
            parent=app.root)
        sizeof = len(remote_file)
        noerror = 1
        pdbcode = ''
        emessage = ''
        pdbfile = ''
        pocfile = ''
        infofile = ''
        jobid = ''

        # Gave a bad PDB code!  PDB codes must be [a-z0-9A-Z]{4}
        if sizeof != 4 and sizeof != 5:
            tkMessageBox.showerror('Oops',
                                   remote_file +
                                   ' does not appear to be a PDB code',
                                   parent=app.root)
            noerror = 0

        # Get Pocket information from CASTp web server!  Size 4 : full structure file
        # Size 5 : a single chain structure file
        if sizeof == 4:
            remote_file = remote_file.lower()
            pdbcode = remote_file
            jobid = pdbcode
            pdir = remote_file[1:3]
            path = CASTP_URL_BASE + '/cast/' + pdir + '/' + remote_file + '.pdb'
            pocpath = CASTP_URL_BASE + '/cast/' + pdir + '/' + remote_file + '.poc'
            infopath = CASTP_URL_BASE + '/cast/' + pdir + '/' + remote_file + '.pocInfo'

        if sizeof == 5:
            pdbcode = remote_file[0:4]
            chident = remote_file[4:5]
            pdbcode = pdbcode.lower()
            chident = chident.upper()
            jobid = pdbcode + '.' + chident
            pdir = remote_file[1:3]
            path = CASTP_URL_BASE + '/sccast/' + pdir + '/' + pdbcode + '.' + chident + '.pdb'
            pocpath = CASTP_URL_BASE + '/sccast/' + pdir + '/' + pdbcode + '.' + chident + '.poc'
            infopath = CASTP_URL_BASE + '/sccast/' + pdir + '/' + pdbcode + '.' + chident + '.pocInfo'

        # Try to retrieve the files if there are no previous errors.
        if noerror:
            pdbfile = urllib.urlretrieve(path)[0]
            pocfile = urllib.urlretrieve(pocpath)[0]
            infofile = urllib.urlretrieve(infopath)[0]
            #            tkMessageBox.showerror('Gotit', pdbfile, parent=app.root)
            if (os.path.getsize(pdbfile) < 400
                    or os.path.getsize(pocfile) < 400
                    or os.path.getsize(infofile) < 400):
                emessage = pdbcode + ' is not in the CASTp database'
                noerror = 0

        if noerror == 0:
            tkMessageBox.showerror('Sorry', emessage, parent=app.root)

        if noerror:

            # Write the contents of the pdb file to a local file. #########
            pdbin = open(pdbfile, 'r')
            pdbout = os.path.dirname(pdbfile) + os.sep + jobid + '.pdb'
            fpout = open(pdbout, 'w')
            fpout.write(pdbin.read())
            pdbin.close()
            fpout.close()
            os.remove(pdbfile)
            cmd.load(pdbout)  # Load the file
            ###############################################################

            # Read the .pocInfo file.  Create an initially empty dictionary with the
            # pocket number as the keys. Create another dictionary called pocNums
            # with the pocket number as the key and the integer pocket number as
            # the value.
            pocNums = {}
            pocDict = {}
            pocin = open(infofile, "r")
            for line in pocin:
                stuff = line[12:16]  # Pocket Number
                stuff = stuff.strip()
                if (stuff.isdigit()):
                    pocDict[stuff] = ''
                    idp = int(stuff)
                    pocNums[stuff] = idp

            pocin.close()
            ##############################################################

            # Read the .poc file.  Load the atom's of the pockets into the corresponding
            # pocket in pocDict (key = pocket number).
            pocin = open(pocfile, "r")
            for line in pocin:
                atmnum = line[6:11]
                atmnum = atmnum.strip()
                pocid = line[67:70]
                pocid = pocid.strip()
                if (atmnum.isdigit()):
                    if len(pocDict[pocid]) == 0:
                        pocDict[pocid] = atmnum
                    else:
                        pocDict[pocid] = pocDict[pocid] + "+" + atmnum

            pocin.close()
            ##############################################################################

            # Remove the .poc, .pocInfo and pdb file from the users temporary directory.
            os.remove(pocfile)
            os.remove(infofile)
            os.remove(pdbout)
            #############################################################################

            # Make an array of the pocket numbers and sort them by pocket number.
            #  Reverse the order of the sort (like CASTp webserver) such that
            #  the larger pockets will be listed first.
            pids = list(pocNums.values())
            pids.sort()
            pids.reverse()
            #####################################################################

            # Load the pocket information into pyMOL!  This section is a little messy.
            #  There is a bug!  If there are too many atoms in the pocket, it can't load
            #  them all.  Need to find a way around this.
            #  Fix 1:  I reduced entries such as atom nums 1,2,3,4,5 to 1-5.  This helps,
            #          but doesn't completely fix the problem.
            counter = 0

            for idp in pids:  # for each pocket number (sorted)
                pid = str(idp)
                vls = pocDict[pid].split('+')
                numgrps = int(len(vls) / 50)  # attempt to make groups of atoms
                stnumgrps = str(numgrps)
                currAtms = {}
                counter = 0

                # For each atom in the current pocket, push the atoms into an
                # array 'currAtms'.  Sort this array.
                for vl in vls:
                    ivl = int(vl)
                    currAtms[counter] = ivl
                    counter = counter + 1

                atms = list(currAtms.values())
                atms.sort()
                #############################################################

                # Here I create a new representation of the atoms.
                # If there are a group of ungapped sequential atoms
                #  I represent them as the x-y, where x is the smallest
                #  atom number in the group and y is the largest.
                #  i.e. If pocket contains 1,4,5,6,8,9,10,12..
                #       this can be represented as 1,4-6,8-10,12

                newsel = ''
                beg = ''
                currSelections = {}
                SelectionCntr = 0
                for i in range(len(atms)):
                    if i == 0:
                        newsel = str(atms[i])
                    else:
                        newsel = newsel + "+" + str(atms[i])

                    if i % 50 == 0 and i != 0:
                        Scntr = str(SelectionCntr)
                        tempPocket = "Pocket_" + pid + "_" + Scntr
                        currSelections[SelectionCntr] = tempPocket
                        SelectionCntr = SelectionCntr + 1
                        cmd.do("select " + tempPocket + ", id " + newsel +
                               ",1,1")
                        newsel = ""

                if newsel != "":
                    Scntr = str(SelectionCntr)
                    tempPocket = "Pocket_" + pid + "_" + Scntr
                    currSelections[SelectionCntr] = tempPocket
                    SelectionCntr = SelectionCntr + 1
                    cmd.do("select " + tempPocket + ", id " + newsel + ",0,1")
                    #                    cmd.do("select " + tempPocket + ", id " + newsel + ",1,1")
                    newsel = ""

                generalSelect = "select Pocket_" + pid + ", "

                for i in range(len(currSelections)):
                    if i == 0:
                        generalSelect = generalSelect + currSelections[i]
                    else:
                        generalSelect = generalSelect + " or " + currSelections[
                            i]

                generalSelect = generalSelect + ",1,1"
                cmd.do(generalSelect)
                for i in range(len(currSelections)):
                    remove = "delete " + currSelections[i]
                    cmd.do(remove)
                cmd.do("refresh")
                counter = counter + 1
def ask(prompt, default=None, title=''):
    """ Get input from the user. default refers to the value which is initially in the field. Returns None on cancel."""
    if default:
        return tkSimpleDialog.askstring(title, prompt, initialvalue=default)
    else:
        return tkSimpleDialog.askstring(title, prompt)
예제 #35
0
 def ask(self, question, password=False):
     """
     Show a question in a dialog window and store the user's answer.
     """
     self.answer = tkSimpleDialog.askstring('Question', question)
예제 #36
0
"""
from __future__ import division
import functions as fn
import math
import datetime
import xlrd
import re
import tkSimpleDialog
from scipy import stats
import matplotlib.pyplot as plt
from classes import *
from option_class import *
from WindPy import w
import Tkinter as tk
tt=tk.Tk()
trade_date=tkSimpleDialog.askstring(u'华泰期货',u'请输入获取交易日期的收盘价',initialvalue ='20160921')
tk.Tk.destroy(tt)
def input_position():
    path=u'C:\\Users\\Administrator\\Desktop\\场外期权\\交易数据08.09\\'
    fname=path+u'PnL Explained Vanilla20160921.xlsm'
    book = xlrd.open_workbook(fname)
    sh=book.sheet_by_name('Calc')
    n=sh.nrows   
    for i in range(n):
        if sh.cell_value(i,2)==u'金牛数据':
            i+=2
            break
    fu_colname=sh.row_values(i)
    fu_pos=[]
    i+=1
    while sh.cell_value(i,2)<>'INSERT ROW':
예제 #37
0
 def prompt_new_name(self):
     new_name = tkSimpleDialog.askstring("Name Change", "New name")
     if new_name is not None:
         self.request_name_change(new_name)
예제 #38
0
# a spiral of family names
awnser = raw_input("want to see a spiral? yes or no\n")
if awnser == "yes":
    print "working..."

    import turtle
    import tkSimpleDialog
    t = turtle.Pen()
    t.speed(0)
    turtle.bgcolor ("black")
    colors = ["pink", "green", "red", "brown", "salmon", "yellow", "gold", "silver", "blue", "purple"]

    family = []
    name = tkSimpleDialog.askstring("family name", "enter in a name, or press [ENTER] to end")

    while name != "":
        family.append(name)
        name = tkSimpleDialog.askstring("family name", "enter in a name, or press [ENTER] to end")


    for x in range(100):
        t.penup()
        t.forward(x*5)
        position = t.position()
        heading = t.heading()
        print (position, heading)

        for y in range(len(family)):
            t.pendown()
            t.width(x/20)
            t.pencolor(colors[y%len(family)%10])
예제 #39
0
def askForString(master, title, text):
    return tkSimpleDialog.askstring(parent=master, title=title, prompt='')
예제 #40
0
 def get_name(self):
     root = Tkinter.Tk()
     root.withdraw()
     return tkSimpleDialog.askstring('New Record!', 'Wow! You made a new record! What is your name?')
예제 #41
0
파일: zopeedit.py 프로젝트: bendavis78/zope
    def getEditorCommand(self):
        """Return the editor command"""
        editor = self.options.get('editor')
        
        if win32 and editor is None:
            from _winreg import HKEY_CLASSES_ROOT, OpenKeyEx, \
                                QueryValueEx, EnumKey
            from win32api import FindExecutable
            import pywintypes
            # Find editor application based on mime type and extension
            content_type = self.metadata.get('content_type')
            extension = self.options.get('extension')
            
            if content_type:
                # Search registry for the extension by MIME type
                try:
                    key = 'MIME\\Database\\Content Type\\%s' % content_type
                    key = OpenKeyEx(HKEY_CLASSES_ROOT, key)
                    extension, nil = QueryValueEx(key, 'Extension')
                except EnvironmentError:
                    pass
            
            if extension is None:
                url = self.metadata['url']
                dot = url.rfind('.')

                if dot != -1 and dot > url.rfind('/'):
                    extension = url[dot:]

            if extension is not None:
                try:
                    key = OpenKeyEx(HKEY_CLASSES_ROOT, extension)
                    classname, nil = QueryValueEx(key, None)
                except EnvironmentError:
                    classname = None

                if classname is not None:
                    try:
                        # Look for Edit action in registry
                        key = OpenKeyEx(HKEY_CLASSES_ROOT, 
                                        classname+'\\Shell\\Edit\\Command')
                        editor, nil = QueryValueEx(key, None)
                    except EnvironmentError:
                        pass

                    if editor is None:
                        # Enumerate the actions looking for one
                        # starting with 'Edit'
                        try:
                            key = OpenKeyEx(HKEY_CLASSES_ROOT, 
                                            classname+'\\Shell')
                            index = 0
                            while 1:
                                try:
                                    subkey = EnumKey(key, index)
                                    index += 1
                                    if str(subkey).lower().startswith('edit'):
                                        subkey = OpenKeyEx(key, 
                                                           subkey + 
                                                           '\\Command')
                                        editor, nil = QueryValueEx(subkey, 
                                                                   None)
                                    else:
                                        continue
                                except EnvironmentError:
                                    break
                        except EnvironmentError:
                            pass

                    if editor is None:
                        try:
                            # Look for Open action in registry
                            key = OpenKeyEx(HKEY_CLASSES_ROOT, 
                                            classname+'\\Shell\\Open\\Command')
                            editor, nil = QueryValueEx(key, None)
                        except EnvironmentError:
                            pass

                if editor is None:
                    try:
                        nil, editor = FindExecutable(self.content_file, '')
                    except pywintypes.error:
                        pass
            
            # Don't use IE as an "editor"
            if editor is not None and editor.find('\\iexplore.exe') != -1:
                editor = None

        if not editor and not win32 and has_tk():
            from tkSimpleDialog import askstring
            editor = askstring('Zope External Editor', 
                               'Enter the command to launch the default editor')
            if not editor: 
                sys.exit(0)
            self.config.set('general', 'editor', editor)
            self.config.save()

        if editor is not None:            
            return editor
        else:
            fatalError('No editor was found for that object.\n'
                       'Specify an editor in the configuration file:\n'
                       '(%s)' % self.config.path)
예제 #42
0
def temperature():
	if isConnected==False:
		tkMessageBox.showerror("connexion","Veuillez vous connecter au serveur d'abord")
	else:
		q=int(var.get())
		if taille.get()=='' or q==0:
			tkMessageBox.showwarning("info","Veuillez renseigner les champs!")
		elif int(taille.get())==0:
			tkMessageBox.showwarning("info","Donner un entier superieur a 0")
		else:
			fonct_temp=tkSimpleDialog.askstring("f(x,y)=a*x + b*x + c", "Entrer la fonction")
			if(fonct_temp==""):
				tkMessageBox.showerror("Erreur", "Entrer la fonction!")
			else:
				
				ok = True
				try:
					print(fonct_temp)		
					ok = (len(fonct_temp.split('x'))==2) and (len(fonct_temp.split('y'))==2)
				except:
					ok = False		
				if ok:
					
					dlg1 = Toplevel(master=fen)
					dlg1.geometry("900x600")
					
					fig = plt.figure()
					center(dlg1)
					traceur = fig.add_subplot(111)
					canvas = FigureCanvasTkAgg(fig, master=dlg1)
					canvas.get_tk_widget().pack()
					#ajout de la barre de navigation
					toolbar = NavigationToolbar2TkAgg(canvas, dlg1)
					toolbar.update()
					canvas._tkcanvas.pack()
					p=int(taille.get())
					cmd = taille.get()+" "+str(var.get())+" coloriage"
					
					if q==1:
						sockClient.send(cmd.encode())
						for i in range(0,p+1):
								traceur.plot([0,1],[float(i)/p,float(i)/p],'white',lw=2) #tracee des traits horizontaux
								traceur.plot([float(i)/p,float(i)/p],[0,1],'white',lw=2) #tracee des traits verticaux
								traceur.plot([float(i)/p,0],[0,float(i)/p],'white',lw=2) #tracee des traits obliques de la partie basse du carre
								traceur.plot([float(i)/p,1],[1,float(i)/p],'white',lw=2) #tracee des traits obliques de la partie haute du carre
						
					if q==2:
						sockClient.send(cmd.encode())
						for i in range(0,p+1):
								traceur.plot([0,1-float(i)/p],[float(i)/p,float(i)/p],'white',lw=2) #tracee des traits horizontaux
								traceur.plot([float(i)/p,float(i)/p],[0,1-float(i)/p],'white',lw=2) #tracee des traits verticaux
								traceur.plot([float(i)/p,0],[0,float(i)/p],'white',lw=2) # tracee des traits obliques 
					
					coords=sommets=triangles=list
					#recuperation des coordonnees
					coords = getCoords("tmp",int(var.get()),int(p))					
					#recuperation des numeros
					sommets = getSommets("tmp")
					
					triangles = getTriangles(coords,sommets)#recuperation des triangles à colorier
					inteTriangles = getIntegrales(triangles,fonct_temp)#valeurs des integrales au niveau de chaque element fini du maillage
					coloriage(triangles,inteTriangles,traceur,canvas)#application des couleurs		
					
					Button(dlg1, text="Quitter", command=dlg1.destroy,font=("Helvetica", 20),fg='grey').pack(side=LEFT)

					
				else:
					tkMessageBox.showinfo("info!","Entrer une fonction de la forme ax+bx+c")
예제 #43
0
 def get_string(self, win_title, win_question):
     string = askstring(win_title, win_question)
     return string
예제 #44
0
def generate_qr_code():
	var0 = tkSimpleDialog.askstring("QR IRN Generate","Please enter the Invoice month and year(mm-yyyy): ")
	tkMessageBox.showinfo("Message", "Please wait while the QR IRN is generating")
	create_qr_image(var0)
예제 #45
0

def draw_o(x, y):
    rachel.pencolor("blue")
    rachel.penup()
    rachel.setpos(x + 30, y - 80)
    rachel.pendown()
    rachel.circle(40)


player1 = [draw_x, ' ']
player2 = [draw_o, ' ']

import tkSimpleDialog

player1[1] = tkSimpleDialog.askstring('Player 1', 'Enter name: ')
player2[1] = tkSimpleDialog.askstring('Player 2', 'Enter name: ')

player = ()
num_moves_made = 0

boxes = {
    1: 'empty',
    2: 'empty',
    3: 'empty',
    4: 'empty',
    5: 'empty',
    6: 'empty',
    7: 'empty',
    8: 'empty',
    9: 'empty'
예제 #46
0
def generate_report():
	var0 = tkSimpleDialog.askstring("Generate Invoice","Please enter the Invoice month and year(mm-yyyy): ")
	tkMessageBox.showinfo("Message", "Please wait while the Invoice is gettting generated")
	generate_invoice(var0)
예제 #47
0
def delete_data():
	var0 = tkSimpleDialog.askstring("Delete data","Please enter the Invoice month and year(mm-yyyy): ")
	tkMessageBox.showinfo("Message", "Please wait while the data is being deleted")
	delete_data_function_call(var0)
예제 #48
0
def saveAs():
    filename = tkSimpleDialog.askstring("Name prompt",
                                        "enter your name") + '.wav'
    sciWav.write(filename, 44000, data)
예제 #49
0
def generate_revenue_report():
	var0 = tkSimpleDialog.askstring("Delete data","Please enter the Invoice month and year(mm-yyyy): ")
	tkMessageBox.showinfo("Message", "Please wait while the MIS Revenue Report is being generated")
	generate_revenue_report_function_call(var0)
예제 #50
0
def ask_user(prompt, command):
    root = Tkinter.Tk()
    var = tkSimpleDialog.askstring(str(prompt), str(command))
    #print var
    return var
예제 #51
0
def getselection(app):
    selection = tkSimpleDialog.askstring('resicolor',
                                       'Please enter a selection',
                                       parent=app.root)
    resicolor(selection)
예제 #52
0
import subprocess
from tkMessageBox import askquestion
from tkFileDialog import askopenfilename
from tkSimpleDialog import askstring
from Tkinter import Tk
def rel(path):
    return os.path.join(os.path.dirname(__file__),path)
config = open(rel('gamelist.conf'), 'r').read()
data = eval(config)

Tk().withdraw()
ans  = askquestion("Image", "Do you want to enter a custom command? (otherwise we ask for a execudable)")

if ans == 'no':    
    cmd = askopenfilename() 
    cmd += askstring("Flags","Addional flags: ")
    if len(cmd)<1:
        print "pleas enter something next time"
        sys.exit(0)
else: 
    cmd = askstring("Command","Command: ")
     
title = askstring("Title","Title: ")
if len(title)<1:
    print "pleas enter something next time"
    sys.exit(0)
desc = askstring("Description","Description: ")
if len(desc)<1:
    print "pleas enter something next time"
    sys.exit(0)
예제 #53
0
                if Solution[step][ic * 4 - 1] == 2 and solution_index == 0:
                    solution_index = 1
                    Solution[step][ic * 4 - 1] = 1
                    if Type[cube[ic][0]][cube[ic][1]] != 'i':
                        Solving[cube[ic][0]][cube[ic][1]] -= 1
                    cube[ic][1] -= 1
            step += 1
            loop_index = 2
    hard = dead * 100.00 / (dead + solutions)
    print "Solutions:", solutions, "Dead end:", dead, "Hard", hard, "%"


master = Tk()
master.resizable(width=0, height=0)

name = tkSimpleDialog.askstring("Name", "Enter Project Name")
size = tkSimpleDialog.askinteger("Size", "Enter Project Demensions")

Matrix = [[0 for x in xrange(size)] for x in xrange(size)]
Type = [['n' for x in xrange(size)] for x in xrange(size)]
Location = [0 for x in xrange(2)]
Testingmode = [0 for x in xrange(1)]

w = Canvas(master, width=(size * 15), height=(size * 15))
w.bind('<Button-1>', buttonOne)
w.bind('<Button-2>', buttonTwo)
w.bind_all('s', saveLevel)
w.bind_all('i', makeInfinite)
w.bind_all('t', makeTeleporter)
w.bind_all('h', hardEvaluation)
w.bind_all('p', makePlayerCube)
예제 #54
0
\nWhen you click "Yes" a box will pop up and you will use that to select where you want your new TLE file to be saved. \
\nIf you do not understand click "No" and the program will be terminated.')

if result == True:
    pass
else:
    tkMessageBox.showinfo ("Program Aborted","You have chosen No, Please get the requisite understanding of file directory selection and run this program again. Thank You.")
    os._exit(0)


directory = tkFileDialog.askdirectory()

os.chdir(directory)


answer = tkSimpleDialog.askstring('File Name', '''Please Enter the name for your Celestrak TLE, if you leave it empty an automatically chosen name will be generated.\n
Do not enter in the file extension ".txt" or the program will break, simply enter in the name of the file you would prefer.''')

if answer != '':
    pass
else:
    answer = 'Celestrak_TLE_All_Active' + str(now_correct)

res = requests.get('https://celestrak.com/NORAD/elements/active.txt')

if res.status_code == requests.codes.ok:
    pass
else:
    tkMessageBox.showinfo("Program Aborted",'''Celestrak has returned an error on its website.  Please manually check https://celestrak.com/NORAD/elements/active.txt and see if it resolves.\
if it does, try running this program again.  If not please check your internet connection and anything else that might cause an issue reaching\
a webpage and run this program again.  Thank you''')
    os._exit(0)
예제 #55
0
def save_loop_file(p, regions, ask_info=True, outfilename=False):
    """
    Saves a Rosetta Loop file.  Also asks to discard residues or not.
    Migrate to use Regions.
    """
    if not p.total_residue():
        print "\n No pose loaded...\n"
        return

    if not regions:
        print "\n No loops to save...\n"
        return

    if ask_info:

        ask_cut_points = tkMessageBox.askyesno(message="Define Cutpoints?",
                                               default=tkMessageBox.NO)

        discard_loops = tkMessageBox.askyesno(
            message=
            "Discard Phi/Psi and build using ideal bond lengths and angles?")
    else:
        ask_cut_points = False
        discard_loops = True
    if not outfilename:
        outfilename = tkFileDialog.asksaveasfilename(
            initialdir=global_variables.current_directory,
            title="Output loop file to...")
    if not outfilename: return
    global_variables.current_directory = os.path.dirname(outfilename)

    FILE = open(outfilename, 'w')
    for region in regions:

        start = region.get_rosetta_start(p)
        end = region.get_rosetta_end(p)
        #This asks the user for each loop what he/she would like to do in terms of cutpoints.  Default= somewhere near the middle.
        if ask_cut_points:
            cutpoint_known = False

            while not cutpoint_known:
                cut = tkSimpleDialog.askstring(
                    title="cutpoint",
                    prompt="Cutpoint for Loop (#, default, 0 for random) " +
                    loop_string,
                    initialvalue="default")
                if cut == "default":
                    cut = (end - start) / 2
                    cut = start + cut
                    cutpoint_known = True
                elif cut == "0":
                    cut = 0
                    cutpoint_known = True
                else:
                    if ((int(cut) < start) | (int(cut) > end)):
                        tkMessageBox.showerror(message="Invalid CutPoint!")
                        cut = int(cut)
                        cutpoint_known = False
        else:
            cut = (end - start) / 2
            cut = start + cut
        FILE.write("LOOP" + " " + repr(start) + " " + repr(end) + " " +
                   repr(cut) + " 0 " + repr(int(discard_loops)) + "\n")

    FILE.close()
    print "\nLoop File written...\n"
    return
예제 #56
0
import Tkinter as tk
import tkSimpleDialog as simpledialog
import turtle
import time
import random
from ball import Ball, Virus, Food
#s = Sound()
#s.read('sound.wav')
#s.play()
#Then when ever you want to ask the user for input use this code
greeting = simpledialog.askstring("Game Mode",
                                  "Play Easy or Intermediate or Extreme?",
                                  parent=tk.Tk().withdraw())
if greeting == ("Extreme"):
    turtle.hideturtle()
    turtle.goto(-400, 0)
    turtle.write("Welcome to Extreme mode!",
                 move=False,
                 align="left",
                 font=("Arial", 50, "bold"))
    time.sleep(2)
    turtle.clear()
    turtle.write("50 points to win",
                 move=False,
                 align="left",
                 font=("Arial", 50, "bold"))
    time.sleep(2)
    turtle.clear()
    turtle.tracer(0)
    print("got this far")
    turtle.bgpic("/home/student/Desktop/Meetyl1201819/aga(1).gif")
예제 #57
0
import Tkinter as tk
import tkSimpleDialog as simpledialog
#Then when ever you want to ask the user for input use this code
greeting = simpledialog.askstring(
    "Input",
    "Hello, possible pirate! What's the password?",
    parent=tk.Tk().withdraw())
if greeting == ("Arrr!"):
    print("Go away, pirate.")
else:
    print("Greetings, hater of pirates!")

# 2
"""
A time traveler has suddenly appeared in your classroom!

Create a variable representing the traveler's
year of origin (e.g., year = 2000)
and greet our strange visitor with a different message
if he is from the distant past (before 1900),
the present era (1900-2020) or from the far future (beyond 2020).
"""
# import Tkinter as tk
# import tkSimpleDialog as simpledialog

# year = int(simpledialog.askstring("Input", "Greetings! What is your year of origin?", parent=tk.Tk().withdraw()))
# if year <= 1900:
#     print ("Woah, that's the past!")
# elif year > 1900 and year < 2020:
#     print ("That's totally the present!")
# else:
예제 #58
0
    def kickCommand(self, command):
        #This is the bad way to do wilds.  I should have put them in from the beginning.

        #This controls splits.
        #Fixes any wild cards.
        #self.textPlace = 0.0
        yourLetters = self.Letters.get()
        yourLetters = yourLetters.replace("#", ".")
        yourLetters = yourLetters.replace("-", ".")
        self.Letters.set(yourLetters)

        #self.textPlace = self.textPlace+1.0
        self.text.insert(
            self.textPlace, "\nReturning New Command: " + self.Letters.get() +
            " : " + self.LetterBuild.get() + "\n")
        if re.search(
                "\.",
                self.LetterBuild.get()) and command == "Find word using base":
            command = "Find word with split base (W...X)"
        if command == "Check if word exists":
            #print "Finding word in list..."
            #self.textPlace+1.0
            self.text.insert(self.textPlace, "\nFinding word in list...\n")
            word = tkSimpleDialog.askstring(
                title="Word",
                prompt=
                "Please enter word(s) you wish to look up (word,word,word)")
            self.text.insert(self.textPlace, "\n" + word)
            self.checkIfWordExists(word)
            return
        elif command == "Find word using letters":
            #Find a word using the combination of letters
            #self.textPlace = self.textPlace+1.0
            self.text.insert(self.textPlace,
                             "\nFinding word using letter combinations...\n")
            #Tosort = tkMessageBox.askquestion(title="Sort", message = "Sort by word length?", default='no')

            Tosort = "points"
            self.makeWords(self.Letters.get(), Tosort)
            return
        elif command == "Find word using base":
            #Find a word using these letters as a base
            #Ask if this starts the word.
            start = tkMessageBox.askyesno(message="Will this start the word?",
                                          default='no')
            self.maxLength = "0"
            self.maxConstraints = StringVar()
            self.maxConstraints.set("0x0")
            self.startWord = False
            if start == True:
                self.startWord = True
                self.maxLength = tkSimpleDialog.askinteger(
                    title="Length",
                    prompt="What is the maximum length of the word (0 = Wild)?",
                    initialvalue=self.maxLength)
            else:

                sides = tkSimpleDialog.askstring(
                    title="Constraints",
                    prompt=
                    "Please enter max Left and max Right of word (2x4) (0x0 = Wild)",
                    initialvalue=self.maxConstraints.get())
                self.maxConstraints.set(sides)
            #more = tkMessageBox.askyesno(message = "Do you wish to specify Special Tiles?", default = 'no')

            constraintDic = dict()
            constraintDic['length'] = self.maxLength
            constraintDic['start'] = self.startWord
            constraintDic['sides'] = self.maxConstraints.get()
            #if more==True:
            #Launch Special Tile dialog box.
            #pass
            #If yes, ask the maximum length of word required:
            buildSP = self.LetterBuild.get().split(",")
            if re.search(",", self.LetterBuild.get()):
                for build in buildSP:

                    self.makeWordBase(self.Letters.get(), build, constraintDic)
                    self.text.insert(1.0, "\nNext Build is: " + build + "\n")
            else:
                self.makeWordBase(self.Letters.get(), self.LetterBuild.get(),
                                  constraintDic)
            return
        elif command == "Find word with split base (W...X)":
            #self.textPlace = self.textPlace+1.0
            self.text.insert(self.textPlace, "\nUsing split base...")
            constraintDic = dict()
            constraintDic['start'] = False
            constraintDic['sides'] = "0x0"
            self.makeWordBase(self.Letters.get(), self.LetterBuild.get(),
                              constraintDic)
            return
예제 #59
-1
def funciontxt():
    #Pedir nombre de archivo, no puede ser nulo
    nombre = tkSimpleDialog.askstring('Archivo','Ingrese el nombre con el que desea guardar su archivo: ')
    while nombre == "":
        nombre = tkSimpleDialog.askstring('Archivo','Ingrese un nombre. No se pueden nombres vacios.')
    #concatena la extension de archivo
    nombre = nombre + '.txt'
    root = tk.Tk()
    root.withdraw()
    lista=[]
    #conversion de archivo a documento de texto
    while True:
        filename = tkFileDialog.askopenfilename()
        try:
            im = Image.open(filename)
            text=image_to_string(im)
            f=open(nombre,"w")
            f.write(text)
            f.close()
            tkMessageBox.showinfo('INFORMACION', 'Su archivo con el nombre "'+nombre+'". Se ha creado con exito')
            break
        except:
            tkMessageBox.showwarning("Open file","Ingrese un archivo de imagen")
            break
    x = 0
예제 #60
-7
파일: eai_Gui.py 프로젝트: twdb/txhis
 def runAdaptorDialog(self):
     try:
        #to be complete
        adtName = askstring('name of the adaptor', 'Please name of the adaptor you are creating')
        #adaptor name verification: if None, just return; if empty string, illegal input
        while adtName == "":
            showinfo("adaptor name error", "sorry,adaptor name cannot be empty....")
            adtName = askstring('name of the adaptor', 'Please name of the adaptor you are creating')
        newAdaptor = None
        if adtName == None:
            return
        elif adtName.find("TPWD") != -1:
            newAdaptor = TPWDadaptor.adaptor(adtName,self.src.get(),self.pipe.get(),self.sink.get())
        elif adtName.find("TCEQ") != -1:
            newAdaptor = TCEQadaptor.adaptor(adtName,self.src.get(),self.pipe.get(),self.sink.get())
        adaptorPool = adaptor_pool()
        while (adaptorPool.adaptors.has_key(adtName)):
            adtName = askstring('name exists', 'Please enter another name for this adaptor')
        # add adaptor to adaptor pool               
        adaptorPool.adaptors[adtName]= newAdaptor
        # schedule the adaptor running 
        adaptorPool.add_operation(adtName,newAdaptor.adpator_run, newAdaptor.adaptorSource.interval)
        self.adaptorList.listbox.insert('end',adtName)
        #adaptor.test(srcConf=self.src.get(),pipeConf=self.pipe.get(),sinkConf=self.sink.get())
     except AssertionError,IOError:
        showerror("Error!",'sorry, an IO error occurred...')