def upload(filepath, caption, user, password, context): print "Filepath is "+filepath insta = InstagramSession() print "InstagramSession started" if user == None and password == None: authfields = ["Username:"******"Password:"******"Authentication", "Please enter a username and password.", authfields) user = auth[0] USERNAME = auth[0] password = auth[1] PASSWORD = auth[1] if user == None: USERNAME = easygui.enterbox("Please enter a username:"******"Please enter a password:"******"Inside login" media_id = insta.upload_photo(filepath) print "media id" if media_id is not None: if caption == None: description = easygui.enterbox("Please enter a description of the image:") else: description = str(caption) insta.configure_photo(media_id, description) if context != "scheduled": main() else: pass
def ask_for_minmax_values(minx,maxx): msg = "Information for linear calculations" title = "Linear Calculations" fieldNames = ["Minimum time (m^1/4)","Maximum time (m^1/4)"] fieldValues = [] # we start with blanks for the values fieldValues = easygui.multenterbox(msg,title, fieldNames) # make sure that none of the fields was left blank while 1: # do forever, until we find acceptable values and break out if fieldValues == None: break errmsg = "" if fieldValues[0] > fieldValues[1]: errmsg = errmsg + ("The minimum value must be lower than the maximum value. ") # look for errors in the returned values for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found else: # show the box again, with the errmsg as the message errmsg = errmsg + " Invalid values. Please try again. " fieldValues = easygui.multenterbox(errmsg, title, fieldNames, fieldValues) return float(fieldValues[0]),float(fieldValues[1])
def ask_dimens(): msg = "Select dimensions" title = "Dimensions" field_names = ["Rows", "columns"] field_values = easygui.multenterbox(msg, title, field_names) ROWS, COLS = None, None valid_range = range(2, 121) # make sure that none of the fields were left blank while 1: if field_values is None: break errmsg = "" for i in range(len(field_names)): if field_values[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % field_names[i]) rows, cols = field_values if str(rows).isdigit() and str(cols).isdigit() and int( rows) in valid_range and int(cols) in valid_range: ROWS, COLS = int(rows), int(cols) else: errmsg = "Invalid values.\nMust be integers in range 2 - 120" if errmsg == "": break # no problems found field_values = easygui.multenterbox(errmsg, title, field_names, field_values) print(msg, "-", " - ".join(list(map(str, [ROWS, COLS])))) if field_values is None: rows, cols = 15, 15 ROWS, COLS = rows, cols return ROWS, COLS
def show_naivebayes_selection(): """ Shows a value input window for Naive Bayes and returns the user selection. """ msg = "Enter running values for Naive Bayes" title = "Naive Bayes run" fieldNames = ["x","dss","c","range","s","p","cross","stu","thn","pH"] fieldValues = [] # we start with blanks for the values fieldValues = eg.multenterbox(msg,title, fieldNames) # make sure that none of the fields was left blank while 1: # do forever, until we find acceptable values and break out if fieldValues == None: break errmsg = "" # look for errors in the returned values for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found else: # show the box again, with the errmsg as the message fieldValues = eg.multenterbox(errmsg, title, fieldNames, fieldValues) print ("Reply was:", fieldValues) pass
def measurement(): fieldNames = ["宽", "高"] size = width, height = 400, 600 fieldValues = gui.multenterbox(msg="请填写喵的尺寸", title="下载一只喵", fields=fieldNames) while True: esmg = "" try: int(fieldValues[0]) except: esmg += "宽度必须是整数" try: int(fieldValues[1]) except: esmg += "高都必须是整数" if esmg == "": break fieldValues = gui.multenterbox(esmg, title="下载一只喵", fields=fieldNames) root = gui.diropenbox(msg="请选择存放喵的文件夹", title="浏览文件夹", default="/Users/yizhichangyuan/Desktop") return fieldValues, root
def new_schedule(): filepath = get_file() timeenters = ["Days", "Hours", "Minutes", "Seconds"] stime = easygui.multenterbox("Scheduler", "Please specify a time", timeenters) days = stime[0] hours = stime[1] minutes= stime[2] seconds = stime[3] description = easygui.enterbox("Please enter a description of the image") days = int(days)*24 hours = int(days)+int(hours) minutes = hours*60+int(minutes) seconds = minutes*60+int(seconds) isauth = os.path.isfile("auth.txt") if isauth == True: authfile = open("auth.txt").read().split('\n') print authfile username = authfile[0] password = authfile[1] else: accountfields = ["Username:"******"Password:"******"Authentication", "Please enter the required information.", accountfields) username = userpass[0] password = userpass[1] p = threading.Thread(target=wait, args=(seconds, filepath, description, username, password)) processes.append(p) p.start() # processfile.close() main()
def reminder_gui(): #*****************************************************************************# msg = "Enter Data for Reminder" title = "SmartClock v1.0" fieldNames = ["Hour","Minute","Second","Day (in DD)", "Month (in MM)", "Year ( in YYYY)", "Remind me to"] fieldValues = [] # we start with blanks for the values fieldValues = easygui.multenterbox(msg,title, fieldNames) while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = easygui.multenterbox(errmsg, title, fieldNames, fieldValues) st = '' if fieldValues == None: return 0 for value in fieldValues: st += value + ":" f = open ("../../data/reminder.txt", "w") f.write (st+'\n') f.close return 1
def ask_for_weight_values(): msg = "Enter Weight Data" title = "Weights" fieldNames = ["Initial Weight (g)","Std Dev","105 Degrees C Weight (g)","Std Dev","550 Degrees C Weight","Std Dev"] fieldValues = [] # we start with blanks for the values fieldValues = easygui.multenterbox(msg,title, fieldNames) # make sure that none of the fields was left blank while 1: # do forever, until we find acceptable values and break out if fieldValues is None: break errmsg = "" if float(fieldValues[0]) < float(fieldValues[2]): errmsg += ("The initial weight must be higher than the 105 degree weight ") # look for errors in the returned values if float(fieldValues[2]) < float(fieldValues[4]): errmsg += ("The 105 degree weight must be higher than the 550 degree weight ") # look for errors in the returned values for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg +=('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found else: # show the box again, with the errmsg as the message errmsg += " Invalid values. Please try again. " fieldValues = easygui.multenterbox(errmsg, title, fieldNames, fieldValues) return float(fieldValues[0]),float(fieldValues[1]),float(fieldValues[2]),float(fieldValues[3]),float(fieldValues[4]),float(fieldValues[5])
def ask_for_RHCoefficient(humidity): msg = "Enter Humidity Information" title = "Humidity" fieldNames = ["RH Setting (%RH)","Coefficient for Weight Correlation to RH"] #fieldValues = [] # we start with blanks for the values fieldValues=zeros(alen(2)) fieldValues[0]=humidity fieldValues = easygui.multenterbox(msg,title, fieldNames) # make sure that none of the fields was left blank while 1: # do forever, until we find acceptable values and break out if fieldValues is None: break errmsg = "" if fieldValues[0] <1 or fieldValues[1] < 1: errmsg += ("You must enter a postive number.") # look for errors in the returned values for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg +=('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found else: # show the box again, with the errmsg as the message errmsg += " Invalid values. Please try again. " fieldValues = easygui.multenterbox(errmsg, title, fieldNames, fieldValues) return float(fieldValues[0]),float(fieldValues[1])
def cadastrar_projeto(): # SEMELHANTE A LINHA ABAIXO. # pesquisadores = [] # for x in MPesquisador.select().order_by(MPesquisador.nome): # pesquisadores.append(x.nome) pesquisadores = [x.nome for x in MPesquisador.select().order_by(MPesquisador.nome)] msg = "Selecione o(a) Coordenador(a) do Projeto." title = "Cadastro de Projeto" coordenador = choicebox(msg, title, pesquisadores) if coordenador == None: return msg = "Entre com os dados do Projeto: " fieldNames = ["Titulo: ", "Resumo: ", "Palavras-chave: ", "Ano de Início: ", "Ano de Término: "] fieldValues = [] fieldValues = multenterbox(msg, title, fieldNames) while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" e um campo requisido.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues) if fieldValues == None: return else: # Tira acentos fieldValues = array_to_ascii(fieldValues) # Converte para Maiúsculo o Titulo do Projeto fieldValues[0] = fieldValues[0].upper() projeto = MProjeto.create( titulo=fieldValues[0], coordenador=coordenador, resumo=fieldValues[1], keywords=fieldValues[2], inicio=fieldValues[3], final=fieldValues[4], ) projeto.save() msgbox( msg="Projeto: " + fieldValues[0] + " cadastrado com sucesso!", title=title, ok_button="Continuar", image=None, root=None, ) return
def teacherSchedule(): # One row for each event in the schedule plus a title row count = 1 if (guiInput == 1): addEvent = True while (addEvent is True): msg = "Please enter in information about event " + str( count) + " in the teacher's schedule" title = "Event " + str(count) fieldNames = ["Start Time", "End Time", "Event Name"] fieldValues = [] # we start with blanks for the values fieldValues = easygui.multenterbox(msg, title, fieldNames) # make sure that none of the fields was left blank while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = easygui.multenterbox(errmsg, title, fieldNames, fieldValues) print("Reply was:" + fieldValues) startTimes.append(fieldValues[0]) endTimes.append(fieldValues[1]) eventTitles.append(fieldValues[2]) count += 1 addEvent = easygui.ynbox( 'Would you like to add another event after ' + eventTitles[count - 2] + '?', 'Add Another Event', ('Yes', 'No')) table = document.add_table(rows=1, cols=1) cell = table.cell(0, 0) cell.text = "Teacher's Schedule" table.style = 'TableGrid' table.alignment = WD_TABLE_ALIGNMENT.CENTER #Left column time , right column event table = document.add_table(rows=count - 1, cols=2) x = 0 #Fill out variable length table while (x < count - 1): leftcell = table.cell(x, 0) rightcell = table.cell(x, 1) leftcell.text = startTimes[x] + " - " + endTimes[x] rightcell.text = eventTitles[x] x += 1 table.style = 'TableGrid' table.alignment = WD_TABLE_ALIGNMENT.CENTER #Add whitespace document.add_paragraph(" ")
def add_stu(): #添加学生信息的函数 global students_info #用于储存学生的基本信息 储存形式为{name_1:obj1, name_2:obj2,........} list_name = [] #用于储存学生姓名(为字典提供键名 name) list_stuobj = [] #用于储存学生对象(为字典提供键值 obj) reply_int = g.integerbox(msg='请输入本次录入学生的个数(单次最多99个)', title='学生管理系统 v1.1 [管理员]', default=1, lowerbound=0, upperbound=99, image='熊本熊.gif', root=None) for i in range(reply_int): msg = "请填写一下信息(其中带*号的项为必填项)" #此处要实现学生信息输入的必选项,其中带*号的为必须输入,否则出现提示【*某一项】为必填项,并要求重新输入,并且保留上次的输入内容 title = "账号中心" fieldNames = [ "*真实姓名", "*性别", "*年龄", "*学号", "*学院", "*专业", "*手机号码", "*QQ", "*专业课成绩", "*高数成绩", "*物理成绩", "*英语成绩" ] input_value = [] #用于暂存一个学生基本信息 input_value = g.multenterbox(msg, title, fieldNames) #print(fieldValues) while True: if input_value == None: break errmsg = "" for i in range(len(fieldNames)): option = fieldNames[i].strip() if input_value[i].strip() == "" and option[0] == "*": errmsg += ("【%s】为必填项 " % fieldNames[i]) if errmsg == "": break input_value = g.multenterbox(errmsg, title, fieldNames, input_value) i = Student() if input_value[0] not in students_info: list_name.append(input_value[0]) #将学生姓名添加到list_name else: g.msgbox(title='警告!', msg='该学生信息已经存在!') add_stu() #完成对相应学生对象的实例化 i.set_student_info(input_value[0], input_value[1], input_value[2], input_value[3], input_value[4], input_value[5], input_value[6], input_value[7]) i.set_student_score(input_value[8], input_value[9], input_value[10], input_value[11]) list_stuobj.append(i) #将产生学生对象添加到list_stuobj #students_info_1 = {} #students_info_1 = dict(zip(list_name,list_stuobj)) flag = 0 while flag < len(list_name): students_info.setdefault( list_name[flag], list_stuobj[flag]) #将学生信息以学生名字做为键名,以生成的学生对象为键值,一个一个地打包成字典 flag += 1 g.msgbox(title='提示!', msg='本次学生基本信息录入完成', ok_button='OK') #student_info_write() back_main_windows()
def main(): # Check if the current version of chromedriver exists # and if it doesn't exist, download it automatically, # then add chromedriver to path try: chromedriver_autoinstaller.install() except FileNotFoundError: print( "ChromeDriver Autoinstaller failed, please install the correct 'chromedriver' manually." ) nltk.download('stopwords') again = True while again: if easygui.ynbox("Would you like to clean program data?", 'Title', ('Yes', 'No')): shutil.rmtree("./report", ignore_errors=True) shutil.rmtree("./most_used", ignore_errors=True) shutil.rmtree("./bar_charts", ignore_errors=True) if os.path.isfile("scraped.json"): os.remove("scraped.json") if os.path.isfile("found_profile_links.json"): os.remove("found_profile_links.json") create_folder("./report/") create_folder("./most_used/") create_folder("./bar_charts/") msg = "Enter your subject profile name" title = "Social Media Scraper" fieldNames = ["Subject Profile Name"] fieldValues = easygui.multenterbox(msg, title, fieldNames) if fieldValues is None: exit(0) # make sure that none of the fields were left blank while 1: errmsg = "" for i, name in enumerate(fieldNames): if fieldValues[i].strip() == "": errmsg += "{} is a required field.\n\n".format(name) if errmsg == "": break # no problems found fieldValues = easygui.multenterbox(errmsg, title, fieldNames, fieldValues) if fieldValues is None: break print("Profile name is: {}".format(fieldValues)) profile_name = fieldValues[0] find_profiles(profile_name) scrape() natural_language() again = easygui.ynbox("Would you like to try again?", 'Title', ('Yes', 'No'))
def bucleConfirmacion(fValues, valoresPick): msg = "Ingresa los datos solicitados" title = "Control de correos" fieldNames = ["CV","Destino","Tarifa",'Linea','Numero de referencia','Correo','CC (no es obligatorio)','CC2 (no es obligatorio)','CC3 (no es obligatorio)'] fieldValues = easygui.multenterbox(msg, title, fieldNames,fValues) cont=0 ack=0 errmsgF='' print(fieldValues) while 1: while cont<=5: if fieldValues[cont].strip() == "": errmsgF += "{} is a required field.\n\n".format(fieldNamees[cont]) ack=1 cont+=1 if ack==1: while 1: if errmsgF=='': break fieldValues = easygui.multenterbox(errmsgF, title, fieldNames, fieldValues) errmsgF='' for b in range(0,6): print(fieldValues[b]) print(fieldNamees[b]) if fieldValues[b].strip() == "": print(fieldValues[b]) errmsgF+="{} is a required field.\n\n".format(fieldNamees[b]) print(errmsgF) print(fieldValues) parseD=fieldValues[1] parseL=fieldValues[3] for i in parseD: arrDest.append(i) for i in parseL: arrLin.append(i) while (arrDest[0].upper()!='M'or arrDest.upper()[1]!='X'): for i in range(len(arrDest)): arrDest.pop(0) errmsgD= "{}: Usa formato MX/#.\n\n".format(fieldNames[1]) fieldValues = easygui.multenterbox(errmsgD, title, fieldNames, fieldValues) parseDNew=fieldValues[1] for i in parseDNew: arrDest.append(i) while (arrLin[0].upper()!='M'or arrLin[1].upper()!='X'): for i in range(len(arrLin)): arrLin.pop(0) errmsgL= "{}: Usa formato MX/#.\n\n".format(fieldNames[3]) fieldValues = easygui.multenterbox(errmsgL, title, fieldNames, fieldValues) parseLNew=fieldValues[3] for i in parseLNew: arrLin.append(i) break print("Reply was:{}".format(fieldValues)) confirm=confirmacion(fieldValues, valoresPick) print(confirm,'Bucle') return confirm
def guiCallback(option): folderPath = sys.argv[1] + '\\' print folderPath if (option._text == 'Replace String'): values = easygui.multenterbox( "Enter replace data:", "Replace", ["Replace What? : ", "Replace With ? : "]) if values != None: whatStr = values[0] withStr = values[1] for fn in os.listdir(folderPath): os.rename(folderPath + fn, folderPath + fn.replace(whatStr, withStr)) elif (option._text == 'Add String to End'): values = easygui.multenterbox("Enter string data:", "Add to End", ["String to be added : "]) if values != None: whatStr = values[0] for fn in os.listdir(folderPath): ext = fn.split('.')[1] name = fn.split('.')[0] os.rename(folderPath + fn, folderPath + name + whatStr + "." + ext) elif (option._text == 'Add String to Start'): values = easygui.multenterbox("Enter string data:", "Add to Start", ["String to be added : "]) if values != None: whatStr = values[0] for fn in os.listdir(folderPath): ext = fn.split('.')[1] name = fn.split('.')[0] os.rename(folderPath + fn, folderPath + whatStr + name + "." + ext) elif (option._text == 'Give sequence number to files'): Counter = 0 z = list(os.listdir(folderPath)) list.sort(z) for fn in z: ext = fn.split('.')[1] name = fn.split('.')[0] Counter += 1 os.rename(folderPath + fn, folderPath + str(Counter) + name + "." + ext) elif (option._text == 'Change extension of files'): values = easygui.multenterbox("Enter extension:", "To which", ["Enter : "]) if values != None: whatStr = values[0] for fn in os.listdir(folderPath): ext = fn.split('.')[1] name = fn.split('.')[0] os.rename(folderPath + fn, folderPath + name + "." + whatStr) elif (option._text == 'About :)'): easygui.msgbox("Programmed By Ammar Rajab :)", "About")
def Run(): account = g.multenterbox(msg = "【*用户名】为必填选项\n【*真实姓名】为必填选项\n【*手机号码】为必填选项\n【*E-mail】为必填选项",title = "账号中心",fields = ("*用户名","*真实姓名","固定电话","*手机号码","QQ号码","*Email")) P = 1 while P : if check(account) is True: msg() account = g.multenterbox(msg = "【*用户名】为必填选项\n【*真实姓名】为必填选项\n【*手机号码】为必填选项\n【*E-mail】为必填选项",title = "账号中心",fields = ("*用户名","*真实姓名","固定电话","*手机号码","QQ号码","*Email")) else: P = 0 else: return account
def addHead(): # add date heading if (guiInput == 0): date = jsonInfo['planDate'] + " PLANS" else: easygui.msgbox( "Welcome to SubShell - A guided process that generates a template for you to edit, and your substitute teacher to follow. Crafted with care by Adam Bloom, Chris Bonilla, Hannah Cline, and Jonathan Davis.", "Welcome to SubShell") msg = "What day will the substitute use the plans?" title = "Date" fieldNames = [ "Day of the Week", "Month (numeral)", "Day (numeral)", "Year (numeral)" ] fieldValues = [] # we start with blanks for the values fieldValues = easygui.multenterbox(msg, title, fieldNames) # make sure that none of the fields was left blank while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = easygui.multenterbox(errmsg, title, fieldNames, fieldValues) print("Reply was: " + fieldValues) date = fieldValues[0] + ", " + fieldValues[1] + "/" + fieldValues[ 2] + "/" + fieldValues[3] heading = document.add_heading(date, 0) heading = WD_ALIGN_PARAGRAPH.CENTER if (guiInput == 0): #sub specific info , specials + customHeaderMessage if (jsonInfo['specialExists'] == "true"): subSpecific = "Our students have specials today from " + jsonInfo[ "specialStartTime"] + " to " + jsonInfo[ "specialEndTime"] + ". " + jsonInfo["customHeaderMessage"] else: subSpecific = jsonInfo["customHeaderMessage"] else: msg = "What info would you like to appear at the top of the front page, below the title? For example, During recess and lunch, please check with the main office to determine if you are needed to cover indoor or outdoor recess or to support in the cafeteria." subSpecific = easygui.enterbox(msg, "Header Informaiton") # todo save this data table = document.add_table(rows=1, cols=1) cell = table.cell(0, 0) cell.text = subSpecific table.style = 'TableGrid' table.alignment = WD_TABLE_ALIGNMENT.CENTER #Add whitespace document.add_paragraph(" ")
def multenterbox(msg,title,fieldValues,fieldNames): fieldValues = easygui.multenterbox(msg, title, fieldNames,fieldValues) while True: if fieldValues is None: break errs = list() for n, v in zip(fieldNames, fieldValues): if v.strip() == "":errs.append('"{}" is a required field.'.format(n)) if not len(errs): break fieldValues = easygui.multenterbox("\n".join(errs), title, fieldNames, fieldValues) return dict(zip(fieldNames,fieldValues))
def popUpImage(img): #image = "/home/pranjal/Documents/PythonProjects/PyTorch-YOLOv3/data/samples/dog.jpg" image = img msg = "Do you want to enter bibId?" choices = ["Yes", "No"] boolean = False fieldValues = [] # we start with blanks for the values while (not boolean): reply = buttonbox(msg, image=image, choices=choices) print(reply) if reply == "Yes": msg = "Enter BibId" title = "Runner bibId" fieldNames = ["BibId"] boolean = True fieldValues = multenterbox(msg, title, fieldNames) if fieldValues == None: print('Entered value', 0) else: print('Entered value', fieldValues[0]) # make sure that none of the fields was left blank while 1: if fieldValues == None: fieldValues = [] fieldValues.append(0) boolean = False break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues) #print('Entered value',fieldValues) # if(fieldValues is None): # boolean=False # else: boolean = True print("Entered BibId:", fieldValues[0]) else: fieldValues.append(0) print("Entered BibId:", fieldValues[0]) boolean = True return fieldValues[0]
def config_gui(): # 配置页面 # config1 = g.read_or_create_settings("./settings.txt") #貌似没起作用,创建文件的是下面的代码 settingFile = "settings.txt" config_app = Settings(settingFile) usr_id = "tjx" usr_structor = "peidao" APP_IP_config = "192.168.19.1" config_app.userId = usr_id config_app.usr_structor = usr_structor config_app.App_IP_config = APP_IP_config config_app.store() print("\nInitial settings") print(config_app) time.sleep(20) #修改配置内容GUI msg = "请填写要修改的配置" title = "参数配置" fieldNames = ["*用户名", "*机构名", "IP", "Port"] fieldValues = [] fieldValues = g.multenterbox(msg, title, fieldNames) while True: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): option = fieldNames[i].strip() if fieldValues[i].strip() == "" and option[0] == "*": errmsg += ("【%s】为必填项 " % fieldNames[i]) if errmsg == "": break fieldValues = g.multenterbox(errmsg, title, fieldNames, fieldValues) print("您填写的资料如下:%s" % str(fieldValues)) #修改配置文件 usr_id = fieldValues[0] usr_structor = fieldValues[1] APP_IP_config = fieldValues[2] APP_Port_config = fieldValues[3] config_app.userId = usr_id config_app.usr_structor = usr_structor if (APP_IP_config != ''): #空字符串的表示方法,和空值(None)是不一样的。 config_app.App_IP_config = APP_IP_config if (APP_Port_config != ''): config_app.App_Port_config = APP_Port_config config_app.store() print("\nInitial settings") print(config_app)
def gui(): easygui.msgbox('Find a place to hold your meeting. ~Team # US-6462', 'International Meeting Management Corporation') msg = "Enter the month of your meeting and the number of participants" title = "International Meeting Management Corporation" fieldNames = ["Time","Participants"] fieldValues = [] # we start with blanks for the values fieldValues = easygui.multenterbox(msg,title,fieldNames) # make sure that none of the fields was left blank while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = easygui.multenterbox(errmsg, title, fieldNames, fieldValues) time = parser.parse(fieldValues[0]) msg = "Enter the home city of each of your participants" num_participants = int(fieldValues[1]) + 1 fieldNames = ["Participant " + str(x) + " City" for x in range(1, num_participants)] fieldValues = [] fieldValues = easygui.multenterbox(msg,title,fieldNames) while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = easygui.multenterbox(errmsg, title, fieldNames, fieldValues) meeting = {} participants = fieldValues msg = "Enter the salary or estimated salary of each of your participants" fieldNames = ["Participant " + str(x) + " Salary" for x in range(1, num_participants)] fieldValues = easygui.multenterbox(msg,title,fieldNames) for participant in range(0, len(participants)): geo = gmaps.geocode(participants[participant]) location_table[participants[participant]] = {'lat':geo[0]["geometry"]["location"]["lat"],'lng':geo[0]["geometry"]["location"]["lng"]} meeting[participants[participant]] = int(fieldValues[participant]) bml = best_meeting_location(time, meeting) msg = "Here are the best cities for your meeting, sorted by least potential loss:" choices = [str(l[0]) + " | Lost Productivity: " + str(l[1][0]) +" | Cost: " + str(l[1][1]) +" | Total Loss: " + str(l[1][2]) for l in bml] choice = easygui.choicebox(msg, title, choices) return choice
def stop_thread(): try: global stop_th, value_command, list_of_started_threads while True: msg = "Manage threads" title = "What do you want to do?" fieldNames = ["Command", "Number of thread"] fieldValues = easygui.multenterbox(msg, title, fieldNames) if fieldValues is None: sys.exit(0) # make sure that none of the fields were left blank while 1: errmsg = "" for i, name in enumerate(fieldNames): if fieldValues[i].strip() == "": errmsg += "{} is a required field.\n\n".format(name) tmp_val = fieldValues[0] if tmp_val.upper() != "START" and tmp_val.upper() != "STOP": errmsg += "Please use 'START' or 'STOP'" try: if not isinstance(int(fieldValues[1]), int): errmsg += "Please use integers to start threads" except: errmsg += "Please use integers to start threads" try: if int(fieldValues[1]) > 10: errmsg += "Number of threads is 10. Please choose smaller digit" except: "Please use integers to start threads" if errmsg == "": break # no problems found fieldValues = easygui.multenterbox(errmsg, title, fieldNames, fieldValues) if fieldValues is None: break value_command = fieldValues[0].upper() stop_th = int(fieldValues[1]) if value_command == "START": if stop_th - 1 not in list_of_started_threads: list_of_threads[stop_th - 1].start() list_of_started_threads.append(stop_th - 1) elif stop_th - 1 in list_of_started_threads: print("release {}".format(stop_th)) tmp_lock = lock_list[stop_th - 1] tmp_lock.set() except: print("Error during getting data") sys.exit(1)
def main(): msg = "请填写喵的尺寸" title = "下载一只猫" fieldName = ["宽:","高:"] fieldValues = [] size = width, height = 200 , 300 # easygui.multenterbox 显示具有多个数据输入字段的屏幕 # 如果值比名称更少,则值的列表将填充空字符串,直到值的数量与名称的数量相同。 # 如果有比名称更多的值,值的列表将被截断,以便有与名称一样多的值。 # 返回字段值的列表,如果用户取消操作,则返回None。 fieldValues = g.multenterbox(msg, title, fieldName, size) while 1: if fieldValues == None: break errmsg = "" try: # strip() 方法用于移除字符串头尾指定的字符(默认为空格) width = int(fieldValues[0].strip()) except: errmsg = "宽度必须为整数!" try: height = int(fieldValues[1].strip()) except: errmsg = "高度必须为整数!" if errmsg == "": break fieldValues = g.multenterbox(errmsg, title, fieldName, fieldValues) url = "http://placekitten.com/g/%d/%d" % (width, height) response = urllib.request.urlopen(url) cat_img = response.read() # easygui.diropenbox 用于获取目录名的对话框 filepath = g.diropenbox("请选择存放喵的文件夹") if filepath: filename = "%s/cat_%d_%d.jpg" % (filepath, width, height) else: filename = "cat_%d_%d.jpg" % (width, height) # w 只写入 wb 以二进制打开只写入 with open(filename, "wb") as f: f.write(cat_img)
def guiSearch(): """ Interface for performing a search """ msg = "Select the type of search to perform" title = "Search Type Selection" choices = [ptr, dpr, aa] choice = eg.choicebox(msg, title, choices) if choice == ptr: msg = "Please enter the patient healthcare number or patient name." title = "Patient Test Record Search" fieldNames = ["Patient Healthcare #", "Patient Name"] fieldValues = [] # Should later be changed to enterbox if only needs one entry fieldValues = eg.multenterbox(msg, title, fieldNames) if fieldValues == None: eg.msgbox('Operation cancelled') return msg = performSearch(ptr, pnum = fieldValues[0], pname = fieldValues[1]) title = "Result" eg.msgbox(msg, title) elif choice == dpr: msg = "Please enter the employee number or employee name and date range for your search." title = "Doctor Prescription Record Search" fieldNames = ["Doctor Employee #", "Doctor Name", "Start Date (dd/mm/yyyy)", "End Date (dd/mm/yyyy)"] fieldValues = [] fieldValues = eg.multenterbox(msg, title, fieldNames) if fieldValues == None: eg.msgbox('Operation cancelled') return #enum, ename, startdate, enddate = fieldValues msg = performSearch(dpr, enum = fieldValues[0], ename = fieldValues[1], sdate = fieldValues[2], edate = fieldValues[3]) title = "Result" eg.msgbox(msg, title) elif choice == aa: msg = "Please enter the name of test type you would like to search for" title = "Alarming Age Search" # Should later be changed to enterbox if only needs one entry fieldNames = ["Test Name"] fieldValues = [] fieldValues = eg.multenterbox(msg, title, fieldNames) if fieldValues == None: eg.msgbox('Operation cancelled') return msg = performSearch(aa, ttype = fieldValues[0]) title = "Result" eg.msgbox(msg, title)
def danche(): while True: retval = g.buttonbox(msg="您想要对单车做什么?", title="管理单车", choices=("增加单车", "删除单车", "查询单车")) if retval == None: break if retval == "增加单车": fieldNames = ["ID", "type", "state", "cost", "district", "street", "longitude", "latitude"] fieldValues = [] fieldValues = g.multenterbox("填写单车信息", "增加单车", fieldNames) if fieldValues == None: continue if net.sent("jiache " + " ".join(fieldValues)) == "ok": g.msgbox("增加成功", title="增加单车") else: g.msgbox("单车已经存在", title="增加单车") elif retval == "删除单车": fieldNames = ["ID"] fieldValues = [] fieldValues = g.multenterbox("填写单车信息", "删除单车", fieldNames) if fieldValues == None: continue l = net.sent("shanche " + " ".join(fieldValues)) if l == "ok": g.msgbox("删除成功", title="删除单车") elif l == "not_exist": g.msgbox("单车不存在", title="删除单车") elif retval == "查询单车": fieldNames = ["ID"] fieldValues = [] fieldValues = g.multenterbox("填写单车信息", "查询单车", fieldNames) if fieldValues == None: continue l = net.sent("chache " + " ".join(fieldValues)).split() if l[0] == "ok": s = "单车编号: " + fieldValues[0] + "\n" s += "单车类型: " + l[1] + "\n" s += "单车状态: " + l[2] + "\n" s += "单车单价: " + l[3] + "\n" s += "单车区域: " + l[4] + "\n" s += "单车街道: " + l[5] + "\n" s += "经度: " + l[6] + "\n" s += "维度: " + l[7] + "\n" g.textbox(msg="单车信息如下:", title="单车信息", text=s) elif l[0] == "not_exist": g.msgbox("单车不存在", title="删除单车") return
def msgIntro(): """ Genere les messages d'introduction """ title = "Stable Roommates Problem" # Premier Message start_msg = "This is a demo of the Irving Algorithm for the Stable roommates problem.\n" start_msg += "It was written by: Vincent LIU - MAIN - Polytech Sorbonne 2017/18.\n\n" start_msg += "Code is written in Python with the easygui library." msgbox(start_msg, title, "Start") # Deuxieme Message min_val = 4 max_val = 18 n = integerbox( "Please enter the number of participants [{} .. {}]".format( min_val, max_val), title, 6, min_val, max_val) # Troisieme Message fieldNames = ["Name {}".format(i) for i in range(1, n + 1)] playerNames = multenterbox("Please enter their names:", title, fieldNames) # make sure that none of the fields was left blank and not duplicate while 1: if playerNames == None: break errmsg1 = "" errmsg2 = "" for i in range(len(fieldNames)): if playerNames[i].strip() == "": errmsg1 = errmsg1 + ('"%s" is a required field.\n\n' % fieldNames[i]) else: if playerNames.count(playerNames[i]) > 1 and errmsg2 == "": errmsg2 = errmsg2 + ("Pas de doublon.\n\n") errmsg = errmsg1 + errmsg2 if errmsg == "": break playerNames = multenterbox(errmsg, title, fieldNames, playerNames) return playerNames
def send(finalSend, toSend): msg = "Enter your text to send" title = "Sending text to the destinations" fieldNames = ["->"] fieldValues = [] # we start with blanks for the values fieldValues = easygui.multenterbox(msg, title, fieldNames) finalSend = checkStatusToSend(finalSend) handle(flagToAvoidRessetingTextBoxes) while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) port = 1337 finalSend = list(dict.fromkeys(finalSend)) for x in finalSend: print("JEST" + x) try: addr = (x, port) UDPSock = socket(AF_INET, SOCK_DGRAM) data = fieldValues[0] data = data.encode('ascii') UDPSock.sendto(data, addr) UDPSock.close() except: messagebox.showerror("Message not send", " {} is invalid or unreachable".format(x)) continue finalSend.clear() tosend.clear() listBoxScrollT.clear() variables.clear() listBoxScrollTS.clear() handle(flagToAvoidRessetingTextBoxes) # os._exit(0) fieldValues = easygui.multenterbox(errmsg, title, fieldNames, fieldValues)
def beam_prs(): try: import easygui msg = "Cantilever beam (Timoshenko Sln)" title = "Enter the problem parameters" fieldNames = [ "Length", "Height", "Inertia", "Poissons ratio", "Young modulus", "Load" ] fieldValues = [] # we start with blanks for the values fieldValues = easygui.multenterbox(msg, title, fieldNames) L = float(fieldValues[0]) h = float(fieldValues[1]) I = float(fieldValues[2]) nu = float(fieldValues[3]) E = float(fieldValues[4]) P = float(fieldValues[5]) except: a1 = raw_input("Length") b1 = raw_input("Height") c1 = raw_input("Inertia") d1 = raw_input("Poissons ratio") e1 = raw_input("Youngs modulus") f1 = raw_input("Load") L = float(a1) h = float(b1) I = float(c1) nu = float(d1) E = float(e1) P = float(f1) return L, h, I, nu, E, P
def ellipse(): try: import easygui msg = "Ingrese los parametros del problema" title = "Elipse" fieldNames = [ "a", "b", "Tamaño del elemento", "Tipo de elemento", "Orden", "Contornos" ] fieldValues = [] ## se empieza con espacios blancos fieldValues = easygui.multenterbox(msg, title, fieldNames) a = float(fieldValues[0]) b = float(fieldValues[1]) c = float(fieldValues[2]) ietype = int(fieldValues[3]) order = int(fieldValues[4]) contornos = int(fieldValues[5]) except: a1 = raw_input("a") b1 = raw_input("b") d1 = raw_input("Tamaño del elemento") c1 = raw_input("Tipo de elemento") e1 = raw_input("Orden") f1 = raw_input("Contornos") a = float(a1) b = float(b1) c = float(d1) ietype = int(c1) order = int(e1) order = int(f1) return a, b, c, ietype, order, contornos
def main(): msg = "Enter the game settings" title = "AI - Flappy Bird Settings:" fieldNames = ["training runs", "exploration(epsilon)", "learning rate(alpha)","discount factor(gamma)", "pipe vertical gap", "FPS", "Agent", "Grid resolution", "dataType"] fieldValues = [10000, 0, 0.7, 0.99, 130, 30, True, 4, 1] # we start with blanks for the values fieldValues = easygui.multenterbox(msg, title, fieldNames, fieldValues) isAgent = fieldValues[ValueIndeces['agent']] pipeGapY = int(fieldValues[ValueIndeces['pipeGapY']]) fps = int(fieldValues[ValueIndeces['fps']]) if isAgent == 'False': flapGame = FlappyGame.FlappyGame(pipeGapY, fps=fps) else: alpha = float(fieldValues[ValueIndeces['alpha']]) gamma = float(fieldValues[ValueIndeces['gamma']]) epsilon = float(fieldValues[ValueIndeces['epsilon']]) trainingRuns = int(fieldValues[ValueIndeces['trainRuns']]) gridRes = int(fieldValues[ValueIndeces['gridRes']]) dataType = int(fieldValues[ValueIndeces['dataType']]) agent = Agent.QLearningAgent(alpha=alpha, numTraining=trainingRuns, gamma=gamma, epsilon=epsilon) if dataType is 1: flapGame = AgentFlappyGame.AgentFlappy(pipeGapY, agent, gridRes=gridRes, noGUI=True, trainingTime=600) elif dataType is 2: flapGame = AgentFlappyGame.AgentFlappyMidPipe(pipeGapY, agent, gridRes=gridRes, noGUI=True, trainingTime=600) elif dataType is 3: flapGame = AgentFlappyGame.AgentFlappyHorizontal(pipeGapY, agent, gridRes=gridRes, noGUI=True, trainingTime=600) elif dataType is 4: flapGame = AgentFlappyGame.AgentFlappyAll(pipeGapY, agent, gridRes=gridRes, noGUI=True, trainingTime=600) flapGame.startGame()
def gui(): msg = "" title = "ETP" fieldNames = ["Path", "Worksheet(s)", "Print Area(s)", "Paper Size(s)"] fieldValues = [".txt or .xlsx", "1,3-5,6,7,11-9", "A1:G57,B4:Z57,A2:G56,A2:G56,A5:J72", "1,2,1,1,2"] fieldValues = easygui.multenterbox(msg, title, fieldNames, fieldValues) return fieldValues
def main(): argv = sys.argv[1:] if(len(argv) == 0): msg = '''Entre com o codigo de rastreio e o intervalo de tempo de monitoramento, em minutos''' title = 'Sistema de Monitoramento' fieldNames = ['Codigo de Rastreio', 'Intervalo de Tempo'] fieldValues = eg.multenterbox(msg, title, fieldNames) obj = adentregas(fieldValues[0], float(fieldValues[1])) obj.monitorEntregas() else: uso = 'adentregas.py -r <codigo de rastreio> -t <tempo verificacao>' try: opts, args = getopt.getopt(argv, "hr:t:", ["rcode=", "dtime="]) except getopt.GetoptError: print uso sys.exit(2) for opt, arg in opts: if opt == '-h': print uso sys.exit() elif opt in ("-r", "--rcode"): codigorastreio = arg elif opt in ("-t", "--dtime"): deltat = arg if(len(opts) == 0): print uso sys.exit() obj = adentregas(codigorastreio, float(deltat)) obj.monitorEntregas()
def translate(word): word = thwart(word) check = c.execute("SELECT * from entries WHERE word = '{0}'".format(word)) if int(check) > 0: data = c.fetchall() out = '\n' for datas in data: name = datas[0] typ = datas[1] meaning = datas[2] meaning = meaning.replace('.', '.\n') out = out + '\n' + 'type - ' + typ + '\n' + 'meaning - ' + meaning + '\n' out = 'name - ' + name + out easygui.msgbox(out, title="result") else: sugg = matching(word) sugg.append('NOTA') choice = easygui.buttonbox('Is your words are one of these?', 'Favorite Flavor', sugg) if choice == 'NOTA': check = easygui.ynbox( 'Could not find the word, do you want to add?', 'Title', ('Yes', 'No')) if check: fieldValues = list( easygui.multenterbox(msg='word to translate.', title='Enter', fields=(fieldNames))) typ = thwart(fieldValues[0]) meaning = thwart(fieldValues[1]) update(word, typ, meaning) else: translate(choice)
def ring_prs(): try: import easygui msg = "Cylinder under internal pressure" title = "Problem parameters" fieldNames = [ "Internal radius", "External radius", "Internal pressure", "External pressure" ] fieldValues = [] # we start with blanks for the values fieldValues = easygui.multenterbox(msg, title, fieldNames) a = float(fieldValues[0]) b = float(fieldValues[1]) pa = float(fieldValues[2]) pb = float(fieldValues[3]) except: a1 = raw_input("Internal radius") b1 = raw_input("Eternal radius") c1 = raw_input("Internal pressure") d1 = raw_input("xternal pressure") a = float(a1) b = float(b1) pa = float(c1) pb = float(d1) return a, b, pa, pb
def membrane_prs(): try: import easygui msg = "Square Box" title = "Enter the problem parameters" fieldNames = [ "b", "a", "Material velocity", "Number of increments", "Total time" ] fieldValues = [] # we start with blanks for the values fieldValues = easygui.multenterbox(msg, title, fieldNames) L = float(fieldValues[0]) h = float(fieldValues[1]) beta = float(fieldValues[2]) ninc = int(fieldValues[3]) Tt = float(fieldValues[4]) except: a1 = raw_input("b") b1 = raw_input("a") d1 = raw_input("Beta") c1 = raw_input("Total increments") f1 = raw_input("Total time") L = float(a1) h = float(b1) beta = float(d1) ninc = int(c1) Tt = float(f1) return L, h, beta, ninc, Tt
def account_change(): accountfields = ["Username:"******"Password:"******"Edit Stored Account", "Please enter the required information.", accountfields) authfile = open("auth.txt", 'w') authfile.write(userpass[0]+'\n') authfile.write(userpass[1]) main()
def render_config(self): field_names = [setting for setting in sorted(self.config.__dict__.keys())] field_desc = [self.field_name_map[key] for key in field_names] msg = "Modify T.A.R.S settings." title = "Configure T.A.R.S" field_values = easygui.multenterbox(msg, title, field_desc) return field_names, field_values
def uiset(self,message="Fill in values for the fields." , title="set dataobject" , FieldNames = None , FieldValues = None , datatype= 'string'): #print "fnames",FieldNames,'fvalues',FieldValues if FieldNames is None and FieldValues is None: FieldNames=[]; FieldValues=[]; for key in self.keys(): v=self[key]; #print 'v',type(v) if (datatype=='string' and isstring(v)): FieldNames.append(key); FieldValues.append(self[key]); elif (datatype=='numeric' and isnumeric(v)): #print key,self[key] FieldNames.append(key); FieldValues.append(str(self[key])); # i=i+1; # print i; inputfieldValues =easygui.multenterbox(message, title, FieldNames, FieldValues); #print inputfieldValues #print type(inputfieldValues) #print str(inputfieldValues) if str(inputfieldValues)!='None': for i in range(0,len(FieldNames)): if datatype=='numeric': self[FieldNames[i]]=str2num(inputfieldValues[i]); elif datatype=='string': self[FieldNames[i]]=inputfieldValues[i];
def boussi_prs(): try: import easygui msg = "Half-space under point load" title = "Enter the problem parameters" fieldNames = [ "Length", "Height", "Point load", "Poissons ratio", "Youngs modulus" ] fieldValues = [] # we start with blanks for the values fieldValues = easygui.multenterbox(msg, title, fieldNames) l = float(fieldValues[0]) h = float(fieldValues[1]) P = float(fieldValues[2]) nu = float(fieldValues[3]) E = float(fieldValues[4]) except: a1 = raw_input("Length") b1 = raw_input("Height") c1 = raw_input("Point load") d1 = raw_input("Poissons ratio") e1 = raw_input("Youngs modulus") l = float(a1) h = float(b1) P = float(c1) nu = float(d1) E = float(e1) return l, h, P, nu, E
def ecg2rri(x): global rri, t, ax2, pos_c pos_c = [] plt.switch_backend('qt4Agg') plt.ion() msg = "RRi Detection Parameters" title = "Parameters Dialog" fieldNames = ["Threshold", "Refractory Period", "Low Cuttof Freq.", "Upper Cuttof Freq.", "Sampling Frequency"] fieldValues = ["0.5", "200", "5", "40", "1000"] fieldValues = multenterbox(msg, title, fieldNames, fieldValues) fieldValues = [float(k) for k in fieldValues] thr = fieldValues[0] Fs = fieldValues[4] lC = fieldValues[2] / (0.5 * Fs) #normalized lower cutoff frequency. uC = fieldValues[3] / (0.5 * Fs) #normalized upper cutoff frequency. B, A = butter(4, [lC, uC], 'band') xf = filtfilt(B, A, x) #filtered ecg. xd = diff(xf) #first derivative of the ecg. peaks = array([peaks + 1 for peaks in xrange(len(xd)) if xd[peaks] > 0 and xd[peaks + 1] < 0 and xf[peaks] > thr or xd[peaks] == 0]) #find RR peaks above threshold. rri = diff(peaks) # RRi in miliseconds t = cumsum(rri) / 1000.0 t_ecg = arange(0, len(xf)) / Fs fig = plt.figure() ax1 = fig.add_subplot(2, 1, 1) ax2 = fig.add_subplot(2, 1, 2) ax1.plot(t_ecg, xf) ax1.plot(t_ecg[peaks], xf[peaks], 'g.-') ax2.plot(t, rri, 'k.-') fig.canvas.mpl_connect('button_press_event', onclick) return t, rri
def canyon_prs(): try: import easygui msg = "Semi-circular canyon under SH waves" title = "Enter the problem parameters" fieldNames = [ "Radius (1.0)", "Side length(10.0)", "Height (10.0)", "Number of increments (4097)", "Angle of incidence (in rads)" ] fieldValues = [] # we start with blanks for the values fieldValues = easygui.multenterbox(msg, title, fieldNames) r = float(fieldValues[0]) l = float(fieldValues[1]) h = float(fieldValues[2]) Ninc = int(fieldValues[3]) gamma = float(fieldValues[4]) except: a1 = raw_input("Radius") b1 = raw_input("Side length") c1 = raw_input("Hight") d1 = raw_input("Number of increments") e1 = raw_input("Angle of incidence (in rads)") r = float(a1) l = float(b1) h = float(c1) Ninc = int(d1) gamma = float(e1) return r, l, h, Ninc, gamma
def _check_credentials(self): """ GUI: show GUI for entering the credentials when there is no credentials. """ if not self.connection_options: title = 'Enter Credentials' msg = textwrap.dedent('''\ Please enter your Credentials for downloading. Or you can put it in "{}" file. * Tips: [←][→] Move, [Enter] Select, [Esc] Cancel '''.format(self.taskcluster_credentials)) field_names = ['clientId', 'accessToken', 'certificate'] field_values = [] field_values = easygui.multenterbox(msg, title, field_names) try: raw_clientId = field_values[0] raw_accessToken = field_values[1] raw_certificate = json.loads(field_values[2]) credentials = Credentials(clientId=raw_clientId, accessToken=raw_accessToken, certificate=raw_certificate) self.connection_options = {'credentials': credentials} logger.debug('connection options: {}'.format(self.connection_options)) except Exception as e: logger.debug(e) self.connection_options = {} logger.debug('Can not load connection options from user input.') title = 'Load Options Error' msg = textwrap.dedent('''\ Can not load Credentials from user input. Run with no credentials. * Tips: [Enter] OK ''') easygui.msgbox(msg, title)
def wedge_prs(): try: import easygui msg = "Self equilibrated wedge" title = "Enter the problem parameters" fieldNames = [ "Semi-angle (Degrees)", "Length", "Poissons ratio", "Youngs modulus", "External shear" ] fieldValues = [] fieldValues = easygui.multenterbox(msg, title, fieldNames) phid = float(fieldValues[0]) l = float(fieldValues[1]) enu = float(fieldValues[2]) emod = float(fieldValues[3]) S = float(fieldValues[4]) except: a1 = raw_input("Semi-angle") b1 = raw_input("Length") c1 = raw_input("Poissons ratio") d1 = raw_input("Youngs modulus") e1 = raw_input("External shear") phid = float(a1) l = float(b1) enu = float(c1) emod = float(d1) S = float(e1) return phid, l, enu, emod, S
def getScreenInput(fieldValues): fieldValues = easygui.multenterbox(msg = msg, title = title, fields = fieldNames, values = fieldValues ) # make sure that none of the fields was left blank while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg += ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = easygui.multenterbox(errmsg, title, fieldNames, fieldValues) return fieldValues
def edit_monsters(m1, m2): while True: # loop until Cancel or having valid values # easygui.multenterbox(text, titles, fieldls, values) values = easygui.multenterbox( "Please edit carefully", "edit monster stats", ( "Monster1: name (text)", "Monster1: attack (float)", "Monster1: defense (float)", "Monster1: hitpoints (integer)", "Monster2: name (text)", "Monster2: attack (float)", "Monster2: defense (float)", "Monster2: hitpoints (integer)" ), ( m1.name, m1.attack, m1.defense, m1.hitpoints, m2.name, m2.attack, m2.defense, m2.hitpoints ) ) if values == None or None in values: easygui.msgbox("nothing changed: empty value or Cancel") break # break out of the edit loop else: try: m1 = goblin.Monster( values[0], float(values[1]), float(values[2]), int(values[3]) ) m2 = goblin.Monster( values[4], float(values[5]), float(values[6]), int(values[7]) ) except: easygui.msgbox("Invalid value. Please try again") continue # repeat editing break # no problems detected: return m1, m2 # return the changed monster instances
def main(): values=easygui.multenterbox("Display settings: ","",["Width","Height","Fullscreen","Sandbox","Tutorial"],["1366","766","Yes","No","No"]) consts.screenwidth=int(values[0]) consts.screenheight=int(values[1]) consts.Center.location=consts.Location1(consts.screenwidth,consts.screenheight) if values[3]!="No": consts.sandbox=True if values[4]!="No": if(easygui.msgbox("Tutorial starting", ok_button="Press 'p' to continiue with the tutorial")): pass consts.tutorial=True if values[2]!="Yes": screen = pygame.display.set_mode((consts.screenwidth, consts.screenheight)) else: screen = pygame.display.set_mode((consts.screenwidth, consts.screenheight),pygame.FULLSCREEN) consts.fs=True running = True #hi text="Empty" pygame.init() graphics.screen=screen graphics.clock = pygame.time.Clock() if consts.tutorial: graphics.tut() if not consts.sandbox: graphics.askBoard("menu") algoModule = algorithm.pyAlgorithm(consts.screenwidth,consts.screenheight,consts.lvl) else: graphics.sandbox() while running: algoModule.nextStep(text) running,text = graphics.drawBoard(algoModule.myCell, algoModule.cellList, algoModule.foodList,[algoModule.myEggs, algoModule.cellEggs])
def cups_print(username, printer_name): conn = cups.Connection() filename = eg.fileopenbox("Select the file to be printed", "File Selector") title = "Filename : " + filename msg = "empty - print all pages, '-' for range, ',' separate ranges)" field_names = ["Pages to be printed"] field_values = [] # we start with blanks for the values field_values = eg.multenterbox(msg, title, field_names, field_values) job_id = 0 if filename: cups.setUser(username) options = {'sides': 'two-sided-long-edge'} val = str(field_values[0]).replace(" ", "").strip(',') if bool(val): options['page-ranges'] = val try: conn.setPrinterUsersAllowed(printer_name, [username]) job_id = conn.printFile(printer_name, filename, filename, options) conn.setPrinterUsersAllowed(printer_name, ['']) except cups.IPPError as (status, description): eg.msgbox(title='IPP status is %d' % status, msg='Meaning: %s' % description)
def consume(now): inlist = gui.multenterbox(msg='请输入账户,消费金额',title=version,fields=(['电话','消费金额']),values=('','')) if inlist: phone = inlist[0] value = inlist[1] if phone.isdigit()==False: show = '请输入正确电话' gui.msgbox(msg=show,title=version) return if value.isdigit()==False: show = '请输入正确金额' gui.msgbox(msg=show,title=version) return info = pd.read_csv('./用户信息.csv') if len(info.loc[info['phone']==int(phone),'account'].values)>0: if info.loc[info['phone']==int(phone),'account'].values[0] >= int(value): info.loc[info['phone']==int(phone),'account'] -= int(value) account = str(info.loc[info['phone']==int(phone),'account'].values[0]) info.to_csv('./用户信息.csv',encoding='utf_8_sig',index=False) with open('./操作记录.csv','a',encoding='utf_8_sig') as log: log.write(phone+','+now+',消费,-'+value+','+account+'\n') show = '会员:'+phone+' 于 '+now+' 消费:'+value+'¥,余额:'+account+'¥' gui.msgbox(msg=show,title=version) else: account = str(info.iloc[info.iloc[:,1]==int(电话),2].values[0]) show = '会员: '+phone+' 余额: '+account+'¥, 余额不足!' gui.msgbox(msg=show,title=version) else: show = '会员:'+phone+' 不存在' gui.msgbox(msg=show,title=version)
def choose_player(world): players = [p.name for p in world.players] + ["Guest", "New"] player = None index = easygui.indexbox(msg="Pick Player", choices=players) if index < len(world.players): return world.players[index] fieldnames = ["Name", "Coins"] fieldvalues = ["BlackBeard " + str(random.randrange(1, 1000)), 9200] results = easygui.multenterbox(msg="Customize your player", title="Guest Player", fields=fieldnames, values=fieldvalues) player = Player() player.location = world.stardock_location player.area = Area.Space player.gold_coins = int(results[1]) player.ship = Junk() player.ship.moves = player.ship.total_moves player.ship.resources = { "wheat": 10, "food": 18, "iron": 1000 } player.name = results[0] if index == len(players) - 1: world.players += [player] return player
def graphic_donut_custom(): msg = "Custom Donut Graph: leave fields blank for default" title = "Donut Graph - Custom" field_names = ["Headline (optional)", "Percent (0-100)", "Description (Text)", "Label (Text)", "Color (Red, 0-255)", "Color (Green, 0-255)", "Color (Blue, 0-255)", "Clockwise (y/n)", "Grayscale (y/n/b)"] field_values = gui.multenterbox(msg, title, field_names) if field_values == None: return headline = field_values[0] percent_value = float(field_values[1].replace('%', '')) description = field_values[2] percent_label = field_values[3] color_red = int(field_values[4]) if field_values[4] != '' else osf.colors.CRIMSON[0] color_green = int(field_values[5]) if field_values[5] != '' else osf.colors.CRIMSON[1] color_blue = int(field_values[6]) if field_values[6] != '' else osf.colors.CRIMSON[2] clockwise = not (field_values[7] in osf.constants.NO_OPTIONS) grayscale = field_values[8] in osf.constants.YES_OPTIONS parameters = { "label": percent_label, "description": description, "color": (color_red, color_green, color_blue), "clockwise": clockwise, "headline": headline, "grayscale": grayscale } if (field_values[8] in osf.constants.BOTH_OPTIONS): parameters["grayscale"] = not parameters["grayscale"] img = osf.graphics.donut(percent_value, parameters) img.show() parameters["grayscale"] = not parameters["grayscale"] img = osf.graphics.donut(percent_value, parameters) img.show()
def graphic_donut(): msg = "Donut Graph" title = "Donut Graph" field_names = ["Headline (optional)", "Percent (0-100)", "Description (Text)", "Grayscale (y/n/b)"] field_values = gui.multenterbox(msg, title, field_names) if field_values == None: return headline = field_values[0] percent_value = float(field_values[1].replace('%', '')) percent_label = field_values[1].replace('%', '') + '%' description = field_values[2] grayscale = field_values[3] in osf.constants.YES_OPTIONS parameters = { "label": percent_label, "description": description, "headline": headline, "grayscale": grayscale } if (field_values[3] in osf.constants.BOTH_OPTIONS): parameters["grayscale"] = not parameters["grayscale"] img = osf.graphics.donut(percent_value, parameters) img.show() parameters["grayscale"] = not parameters["grayscale"] img = osf.graphics.donut(percent_value, parameters) img.show()
def EditHomework(): global displayHomework, homeworklist value = str((displayHomework.get('active'))) Index = displayHomework.index('active') b = homeworklist[Index].split(' ') b[0] = b[0].replace('[', '').replace(']', '') if '$_' in b[0]: b[0] = b[0].replace('$_', ' ') if '$_' in b[1]: b[1] = b[1].replace('$_', ' ') b.remove('-') b.remove('Due') j = b[3].split('-') b.remove(b[3]) for i in j: b.append(i) t = e.multenterbox("Edit The Values", title, b) counter = 0 for i in t: if i == '': t[counter] = b[counter] counter += 1 homework = f'[{t[0]}] {t[1]} - Due {t[2]} {t[3]}-{t[4].upper()}' homework2 = f"[{t[0].replace(' ','$_')}] {t[1].replace(' ','$_')} - Due {t[2]} {t[3]}-{t[4].upper()}" homeworklist[Index] = homework2 displayHomework.delete(Index) displayHomework.insert(Index, homework) SaveHomework()
def thing(): global datedue, hwitem hwthing = e.multenterbox( "Please enter the Name, Class, and Due Date of your assignment:", title, ['Name:', 'Class:', 'MM/DD/YY', 'HH:MM', 'AM/PM']) hwitem = hwthing[:2] datedue = hwthing[2:]
def guiTest(): """ Interface for performing a test. """ msg = "Enter test information to confirm patient eligibility. Enter 1 as patient number to test successful patient eligibility." title = "Test Details" fieldNames = ["Patient Healthcare #", "Test Name", "Employee #"] fieldValues = [] fieldValues = eg.multenterbox(msg, title, fieldNames) if fieldValues == None: return "Operation cancelled." if fieldValues[0] == '': eg.msgbox("Patient Healthcare # not provided", "Error!") return if fieldValues[1] == '': eg.msgbox("Test Name not provided", "Error!") return if fieldValues[2] == '': eg.msgbox("Employee # not provided", "Error!") return pnum, tname, enum = fieldValues try: pnum = int(pnum) enum = int(enum) except: eg.msgbox("Error! Please ensure that patient and employee # are integers") return valid_prescription = checkTest(pnum, tname, enum) if valid_prescription: test_id = valid_prescription[0] result = valid_prescription[1] if result: eg.msgbox("Prescription already used!", "Error!") return msg = "Patient eligibility confirmed. Enter test result." title = "Test Results" fieldNames = ["Lab Name", "Test Result"] fieldValues = [] fieldValues = eg.multenterbox(msg, title, fieldNames) if fieldValues == None: eg.msgbox('Operation cancelled') return lname, tresult = fieldValues msg = performTest(test_id, lname, tresult) title = "Result" eg.msgbox(msg, title) else: eg.msgbox("Prescription info invalid. Please check all fields. ", "Error!")
def input_data(): with open("cal_data.txt", "a") as data: msg = "Here you can enter some basic information" title = "Get the DATA!" fields = ["Fornavn", "Etternavn", "Fødselsdato"] data_string = str(easygui.multenterbox(msg, title, fields)) data_string = data_string.replace("'", "") data.write(data_string + ",\n")
def info(): #function to get the input from user global FirstName, LastName, Month, Day, Year, fieldValues msg = 'Enter your first and last name. Enter your birthday within the years 1900-2013.' title = 'Name Please' fieldNames = ['First Name', 'Last Name', 'Month', 'Day', 'Year'] fieldValues = easygui.multenterbox(msg, title, fieldNames, fieldValues) FirstName, LastName, Month, Day, Year = fieldValues
def GuiHashRange(): """ Retrieve records with a given range when database type is hash. Just a proof of concept, doesn't return anything readable or write to the answer file yet, but it does work. """ # Take input values msg = "Please enter the range search key values." title = "Ranged Search" fieldNames = ["Lower Bound", "Upper Bound"] fieldValues = [] fieldValues = eg.multenterbox(msg, title, fieldNames) if fieldValues == None: eg.msgbox('Operation cancelled') return lowerKey = fieldValues[0] upperKey = fieldValues[1] # Check that lower key < upper key. if upperKey <= lowerKey: eg.msgbox("Error! Upper bound must be larger than lower bound.") return # Change the key from string to bytes: lowbyte_key = lowerKey.encode('utf-8') upperbyte_key = upperKey.encode('utf-8') current = cur.first() # Iterate through the database, taking time before and after resultlist = [] i = 0 time_before = time.time() while i < len(DATABASE): if lowbyte_key <= current[0] <= upperbyte_key: resultlist.append((current[0], current[1])) current = cur.next() i += 1 time_after = time.time() # Get time in microseconds runtime = (time_after - time_before) * 1000000 # Results found if (resultlist): for item in resultlist: answers.write(item[0].decode('utf-8')) answers.write('\n') answers.write(item[1].decode('utf-8')) answers.write('\n') answers.write('\n') else: text = ("No results found for the following key range:\n{}\n{}\nTime: {} microseconds".format(lowerKey, upperKey, runtime)) msg = "Results:" title = "Retrieve With Key" eg.textbox(msg, title, "Number of records: {} in {} microseconds\n{}".format(len(resultlist), runtime, resultlist))
def initialize_game(): #image = "images/python_and_check_logo.gif" image = "images/checkbox.gif" title = "Memory Card" msg = "Please Choose Your Level" choices = ["Easy","Medium","Hard","Customize"] reply = eg.buttonbox(msg,image=image,choices=choices) size = [] if reply=="Easy": size=[4,4] if reply=="Medium": size=[6,6] if reply=="Hard": size=[8,8] if reply=="Customize": msg = "Enter Your Dimensions(at least one even number)" title = "Memory Card" fieldNames = ["row","column"] fieldValues = [] # we start with blanks for the values fieldValues = eg.multenterbox(msg,title, fieldNames) while 1: # do forever, until we find acceptable values and break out if fieldValues == None: break errmsg = "" # look for errors in the returned values for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) if int(fieldValues[0])%2!=0 and int(fieldValues[1])%2!=0: errmsg = ('Please input at least on EVEN number') if errmsg == "": break # no problems found else: # show the box again, with the errmsg as the message fieldValues = eg.multenterbox(errmsg, title, fieldNames, fieldValues) size=[int(fieldValues[0]),int(fieldValues[1])] return size