def on_mouse(self, event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: deg = int(get_angle_between_points(self.center, (x, y))) deg_plus_90 = (deg + 90)%360 i = integerbox(msg="enter value", title='analog trainer', lowerbound=0, upperbound=9999) self.training_data.append({'degree': deg_plus_90, 'value': i})
def getLength(): wantsHourBox = easygui.ynbox( "Please choose a format for inputting timer length.\nThe second option will allow more than 60 minutes.", "Timer Entry", ("Hours, Minutes, Seconds", "Minutes, Seconds")) minuteQuestion = "How many minutes, if any, will the timer last?" totalHours, totalMinutes, totalSeconds = 0, 0, 0 if wantsHourBox is True: totalHours = easygui.integerbox( "How many hours, if any, will the timer last?\nLeave the answer as 0 if the timer is under an hour.", "Hours", 0) minuteQuestion = "How many additional minutes, if any, will the timer last?" totalMinutes = easygui.integerbox( minuteQuestion, "Minutes", 0, ) totalSeconds = easygui.integerbox( "How many additional seconds, if any, will the timer last?", "Seconds", 0, upperbound=59) checkLength(totalHours, totalMinutes, totalSeconds) timerLengthInSeconds = (totalHours * 120) + (totalMinutes * 60) + totalSeconds return timerLengthInSeconds
def GuessNum(): choices = ("开始", "退出") user_sel = g.buttonbox("欢迎来到猜数字游戏", "猜数字游戏", choices=choices, default_choice=choices[1], cancel_choice=choices[1]) if user_sel == choices[0]: #print("选择了开始") user_input = g.integerbox("你猜我心里想的是什么数字?(0-100内的整数):", lowerbound=0, upperbound=100) while True: if user_input == TargetNum: g.msgbox("哇!猜对了!!真棒!!") break elif user_input > TargetNum: user_input = g.integerbox("猜大啦,再试一次(0-100):", lowerbound=0, upperbound=100) else: user_input = g.integerbox("猜小啦,再试一次(0-100):", lowerbound=0, upperbound=100)
def KI(): msg = 'Введите рост спортсмена' title = 'Сбор антропометрических данных' default = '0' lowerbound = 0 upperbound = 250 fieldValues = easygui.integerbox(msg, title, default, lowerbound, upperbound) rost = fieldValues msg1 = 'Введите массу тела спортсмена' title1 = 'Сбор антропометрических данных' default1 = '0' lowerbound1 = 0 upperbound1 = 250 fieldValues1 = easygui.integerbox(msg1, title1, default1, lowerbound1, upperbound1) mass = fieldValues1 IMT = float((mass * 10000) / (rost * rost)) strrost = str(rost) strmass = str(mass) strIMT = str(IMT) f = open('rostFile' + spch + '.dat', 'a') f.write('\n' + strrost) g = open('massFile' + spch + '.dat', 'a') g.write('\n' + strmass) h = open('IMTFile' + spch + '.dat', 'a') h.write('\n' + strIMT) easygui.msgbox('Индекс массы тела равен ' + strIMT) f.close() g.close() h.close() MainSPMenu()
def TLoad(): msg = 'Введите время тренировки в минутах' title = 'Сбор информации о тренировке' default = '0' lowerbound = 0 upperbound = 360 fieldValues = easygui.integerbox(msg, title, default, lowerbound, upperbound) time = fieldValues msg1 = 'Введите оценку напряженности тренировки' title1 = 'Сбор информации о тренировке' default1 = '0' lowerbound1 = 0 upperbound1 = 10 fieldValues1 = easygui.integerbox(msg1, title1, default1, lowerbound1, upperbound1) Load = fieldValues1 SLoad = time * Load strtime = str(time) strLoad = str(Load) strSLoad = str(SLoad) f = open('timingFile' + spch + '.dat', 'a') f.write('\n' + strtime) g = open('markFile' + spch + '.dat', 'a') g.write('\n' + strLoad) h = open('SLoadFile' + spch + '.dat', 'a') h.write('\n' + strSLoad) f.close() g.close() h.close() MainSPMenu()
def guessnum2(self): secret = random.randint(1, 9) times = 3 num = easygui.integerbox("来猜猜小公主我现在心里想的是1-9里哪一个数字::", title="猜数字", lowerbound=1, upperbound=9) if num == secret: easygui.msgbox("你是小公主我肚子里的蛔虫吗??!!") else: while num != secret: times -= 1 if num > secret: easygui.msgbox("大了", title="游戏结果") elif num < secret: easygui.msgbox("小了", title="游戏结果") if times > 0: easygui.msgbox("总共 3 次机会,你还剩下 %d 次机会哦" % times) num = easygui.integerbox("重新输吧:", title="猜数字", lowerbound=1, upperbound=9) else: easygui.msgbox("次数用光了") break else: easygui.msgbox("终于猜对了呀,哼,真是的,居然不是一次就中,你根本不爱我!") exitgame = easygui.boolbox("游戏结束辣", choices=["退出游戏", "再玩一次"]) if exitgame: sys.exit(0) else: self.guessnum2()
def guessnum1(self): secret = random.randint(1, 9) times = 3 num = easygui.integerbox("来猜猜小公主我现在心里想的是哪一个数字:", title="猜数字", lowerbound=1, upperbound=9) while (num != secret) and (times > 0): times -= 1 if num == secret: easygui.msgbox("你是小公主我肚子里的蛔虫吗??!!") break elif num > secret: easygui.msgbox("大了", title="游戏结果") elif num < secret: easygui.msgbox("小了", title="游戏结果") if times > 0: num = easygui.integerbox("重新输吧:", title="猜数字", lowerbound=1, upperbound=9) else: easygui.msgbox("次数用光了") exitgame = easygui.boolbox("游戏结束", choices=["退出游戏", "取消"]) if exitgame: sys.exit(0) else: pass
def Init(): # Variables initialization path = gui.diropenbox("Choose repertory of image", "./") files = os.listdir(path) if not os.path.exists("./GFD"): os.mkdir("GFD") if path is not None: # If we didn't click in the cancel bottom rad = gui.integerbox("Enter radian", "int ", 4, 1, 20) ang = gui.integerbox("Enter angle", "int ", 6, 1, 20) gui.msgbox("please be patient , it will take time") for file in files: # parcourir fichier #O(n) fic = path + '/' + file if os.path.isdir(fic): # If the file selected is a directory continue else: if imghdr.what( fic ) is None: # Check if the picture is not a picture continue else: # if the file is not a directory and a picture img = cv.imread( fic) # read the picture with cv.imread() grayScale = cv.cvtColor(img, cv.COLOR_RGB2GRAY) # calculate grayScale -= 255 sp = img.shape nom_img = os.path.splitext( os.path.basename(fic))[0] # get image signature OutputFeatureVectorFD(sp, grayScale, rad, ang, nom_img) gui.msgbox("complete") else: print("User has canceled the operation")
def problem2(): """Uses the specified function as described in the exam document.""" # TODO 2b: Write code to use the function as described in the exam document. count = easygui.integerbox("How many numbers?") bottom = easygui.integerbox("Lower Bound?") top = easygui.integerbox("Upper Bound?") even_odd(count, bottom, top)
def GuessNum(): try: temp = g.integerbox(msg, title, lowerbound=1, upperbound=10) guess = int(temp) while guess: if guess == secret: g.msgbox("我草,你是小甲鱼心里的蛔虫吗?!") g.msgbox("哼,猜中了也没有奖励!") break else: if guess > secret: g.msgbox("哥,大了大了~~~") else: g.msgbox("嘿,小了,小了~~~") guess = g.integerbox(msg, title, lowerbound=1, upperbound=10) except ValueError as reason: g.msgbox("输入值有误...请重新输入" + str(reason)) except EOFError as reason: g.msgbox("输入值有误...请重新输入" + str(reason)) except KeyboardInterrupt as reason: g.msgbox("输入值有误...请重新输入" + str(reason)) finally: g.msgbox("游戏结束,不玩啦^_^")
def guessnum(): guess = g.integerbox('不妨猜一下我现在在想那个数字吧(1-10)?', '猜数字小游戏', upperbound=10) while guess != secret: if guess < secret: guess = g.integerbox('小了(1-10)?', '猜数字小游戏', upperbound=10) else: guess = g.integerbox('大了(1-10)?', '猜数字小游戏', upperbound=10) g.msgbox('恭喜你猜对了!', '恭喜')
def exercise3(): """Interact with the user and test the count_multiples function.""" # You _DO_NOT_ need to modify this code for Lab 10. start = easygui.integerbox("Enter start value:", "Input", "", -2 ** 31, 2 ** 31) stop = easygui.integerbox("Enter stop value:", "Input", "", -2 ** 31, 2 ** 31) step = easygui.integerbox("Enter divisor value:", "Input", "", -2 ** 31, 2 ** 31) easygui.msgbox("There are {} multiples of {} in the range [{},{}].".format( count_multiples(start, stop, step), step, start, stop), "Result")
def date_input(): when_made = easygui.ynbox('Was the batch made today?', 'Date', ['Yes', 'No']) date = datetime.datetime.now() # sets current date and time to date module if when_made: date = date.strftime( '%Y%m%d' ) # Formats date as required, using datetime lib (Upper case Y for ful year) return date else: # if user wants to input there own date then month = 0 day = 0 # limiting inputs to the present date and back to the year 2000 year = easygui.integerbox('Please enter the year of manufacture', 'manual selection', lowerbound=2000, upperbound=int(datetime.datetime.now().year)) # if the user clicks cancel return to main menu if year is None: main() month = easygui.integerbox( 'Please enter the month of manufacture as a number', lowerbound=1, upperbound=12) if month is None: main() # If user selects feb limits input to 1 > 28 + Leap year Validation if month == 2: if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: while day < 1 or day > 29: day = easygui.integerbox( 'Please enter the day of manufacture:') else: while day < 1 or day > 28: day = easygui.integerbox( 'Please enter the day of manufacture') else: while day < 1 or day > 31: day = easygui.integerbox('Please enter the day of manufacture') if day is None: main() # This will check user inputs and format using the built in python function zfill if day < 10 and month < 10: date = (str(year) + str(month).zfill(2) + str(day).zfill(2)) elif day < 10: date = (str(year) + str(month) + str(day).zfill(2)) elif month < 10: date = (str(year) + str(month).zfill(2) + str(day)) else: date = (str(year) + str(month) + str(day)) return date
def exercise3(): """Interact with the user and test the count_multiples function.""" # You _DO_NOT_ need to modify this code for Lab 10. start = easygui.integerbox("Enter start value:", "Input", "", -2**31, 2**31) stop = easygui.integerbox("Enter stop value:", "Input", "", -2**31, 2**31) step = easygui.integerbox("Enter divisor value:", "Input", "", -2**31, 2**31) easygui.msgbox( "There are {} multiples of {} in the range [{},{}].".format( count_multiples(start, stop, step), step, start, stop), "Result")
def exercise5(): """Interact with the user and test the count_multiples function.""" # TODO 5b: Write code to use the count_multiples function as described in the lab document. start = easygui.integerbox('Enter start value:', ' ', '', 0, 2**31) stop = easygui.integerbox('Enter stop value:', ' ', '', start, 2**31) divisor = easygui.integerbox('Enter divisor value:', ' ', '', 0, 2**31) result = count_multiples(start, stop, divisor) easygui.msgbox( msg="There are {} multiples of {} in the range [{},{}]".format( result, divisor, start, stop))
def exercise1(): """Interact with the user and test the exemplar function.""" # Get a year from the user. year = easygui.integerbox( "Enter two-digit class year, 16-18:", "Input", "", 16, 18 ) # Continue until the user clicks the Cancel button. while year is not None: # Show the exemplar for the given year. easygui.msgbox( "Class of 20{}'s exemplar is {}.".format( year, exemplar( year ) ), "Result" ) # Get another year from the user. year = easygui.integerbox( "Enter two-digit class year, 16-18:", "Input", "", 16, 18 )
def exercise2(): """Interact with the user and test the drink_size function.""" # Get a number of ounces from the user. oz = easygui.integerbox( "Enter drink ounces:", "Input", "", 1, 144 ) # Continue until the user clicks the Cancel button. while oz is not None: # Show the drink size for the given number of ounces. easygui.msgbox( "A {}oz drink is {}.".format( oz, drink_size( oz ) ), "Result" ) # Get another drink size from the user. oz = easygui.integerbox( "Enter drink ounces:", "Input", "", 1, 144 )
def setupSession(chapters): qnum = easygui.integerbox("How many questions should be asked?") if not (easygui.ynbox( "Asking from all chapters, YES to continue or NO to select chapters." )): cstart = easygui.integerbox("Chapter to start: ") clen = easygui.integerbox( "How many chapters should be included (Max 22): ") else: cstart = 0 clen = 22 return qnum, chapters[cstart:cstart + clen]
def two_level_continuous_cycles_with_rest(): #A battery degradation test where the degradation is done at one current #and the capacity measurement is done at another current. #e.g. 9 degradation cycles, then 1 capacity measurement cycle. #degradation cycles #get user to enter number of cycles degradation_cycle_settings = Templates.CycleSettings() degradation_cycle_settings.get_cycle_settings("Degradation") num_degradation_cycles = eg.integerbox(msg="How Many Degradation Cycles?", title="Degradation Cycle", default=9, lowerbound=0, upperbound=99) #capacity measurement cycles capacity_cycle_settings = Templates.CycleSettings() capacity_cycle_settings.get_cycle_settings("Capacity") num_capacity_cycles = eg.integerbox(msg="How Many Capacity Cycles?", title="Capacity Cycle", default=1, lowerbound=0, upperbound=99) #test cycles - X discharge, Y charge, how many times? num_test_cycles = eg.integerbox(msg="How Many Test Cycles?", title="Test Cycles", default=1, lowerbound=0, upperbound=99) cycle_types = ("Degradation", "Capacity") first_cycle = eg.buttonbox( msg="Which cycle type should be completed first?", title="First Cycle", choices=cycle_types, default_choice=cycle_types[0]) cycle_settings_list = list() for j in range(num_test_cycles): if (first_cycle == "Degradation"): for i in range(num_degradation_cycles): cycle_settings_list.append(degradation_cycle_settings) for i in range(num_capacity_cycles): cycle_settings_list.append(capacity_cycle_settings) elif (first_cycle == "Capacity"): for i in range(num_degradation_cycles): cycle_settings_list.append(capacity_cycle_settings) for i in range(num_capacity_cycles): cycle_settings_list.append(degradation_cycle_settings) return cycle_settings_list
def load_parameter(): msg = "Parameter Dump auswählen oder Best-Score-Visualisierung" choices = ["Parameter auswählen","Beste Visualisierug"] reply = eg.buttonbox(msg, choices=choices) if reply == choices[0]: parameter_dir = eg.fileopenbox() vis_time = eg.integerbox("Dauer der Simulation (in Sek.):","TW Circuit") vs.main(parameter_dir, int(vis_time)) elif reply == choices[1]: parameter_dir = "parameter_dumps/20180817_01-56-01_rs2_v2_200.hkl" vis_time = eg.integerbox("Dauer der Simulation (in Sek.):","TW Circuit") vs.main(parameter_dir, int(vis_time))
def exercise3(): """Interact with the user and test the quadrant function.""" # Get a coordinate from the user. x = easygui.integerbox( "Enter x coordinate:", "Input", "", -2 ** 31, 2 ** 31 ) y = easygui.integerbox( "Enter y coordinate:", "Input", "", -2 ** 31, 2 ** 31 ) # Continue until the user clicks the Cancel button. while x is not None and y is not None: # Show the quadrant for the given coordinate. easygui.msgbox( "({},{}) is in quadrant {}.".format( x, y, quadrant( x, y ) ), "Result" ) # Get another coordinate from the user. x = easygui.integerbox( "Enter x coordinate:", "Input", "", -2 ** 31, 2 ** 31 ) y = easygui.integerbox( "Enter y coordinate:", "Input", "", -2 ** 31, 2 ** 31 )
def youxi(): while 1: ass = '用户' can = '密码' s = g.multpasswordbox('请输入你的账号和密码', '账号输入', [ass, can]) if s[0] == '3117004628' and s[1] == '123': g.msgbox('欢迎来到你的专属sex空间~~~', ok_button='oh~yeah~') break else: g.msgbox('输入错误,无法享受sex空间!') #猜数字 g.msgbox('来玩个猜数字游戏吧~,猜对了才有福利哦', '猜数字', '嗯?!') g.msgbox('警告:该游戏只能玩三次,三次不过的话就没福利了!!!', '猜数字', ok_button='好的,我知道了!') ass = g.integerbox(msg='请输入1~10任一个数字', lowerbound=1, upperbound=10) shu = a.randint(1, 10) i = 0 while 1: if shu > ass: g.msgbox('小了小了~', ok_button='知道了') i += 1 ass = g.integerbox(msg='请输入1~10任一个数字', lowerbound=1, upperbound=10) elif shu == ass: g.msgbox('猜对咯!') break elif shu < ass: g.msgbox('大了大了!', ok_button='知道了') i += 1 ass = g.integerbox(msg='请输入1~10任一个数字', lowerbound=1, upperbound=10) else: if i == 2: g.msgbox('与福利擦身而过了,下次加油吧', ok_button='知道了') sys.exit(0) #通过游戏,提问考验 sea = g.buttonbox('你渴望奈子么??', '选择吧,让我听到你的心声!', image='gg.gif', choices=('是的!', '额..(⊙o⊙)其实我更喜欢屁股~')) if sea == '是的!': g.msgbox('恭喜你!获得奈子!') we = g.buttonbox('怎么样?', image='sex1.gif', choices=('还可以', '我觉得不行!')) if we == '我觉得不行!': g.msgbox('滚犊子!再见!', '恩~,不要嘛~') sys.exit(0) else: g.msgbox('祝你身体愉快,生活健康,再见~', '我还想要怎么办???') sys.exit(0) else: g.msgbox('再见,没有福利了!', '...其实奈子是不错的!!') sys.exit(0)
def fsetting(): global n,m,nowcolor nn=easygui.integerbox(msg="自定义行数:",default=n,title="设置",lowerbound=1,upperbound=15) if nn: n=nn mm=easygui.integerbox(msg="自定义列数:",default=m,title="设置",lowerbound=1,upperbound=15) if mm: m=mm colorc=[x[0] for x in colorchoices] tchoice=easygui.choicebox(msg="选择主题",title="设置",choices=colorc,preselect=nowcolor) if tchoice in colorc: set_color(colorc.index(tchoice)) #print(nowcolor) all_redraw() change_nm()
def high_low(): """Implement the number guessing game High Low.""" # Create a random number in the range [1,100] for the user to guess. secret_number = 37 # random.randint( 1, 100 ) # For debugging purposes only, it's nice to know the secret. print(secret_number, flush=True) # Add the flush to ensure there's no buffering. count = 0 guess = 0 low = 0 high = 100 # TODO 6: Implement the High Low guessing game as described in the lab document. while count < 7: guess = easygui.integerbox( "Enter a guess between {} and {}:".format(low, high), "Input", "", 1, 100) count += 1 if guess == secret_number: break if guess > secret_number: result = "high" high = guess else: result = "low" low = guess easygui.msgbox("Your guess of {} is too {}.".format(guess, result), "Result") if guess == secret_number: easygui.msgbox( "You win! You guessed {} in {} guesses".format( secret_number, count), "Result") else: easygui.msgbox( "You Lose :( The secret number was {}".format(secret_number), "Result")
def exercise4(): """Interact with the user and test the count_sevens function.""" rolls = easygui.integerbox('How many 7s:', 'Input', '', 0, 2**31) total = count_sevens(rolls) percent = rolls * 100 / total easygui.msgbox("{} out of {} rolls ({:.2f}%) were 7.".format( rolls, total, percent))
def viewcomponents(): with open("batchindex.json", "r") as f: #reads json data indata = json.load(f) f.close() mylist = indata["UsedBatches"] n = 0 newcomp = easygui.integerbox( msg="Enter component serial number", upperbound=99999999999999) #user inputs component number while n < len(mylist): filename = str(newcomp) + ".pck" if os.path.exists(filename): newcomp = mylist[n] f1 = open(filename, "rb") #reads back the pickle file file_contents = pickle.load(f1) f1.close() msg = "Component Details for %s" % newcomp #returns following file contents from pickle file typ = "\nType: %s" % file_contents.type siz = "\nSize: %s" % file_contents.size date = "\nDate: %s" % file_contents.date stat = "\nCurrent Status: %s" % file_contents.componentstatus part = "\nPart of Batch: %s" % file_contents.batchno details = easygui.msgbox(msg + typ + siz + date + stat + part) break else: easygui.msgbox(msg="Component not found" ) #error message if component can't be found break
def problem3(): """Uses the specified function as described in the exam document.""" # TODO 3b: Write code to use the function as described in the exam document. first_num = easygui.integerbox("First Number?") second_num = easygui.integerbox("Second Number?") third_number = easygui.integerbox("Third Number?") fourth_number = easygui.integerbox("Fourth Number?") first = gcd(first_num, second_num) second = gcd(second_num, third_number) third = gcd(third_number, fourth_number) greatest_common_denominator = first if second <= greatest_common_denominator: greatest_common_denominator = second elif third <= greatest_common_denominator: greatest_common_denominator = third easygui.msgbox("GCD: " + str(greatest_common_denominator))
def gui(self, cryptionKey): '''FileUploader GUI''' while self.running: choise = easygui.indexbox( 'Upload files\n\nKey: ' + str(cryptionKey), 'File Uploader', ('Full Upload', 'Select File', 'Select Directory', 'Check files', 'Upload', 'Decrypt')) if choise == None: self.running = False elif choise == 0: fail( 'For now, Full Upload will only count files in drives and highest sized files.' ) byteLimit = easygui.integerbox( 'Enter Max Filesize (MegaBytes)', 'File Uploader', 500, 1, 100000) self.fullUpload(byteLimit) elif choise == 1: self.includeFile() elif choise == 2: self.includeDir() elif choise == 3: info(str(self.files) + ', ' + str(self.dirs)) elif choise == 4: self.upload() elif choise == 5: self.decryptFiles()
def inventory(self): items = [i for i in Game.items.values() if i.carrier == 1] #return easygui.choicebox("select item to use", choices=i) text = "------ Items in backpack of player ------\n" mass = 0 for i in items: text += i.__repr__() + "\n" mass += i.mass text += "====== Total mass of backpack: {} kg ======\n".format(mass) #text += "----- Items on the ground ---------\n" #items = [i for i in Game.items.values() if i.room == self.room and i.carrier is None] #for i in items: # text += i.__repr__() + "\n" text += self.show_items() number = easygui.integerbox( "Please enter number of item to use or to pick it up!\n" + "Enter a negative number to drop an item!\n" + text, lowerbound=-9999, upperbound=9999) if number is None: return None keys = [ k for k, v in Game.items.items() if v.carrier == 1 or v.room == self.room ] if number in keys: return number if number < 0: if number * -1 in keys: return number # negative number, to drop item! return None
def viewbatchdetails(): with open("batchindex.json", "r") as f: #reads json data indata = json.load(f) f.close() mylist = indata["UsedBatches"] n = 0 batchno = easygui.integerbox( msg="Enter batch number:", upperbound=9999999999 ) #user can input batch number to search for specific batch while n < len(mylist): filename = str(batchno) + ".pck" if os.path.exists(filename): batchno = mylist[n] f1 = open(filename, "rb") file_contents = pickle.load(f1) f1.close() btchno = "Batch Number: %s" % file_contents.batchno #returns the following attributes of the batch date = "\nManufacturedate: %s" % file_contents.date typ = "\nComponent Type: %s" % file_contents.type sze = "\nComponent Size: %s" % file_contents.size quanty = "\nNumber of Components %s" % file_contents.noofcomponents serialno = "\nSerial Numbers: %s" % file_contents.newcomplist status = "\nComponent Status: %s" % file_contents.componentstatus details = easygui.msgbox( btchno + date + typ + sze + quanty + serialno + status) #displays attributes in easygui message box break else: easygui.msgbox(msg="Batch not found" ) #if there is no batch, returns error message break
def mode2(): #air resistance B = [] i = 0 angle = 45 k = easygui.integerbox("Input the number of curved lines(1~)") if k == None: choosemode() for v in range(100, (k + 5) * 20, 20): i += 1 temp = drag_cannon(ini(v, angle), _dt=0.1) B.append(temp) choice = easygui.buttonbox('Choose path or velocity to polt', 'Choice', ['trajectory', 'velocity change']) if choice == 'trajectory': for i in range(0, k - 1, 1): v = 100 + 20 * i B[i].shoot() B[i].show_trajectory(v, angle) show() if choice == 'velocity change': for i in range(0, k - 1, 1): v = 100 + 20 * i B[i].shoot_v() B[i].show_velocity(v, angle) show() choosemode()
def load_parameter_weights(): eg.msgbox(msg="Wählen Sie zuerst den Parameter-Dump.") parameter_dir = eg.fileopenbox() eg.msgbox(msg="Wählen Sie nun den entsprechenden Weight-Dump.") weight_dir = eg.fileopenbox() vis_time = eg.integerbox("Dauer der Simulation (in Sek.):","TW Circuit") vs.main_with_weights(parameter_dir, weight_dir, int(vis_time))
def game(): times = 3 num = random.randint(1, 10) while 1: times = times - 1 msg = 'Try to guess what the number is (1~10): ' title = 'number game' E_num = g.integerbox(msg, title, lowerbound=1, upperbound=10) if E_num == num: g.msgbox("Yeah, you're right!") choice() else: if E_num > num: g.msgbox("Oh, it's big!") else: g.msgbox("No, it's small!") if times > 0: g.msgbox("Come again!") else: g.msgbox("Opportunity to run out!") choice()
def exercise1(): """Interact with the user and test the sum_odds and sum_evens functions.""" # You _DO_NOT_ need to modify this code for Lab 10. n = easygui.integerbox("Enter n:", "Input", lowerbound=0, upperbound=2 ** 31) odd = sum_odds(n) even = sum_evens(n) easygui.msgbox("n = {}\nsum of odds = {}\nsum of evens = {}".format(n, odd, even))
def showHomeworkByDate(): """ 按时间读取作业 用到了func块的getSubject、showHomeworkInfo和getHomeworkBydate方法 基本和showAllHomework方法相同 """ global user_id subjects = func.getSubject(user_id) choice = easygui.choicebox("选择你要查看的学科:", "YoxueHelper", subjects) # 这里是获取用户要查询的学科 days = easygui.integerbox('输入你要查询几天前至今的作业:', 'YoxueHelper', 7, 3, 5000) # 查看的时间限制 if days == None: main() return None # 直接关闭弹窗会返回None并报错,这儿做了一个处理 cards = func.getHomeworkBydate(user_id, days, choice) showList = [] for card in cards: showList.append(card['title']) choiceOption = easygui.choicebox("%s作业,共%i个" % (choice, len(showList)), "YoxueHelper", showList) if choiceOption: showHomeworkInfo(cards, showList.index(choiceOption), True) else: main()
def gui(): ver = get_latest_version() while True: choices = ['Download v%s' % ver, 'Specify Version', 'Backup v%s' % settings.current_ver, 'Revert to v%s' % settings.backup_ver, 'Edit Save Dir', 'Exit'] choice = easygui.indexbox('What do you want to do?', 'Chromium Downloader', choices) if choice == 0: del_current(True) download_chromium(ver) unzip() elif choice == 1: ver = get_closest_version(easygui.integerbox( 'Enter desired verson (The closest match will be used):', 'Specify a version', int(ver)) or int(ver)) elif choice == 2: backup(ver) elif choice == 3: revert() elif choice == 4: settings.save_dir = (easygui.enterbox("New Save Directory", "", "") or path.join(environ["ProgramFiles"], 'Chromium\\')) settings.store() else: break
def exercise4(): """Interact with the user and test the count_sevens function.""" # TODO 4b: Write code to use the count_sevens function as described in the lab document. rolls_desired = easygui.integerbox("How many rolls of sevens?", "Input", default="1000", lowerbound=0, upperbound=2 ** 31) shoot = roll_sevens(rolls_desired) easygui.msgbox("Took {} rolls to get {} sevens".format(shoot, rolls_desired))
def entrar(msg, inteiro=False): '''entrar(msg) -> str Exibe uma janela com a mensagem em msg e uma caixa de texto para que o usuário informe alguma string.''' if inteiro: return eg.integerbox(msg, TITLE) return eg.enterbox(msg, TITLE)
def exercise1(): """Odd and Even Sums exercise.""" # TODO 1c: Write code to use the sum_odds and sum_evens functions, as described in the lab document. number1 = int(easygui.integerbox(msg="Number: ", title="Lab08", default="", lowerbound=int(0))) odd = sum_odds(number1) even = sum_evens(number1) easygui.msgbox(msg="Number:" + str(number1) + " " + "sum of evens:" + str(even) + " " + "sum of odds:" + str(odd), title="results", ok_button="Cool")
def exercise4(): """Interact with the user and test the days_in_month function.""" # Get a month from the user. m = easygui.integerbox( "Enter month (1-12):", "Input", "", 1, 12 ) # Continue until the user clicks the Cancel button. while m is not None: # Show the number of days in the given month. if m == 2: # Prompt the user for the year if the month is February. y = easygui.integerbox( "Enter year (1582-):", "Input", "", 1582, 2 ** 31 ) easygui.msgbox( "{} of {} has {} days.".format( m, y, days_in_month( m, y ) ), "Result" ) else: # Use the current year for any month besides February. easygui.msgbox( "{} has {} days.".format( m, days_in_month( m, 2015 ) ), "Result" ) # Get another month from the user. m = easygui.integerbox( "Enter month (1-12):", "Input", "", 1, 12 )
def entrar(msg, inteiro=False): '''entrar(msg) -> str Exibe uma janela com a mensagem em msg e uma caixa de texto para que o usuário informe alguma string.''' if inteiro: # há 168h em uma semana return eg.integerbox(msg, TITLE, argUpperBound=168) return eg.enterbox(msg, TITLE)
def exercice_11(): myList = [1,4,12,43,12,44] monChoix = easygui.integerbox() for i in myList: if monChoix == i: break else: easygui.msgbox("the number doesn't exist on my list") print ("test")
def exercise5(): """Interact with the user and test the scorekeeper function.""" # TODO 5b: Write code to use the scorekeeper function as described in the lab document.\ player1 = easygui.enterbox("Name of Player 1?") player2 = easygui.enterbox("Name of Player 2?") winning_score = easygui.integerbox("Winning score for the game?", "Input", "10", 3, 2 ** 31) winner = scorekeeper(player1, player2, winning_score) easygui.msgbox("{} WINS!".format(winner), "Result")
def exercice_11_2 (): monChoix = easygui.integerbox("Enter a positive number. I'll tell is it's a primer one :", "", 7, 1) div = monChoix - 1 while div > 2: print("{} % {} = {}".format(monChoix,div,monChoix%div)) if (monChoix % div == 0): easygui.msgbox("not primer and first divider is {}".format(div)) break div -= 1 else: easygui.msgbox("your number {} is primer, congrats ! ".format(monChoix))
def makeBid(self, nplayers, ncards, trumpsuit, previousbids): thisbid = None if GRAPHICAL_INPUT: thisbid = easygui.integerbox(msg='Choose bid', title='Choose bid', lowerbound=0, upperbound=10) else: print("Enter bid: ") thisbid = int(input()) self.bid = thisbid self.advanceZeroCounter(thisbid) return thisbid
def run_application(): """ main application that runs all user interaction/scraping/prediction functions (highest layer) """ msg ="Forecast Dining Halls or Libraries?" title = "Settle" choices = ["Dining Halls", "Libraries"] choice = eGUI.choicebox(msg, title, choices) msg = "About how many minutes into the future shall I predict? (<300)" integer = eGUI.integerbox(msg, title, default = '30', upperbound = 300) n_predictions = int(integer)/15 msg = "How many earlier predictions shall I show?" n_earlier_predictions = int(eGUI.integerbox(msg, title, default = '4',upperbound=40)) if n_predictions == 0: n_predictions = 1 if choice == "Libraries": msg ="Which library do you want to explore?" title = "Where 2 Study" places = ["All Butler", "Science_and_Engineering_Library", "Uris", "Butler_Library_2", "Butler_Library_3", "Butler_Library_4", "Butler_Library_5", "Butler_Library_6"] place = eGUI.choicebox(msg, title, places) else: msg ="Which dining hall do you want to explore?" title = "Where 2 Eat" places = ["john_jay", "jjs"] place = eGUI.choicebox(msg, title, places) if place == "All Butler": i = 0 colors = ['red', 'orange', 'green', 'purple', 'pink'] for lib in [ "Butler_Library_2", "Butler_Library_3", "Butler_Library_4", "Butler_Library_5", "Butler_Library_6"]: pred(n_predictions, n_earlier_predictions, lib, colors[i]) i += 1 else: pred(n_predictions, n_earlier_predictions, place, 'purple') plt.title( 'Current and Predicted Occupancy for ' + place + ' Today') plt.ylabel('users connected') plt.xlabel('time') plt.show()
def exercise2(): """Summations exercise.""" # TODO 2b: Write code to use the summation function, as described in the lab document. number = int(easygui.integerbox(msg="n: ", title="Lab08", default="", lowerbound=(0), upperbound=(32))) some = summation(number, 1) formula = number * (number + 1) / 2 easygui.msgbox("n = {}, summation(n,1) = {}, formula result = {}". format(number, some, formula)) some = summation(number, 2) formula = number * (number + 1) * (2 * number + 1) / 6 easygui.msgbox("n = {}, summation(n,1) = {}, formula result = {}". format(number, some, formula)) some = summation(number, 3) formula = (number * (number + 1) / 2)**2 easygui.msgbox("n = {}, summation(n,1) = {}, formula result = {}". format(number, some, formula))
def exercise2(): """Interact with the user and test the summation function.""" # You _DO_NOT_ need to modify this code for Lab 10. n = easygui.integerbox("Enter n:", "Input", lowerbound=0, upperbound=2 ** 31) s = summation(n, 1) f = n * (n + 1) // 2 easygui.msgbox("n = {}, summation( n, 1 ) = {}, formula result = {}".format(n, s, f)) s = summation(n, 2) f = n * (n + 1) * (2 * n + 1) // 6 easygui.msgbox("n = {}, summation( n, 2 ) = {}, formula result = {}".format(n, s, f)) s = summation(n, 3) f = (n * (n + 1) // 2) ** 2 easygui.msgbox("n = {}, summation( n, 3 ) = {}, formula result = {}".format(n, s, f))
def predict(): msg ="Which dining hall do you want to explore?" title = "Where 2 Eat" dhalls = ["john_jay", "jjs"] dhall = eGUI.choicebox(msg, title, dhalls) msg = "How many hours do you want to glance into the future?" integer = eGUI.integerbox(msg, title, default = '2') points_to_predict = int(integer)*4 c, f, w = load_all_current(dhall, 'spr_2016') predicted = forecast_master(c, f, w, points_to_predict) plt.plot(predicted.index, predicted.values, color='black', linewidth=1., linestyle='dashed') historical = w[w.columns[:3]].iloc[:len(predicted.index)] plt.plot(historical.index, historical.values, linewidth=.7,color='gray', linestyle='dashed') plt.plot(c.index, c.values, color='blue', linewidth=2., label = 'Today') plt.title( 'Current and Predicted Occupancy for ' + dhall + ' Today') plt.ylabel('users connected') plt.xlabel('time') plt.show() return predicted, w
def high_low(): """Implement the number guessing game High Low.""" # Create a random number in the range [1,100] for the user to guess. secret_number = 37 # random.randint( 1, 100 ) # For debugging purposes only, it's nice to know the secret. print(secret_number, flush=True) # Add the flush to ensure there's no buffering. # TODO 6: Implement the High Low guessing game as described in the lab document. guesses = 7 while guesses > 0: guess = easygui.integerbox("Enter a guess:", "Input", "", 1, 100) easygui.msgbox("Your guess is {}.".format(guess), "Result") if guess != secret_number: if guess > secret_number: return "Too High" elif guess < secret_number: return "Too Low" return "You're at " + str(guess) + "guesses" guesses -= 1 return "You won! The secret number was " + str(secret_number)
def enter_settings(self): s1 = "What is your local time zone? (i.e. Australia/Perth.) Used to determine the UTC/GMT time for file naming purposes." self.timezone_name = easygui.choicebox(s1, "Choose local time zone", pytz.common_timezones) s2 = "Enable debug mode? (Displays very detailed program execution information on screen.)" a = easygui.buttonbox(s2,"Debug mode?",("Normal mode (recommended)","Debug mode (experts only)")) self.debug_mode = True if a.lower().startswith("debug") else False s3 = "Save emails older than X days: (default 60 days; 0 for all emails regardless of age.)" self.days_old = easygui.integerbox(s3,"Email age?",default=60, lowerbound=0, upperbound=99999999) self.dest_dir = easygui.diropenbox("Pick a folder to save the email .msg files to.", "Choose backup destination", "%HOMEPATH%") b = easygui.ynbox("Apply 'Saved as MSG' tag to emails that are saved?", title="Mark emails as saved?", choices=("Yes (recommended)","No (experts only)")) self.mark_as_saved = bool(b)
def mode2(): #air resistance B = [] i = 0 angle = 45 k = easygui.integerbox("Input the number of curved lines(1~)") if k == None: choosemode() for v in range(100,(k+5)*20,20): i += 1 temp = drag_cannon(ini(v, angle), _dt = 0.1) B.append(temp) choice = easygui.buttonbox('Choose path or velocity to polt','Choice',['trajectory','velocity change']) if choice == 'trajectory': for i in range(0,k-1,1): v = 100 + 20*i B[i].shoot() B[i].show_trajectory(v,angle) show() if choice == 'velocity change': for i in range(0,k-1,1): v = 100 + 20*i B[i].shoot_v() B[i].show_velocity(v,angle) show() choosemode()
def exercise5(): """Interact with the user and test the passed_pft function for someone less than 30 years of age.""" # Get a set of PFT results from the user. g = easygui.buttonbox( msg="Select gender:", title="Select", choices=[ "Female", "Male" ] ) r = easygui.integerbox( "Enter run time (in seconds):", "Input", "", 300, 3000 ) s = easygui.integerbox( "Enter situps completed:", "Input", "", 0, 180 ) p = easygui.integerbox( "Enter pushups completed:", "Input", "", 0, 180 ) # Continue until the user clicks the Cancel button. while g is not None and r is not None and s is not None and p is not None: # Show the Pass/Fail result of the PFT. if passed_pft( g, r, s, p ): easygui.msgbox( "Pass!", "Result" ) else: easygui.msgbox( "Fail.", "Result" ) # Get another set of PFT results from the user. g = easygui.buttonbox( msg="Select gender:", title="Select", choices=[ "Female", "Male" ] ) r = easygui.integerbox( "Enter run time (in seconds):", "Input", "", 300, 3000 ) s = easygui.integerbox( "Enter situps completed:", "Input", "", 0, 180 ) p = easygui.integerbox( "Enter pushups completed:", "Input", "", 0, 180 )
if re.search('MC\d\d.txt',file): tool = file[:4] BEzoneList, PCzoneList, zoneToIndexMap, MPcomPort, BEintTime, BEnumScans, PCintTime, PCnumScans = nsl.load_OES_config(tool) try: runNum = sys.argv[1] process = sys.argv[2] except: BEproc = eg.ynbox(msg='Which process is running?', title='choose process', choices=('BE','PC')) if BEproc: process = 'BE' elif not BEproc: process = 'PC' try: runNum = str(eg.integerbox(msg='enter run number (a format like \'440\' is fine)', title='enter run number', upperbound=99999)) runNum = runNum.lstrip('S') runNum = runNum.lstrip('s') runNum = runNum.lstrip('0') print 'using',runNum,'as run number' except: runNum = None try: tool = sys.argv[3] except: files = os.listdir('C:/OESdata') for file in files: if re.search('MC\d\d.txt',file): tool = file[:4]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import random import easygui secret = random.randint(1, 100) guess = 0 tries = 0 easygui.msgbox("""AHOY! I\'m the Dread Pirate Robers, and I have a secret! It is a number from 1 to 99. I\'ll give you 6 tries.""") while guess != secret and tries < 6: guess = easygui.integerbox('What\'s your guess?') if not guess: break if guess < secret: easygui.msgbox(str(guess) + 'is too low, you scurvy dog!') elif guess > secret: easygui.msgbox(str(guess) + 'is too high, landlubber!') tries += 1 if guess == secret: easygui.msgbox('Bingo! You got it! Found my secret, you did!') else: easygui.msgbox('The secret number was:', secret)
import random, easygui secret = random.randint(1, 99) guess = 0 tries = 0 easygui.msgbox("""AHOY! I'm the Dread Pirate Roberts, and I have a secret! It is a number from 1 to 99. I'll give you 6 tries.""") while guess != secret and tries < 6: guess = easygui.integerbox("What's yer guess, matey?") if not guess: break if guess < secret: easygui.msgbox(str(guess) + " is too low, ye scurvy dog!") elif guess > secret: easygui.msgbox(str(guess) + " is too high, landlubber!") tries = tries + 1 if guess == secret: easygui.msgbox("Avast! Ye got it! Found my secret, ye did!") else: easygui.msgbox("No more guesses! Better luck next time, matey!")
import easygui secret="Tawheed" year=23 name=easygui.enterbox ("What is your name?") if name == secret: str(easygui.msgbox ("Are you the birthday boy?")) else: easygui.msgbox ("You are not the birthday boy. Sorry, no cake for you!") number=easygui.integerbox("How old are you going to be on your birthday?") if number==year: easygui.msgbox("You are the birthday boy! Blow the candles!Hip-hip-Hooray!Yay!") else: easygui.msgbox ("You are dfinetly not the birthday boy! Too bad!")