def generatePDF(self): try: i = max(self.lPaid + self.lUnpaid) except: i = 0 downloadFile(FILENAME) numberOfPermissions = simpledialog.askinteger('Antal', 'Hur många tillstånd?') while numberOfPermissions != None and numberOfPermissions % 3 != 0: tk.messagebox.showinfo('Fel', 'Måste vara jämt delbart med tre!') numberOfPermissions = simpledialog.askinteger('Antal', 'Hur många tillstånd?') if numberOfPermissions: self.updateListOfUnpaid(i, numberOfPermissions) fileName = creatPermissionPDF(self.apartmentNumber, i+1, numberOfPermissions) updateFile_PaidUnpaid(self.apartmentNumber, self.dPaid_dates, self.lUnpaid) if self.checkButtonVal.get(): sendEmail(fileName, self.lEmail, 'Parkeringstillstånd', 'Här kommer dina parkeringstillstånd!') else: webbrowser.open_new(r'%s' % fileName)
def reserve_Button(self): # Input the information input_id_value = simpledialog.askinteger("test", "Please enter customer ID: ") Input_Date_value = simpledialog.askstring("test","Please enter date for reservation: ") Input_Time_value = simpledialog.askstring("test","Please enter time for reservation: ") InputService_value = simpledialog.askstring("test","Which services do you want?") length_value = simpledialog.askinteger("test", "For how long?") ServiceObject = eval(InputService_value) ServiceObject.reserve(input_id_value, Input_Date_value, Input_Time_value, length_value, InputService_value)
def set_child_cap(): """Requests new child cap from the user.""" child_split = list(lnp.settings.childcap.split(':')) child_split.append('0') # In case syntax is invalid v = simpledialog.askinteger( "Settings", "Absolute cap on babies + children:", initialvalue=child_split[0]) if v is not None: v2 = simpledialog.askinteger( "Settings", "Max percentage of children in fort:\n" "(lowest of the two values will be used as the cap)", initialvalue=child_split[1]) if v2 is not None: df.set_option('childcap', str(v)+':'+str(v2)) binding.update()
def parameterSelected(self, selectPos): """Callback when a parameter is selected""" tmParamExtraction = self.tmParamExtractions[selectPos] name = tmParamExtraction.name descr = tmParamExtraction.descr paramType = tmParamExtraction.valueType value = self.tmParamValues[selectPos] if paramType == UTIL.DU.BITS or paramType == UTIL.DU.SBITS or \ paramType == UTIL.DU.UNSIGNED or paramType == UTIL.DU.SIGNED: answer = simpledialog.askinteger("Integer Parameter", descr + ": " + name, parent=self, initialvalue=value) elif paramType == UTIL.DU.BYTES or paramType == UTIL.DU.FLOAT or \ paramType == UTIL.DU.TIME or paramType == UTIL.DU.STRING: answer = simpledialog.askstring("String Parameter", descr + ": " + name, parent=self, initialvalue=value) else: answer = None if answer == None: return # new parameter value entered --> update param value entry and list newValue = answer self.tmParamValues[selectPos] = newValue text = tmParamExtraction.descr + ": " + tmParamExtraction.name + " = " + str(newValue) self.parametersListbox.list().delete(selectPos) self.parametersListbox.list().insert(selectPos, text)
def plotRate(Kn, K1, KnSD, K1SD, CONC, antib): Kn1=Kn/K1 SDkn1=(Kn/K1)*np.sqrt(((KnSD/Kn)**2)+((K1SD/K1)**2)) fig=plt.figure() ax = fig.add_subplot(111) ax.errorbar(CONC, Kn1,yerr=SDkn1,color='g',label='$'+str('wt')+str(antib)+'- %s$' % str('Kn/K1')) ax.legend(fontsize=16) #ax.set_xlim([-1,max()]) ax.set_ylim([0.001,1.5]) if x_ax==True: xe=simpledialog.askinteger('X_lim','set_xlim') else: xe=max(conc[str(ant)]) ax.set_xlim([0,xe]) ax.set_yscale('linear',fontsize=16) ax.set_xscale('linear',fontsize=16) ax.tick_params(axis='x', labelsize=14) ax.tick_params(axis='y', labelsize=14) plt.ylabel('Kn/K1',fontsize=16) plt.xlabel('Conc '+str(antib)+ ' (microM)',fontsize=16) ax.grid(True) #fig.savefig(str(antib)+str(n1)+':'+str(n2)+'.pdf') return fig
def paramClicked(self, param, nodeID): """callback when a Param node is clicked""" innerTree = self.tree() if param.isReadOnly(): return nodeKey = innerTree.item(nodeID, "text") nodeValues = innerTree.item(nodeID, "value") name = nodeValues[0] value = nodeValues[1] paramType = param.getParamType() if paramType == UTIL.DU.BITS or paramType == UTIL.DU.SBITS or \ paramType == UTIL.DU.UNSIGNED or paramType == UTIL.DU.SIGNED: answer = simpledialog.askinteger("Integer Parameter", nodeKey + ": " + name, parent=self, initialvalue=value) elif paramType == UTIL.DU.BYTES or paramType == UTIL.DU.FLOAT or \ paramType == UTIL.DU.TIME or paramType == UTIL.DU.STRING: answer = simpledialog.askstring("String Parameter", nodeKey + ": " + name, parent=self, initialvalue=value) else: answer = None if answer == None: return # new parameter value entered --> update param object and tree newValue = answer param.value = newValue innerTree.set(nodeID, 1, newValue)
def delete_rode(self, event): if Rodstable.count == 0: showerror('Ошибка удаления', 'В таблице не осталось заполненных полей') return number_to_del = askinteger('', 'Введите № стержня:', parent=self) if number_to_del not in Rodstable.dict_items: showwarning('Предупреждение', 'Вы пытаетесь удалить стержень, которого ' 'не существует', parent=self) return self.clear_table() Rodstable.dict_items.pop(number_to_del) Rodstable.count -= 1 for item in Rodstable.dict_items: if item > number_to_del: Rodstable.dict_items[item - 1] = (Rodstable.dict_items[item][0], Rodstable.dict_items[item][1], Rodstable.dict_items[item][2], Rodstable.dict_items[item][3], Rodstable.dict_items[item][4]) Rodstable.dict_items.pop(item) self.fill_table()
def inputdata(): x = tkSimpleDialog.askinteger("Input","Multiplier") if x: tkMessageBox.showwarning("Yes",x) listbox.insert(END, x) else: tkMessageBox.showwarning("No","You did it wrong")
def set_pop_cap(self): """Requests new population cap from the user.""" v = simpledialog.askinteger( "Settings", "Population cap:", initialvalue=self.lnp.settings.popcap) if v is not None: self.lnp.set_option('popcap', str(v)) binding.update()
def set_pop_cap(self): """Requests new population cap from the user.""" v = simpledialog.askinteger( "Settings", "Population cap:", initialvalue=self.lnp.settings.popcap, parent=self.root) if v is not None: self.lnp.set_option('popcap', v) self.update_displays()
def set_graze_coef(): """Requests new graze coefficient from the user.""" v = simpledialog.askinteger( "Settings", "Graze coefficient:", initialvalue=lnp.settings.grazeCoef) if v is not None: df.set_option('grazeCoef', str(v)) binding.update()
def set_strict_pop_cap(): """Requests new strict population cap from the user.""" v = simpledialog.askinteger( "Settings", "Strict population cap:", initialvalue=lnp.settings.strictPopcap) if v is not None: df.set_option('strictPopcap', str(v)) binding.update()
def getN_NumMines(self, **kwargs): """ gets N and num_mines {from the user in text mode|from the kwargs in test mode} """ if self.app_type == 'text': N = int(input('Please input the size of board (e.g., 16): ')) num_mines = int(input('Please input the number of mines (e.g., 15): ')) return N, num_mines elif self.app_type == 'test': N = kwargs['N'] num_mines = kwargs['num_mines'] return N, num_mines elif self.app_type == 'gui': master = kwargs['master'] master.withdraw() N = simpledialog.askinteger('Minesweeper','Enter Size of Map:',minvalue=1,maxvalue=25)#TODO: check min/max num_mines = simpledialog.askinteger('Minesweeper','Enter Number of Mines:',minvalue=1, maxvalue=N*N-1) #TODO: check min/max return N, num_mines
def AvailableTimeForService_Button(self): InputService_value = simpledialog.askstring("test","Which services do you want?") Start_Date_value = simpledialog.askstring("test","Please enter start date: ") Start_Time_value = simpledialog.askstring("test","Please enter start time: ") End_Date_value = simpledialog.askstring("test","Please enter end date: ") End_Time_value = simpledialog.askstring("test","Please enter end time: ") length_value = simpledialog.askinteger("test", "For how long?") AvailableTimeForServiceInstance = AvailableTimeForService(Start_Date_value, Start_Time_value,End_Date_value, End_Time_value, InputService_value, length_value)
def rand_board(): global board global step global openfile density = tkd.askinteger('Density', 'enter a cell density between 0 and 100') create_random_board(density) step = 1 openfile = 'empty_board.gol' display_board(board)
def gotoQuestion(): global socket, running if running: questionNo = simpledialog.askinteger("Go to question...", "Question Number:") if questionNo: disableButton() network.sendMessage('gotoQu', questionNo, socket) else: messagebox.showerror("Error", "Server has not Started Running Yet!")
def node_modify(self, event): i = self.get_node_at_coord(event.x, event.y) if not i: return weight = simpledialog.askinteger("Weight", "Enter weight of node {}".format(i), initialvalue=self.nodes[i]['weight']) if weight: self.nodes[i]['weight'] = weight self.redraw()
def line_modify(self, event): start, end = self.get_line_at_coord(event.x, event.y) if not start: return weight = simpledialog.askinteger("Weight", "Enter weight of connection {}-{}".format(start, end), initialvalue=self.connections[(start, end)]) if weight: self.connections[(start, end)] = weight self.redraw()
def goto_line_event(self, event): lineno = tkSimpleDialog.askinteger("Goto", "Go to line number:", parent=self) if lineno is None: return "break" if lineno <= 0: self.bell() return "break" self.mark_set("insert", "%d.0" % lineno) self.see("insert")
def insertClicked(self,root): listName = "personnel" selection = self.view.tree1.selection() if len(selection) > 0: listName = self.view.tree1.item(selection[0])['text'] idt = tkSimpleDialog.askinteger(title = 'personnel ID',prompt = 'input personnel ID:',minvalue = 1) name = tkSimpleDialog.askstring(title = 'name',prompt = "input personnel's name:") gender = tkSimpleDialog.askstring(title = 'gender',prompt = "input personnel's gender:",initialvalue="male") age = tkSimpleDialog.askinteger(title = 'age',prompt = "input personnel's age:",initialvalue=20,minvalue = 0) nationality = tkSimpleDialog.askstring(title = 'nationality',prompt = "input personnel's nationality:",initialvalue="China") phone = tkSimpleDialog.askstring(title = 'phone number',prompt = "input personnel's phone number:",initialvalue="0") if name == "": tkMessageBox.showerror("Error","invalid input, personnel's name can not be empty") return if True == self.service.insert(listName, idt, name, gender, age, nationality, phone): #dictres = selectByIdt(listName,idt) self.loadDetails(root) else: tkMessageBox.showerror("Error","Sorry, this personnel ID may already exist in database")
def reset_board(self): probability = tkdialogs.askinteger("Probability", "Enter a probability of a cell being alive, ranging from 0 to 100\n" "\tTo get an empty board use the '0' value") if probability is None or probability < 0 or probability > 100: # None is returned if 'Cancel' is pressed return self.board.board = board.BoardFactory.generate_randomized_board_field(h_size=self.board.horizontal_size, v_size=self.board.vertical_size, probability=probability) self.board.update_observers() # update all observers over changed board manually
def goto_line_event(self, event): """Perform goto line operation.""" lineno = tkSimpleDialog.askinteger("Goto", "Go to line number:", parent=self) if lineno is None: return "break" if lineno <= 0: self.bell() return "break" self.mark_set("insert", "{0:d}.0".format(lineno)) self.see("insert")
def sad(): messagebox.showinfo("Wondering", "Now you're thinking if you still want to continue with your soccer dream OR start learning about something and become whatever you just learned.") choice = simpledialog.askinteger("Think", "Start improving by going back to your high school team until something good happens(1) OR quit soccer and find an another career(2).") if (choice == 1): college() elif (choice == 2): career() else: intro()
def career(): messagebox.showinfo("Career", "You found a career that you're interested in. But someone from the academy team motivates you to do better and put in 100% to acheive your dream of being a professional soccer player.") choice = simpledialog.askinteger("Career", "Stick with the career you were learning about(1) OR you are willing to take another chance of being a professional soccer player(2).") if (choice == 1): career2() elif (choice == 2): tryout2() else: intro()
def decide(): messagebox.showinfo("Decide", "Have you decide yet? Whats it going to be.?") choice = simpledialog.askinteger("Decide", "I'll take the offer(1) or naaaahhhhhhh Im good(2)") if (choice == 1): lucky() elif (choice == 2): messagebox.showinfo("Denied", "You have denied the offer and you're going to find another career to become as for your future but most importantly..") end()
def intro(): """ Introductory Function -> starts the story going """ messagebox.showinfo("Title", "\nHello, you are a _____ from ____. " + \ "You stumble across such and such.") choice = simpledialog.askinteger("Choose wisely", "You have a choice to pick: 1 or 2.") if choice == 1: choice1() elif choice == 2: choice2() else: intro()
def choice2(): choice = simpledialog.askinteger("Choose wisely", "This is the next part of the story. Now you must choose 1 or 2 again.") if (choice == 1): messagebox.showinfo("The End", "You chose right. THE END") elif (choice == 2): messagebox.showinfo("The End", "You chose ok. THE END") else: choice2()
def intro(): """ Introductory Function -> starts the story going """ messagebox.showinfo("Title", "\nHello, you are a high schooler from Luisito High School. " + \ "You want to try out to a professional soccer club form Oregon like Timbers. Alright? ") choice = simpledialog.askinteger("Choose wisely", "Would you like to try out? (When 1 is 'yes' and 2 is 'no'). ") if choice == 1: tryout() elif choice == 2: noTryout() else: intro()
def updateClicked(self,root): listName = "personnel" selection = self.view.tree1.selection() if len(selection) > 0: listName = self.view.tree1.item(selection[0])['text'] idt = tkSimpleDialog.askinteger(title = 'update personnel information',prompt = 'input personnel ID:',minvalue = 1) res = self.service.selectByIdt(listName, idt) if len(res) == 0 or res is None: tkMessageBox.showerror("Error","Sorry, can not update personnel information") return name = tkSimpleDialog.askstring(title = 'name',prompt = "input personnel's name:",initialvalue=res[0]['name']) gender = tkSimpleDialog.askstring(title = 'gender',prompt = "input personnel's gender:",initialvalue=res[0]['gender']) age = tkSimpleDialog.askinteger(title = 'age',prompt = "input personnel's age:",initialvalue=res[0]['age'],minvalue = 0) nationality = tkSimpleDialog.askstring(title = 'nationality',prompt = "input personnel's nationality:",\ initialvalue=res[0]['nationality']) phone = tkSimpleDialog.askstring(title = 'phone number',prompt = "input personnel's phone number:",initialvalue=res[0]['phone']) if True == self.service.update(listName, idt, name, gender, age, nationality, phone): self.loadDetails(root) tkMessageBox.showinfo("success", "personnel information updated") else: tkMessageBox.showerror("Error", "Sorry, please check if your input is legal")
def choice1(): choice = simpledialog.askinteger("Choose wisely", "Eat appropriate food before training? Now you must choose 1(Yes) or 2(No) again.") if (choice == 1): messagebox.showinfo("Yes", "Training goes amazing! You're offered a spot on the team.") elif (choice == 2): messagebox.showinfo("No", "Training goes bad, and you go back home.") else: choice1()
def main(): while True: print() file = input( "Enter the file's name with extension in the correct directory: ") try: f = open(file, 'r') except FileNotFoundError: print("Wrong file or file path. Please try again.") else: break app = tk.Tk() app.withdraw() num_letters = simpledialog.askinteger( 'Pie Chart Limit', "Please input number of letters to show on Pie Chart:", parent=app) pie_chart = PieChart( 200, file, f, num_letters) # Create instance using the file we entered pie_chart.draw_chart()
def run(): Tk().withdraw() filename = askopenfilename(title="Choose an image file to rotate") type = filename[-3:].upper() path = filename.split('/') # save_path = '/'.join(path[:-1]) im = Image.open(filename) imtk = ImageTk.PhotoImage(im) degrees = simpledialog.askinteger("Degrees", "Rotate the image how many degrees?", minvalue=0, maxvalue=360) rotated = im.rotate(degrees) im.show() rotated.show() im.save(path[-1] + '-rotated', type)
def connect_node(self): ip = simpledialog.askstring("Input", "IP: ", parent=self.toplevel) if ip is not None: print("IP: ", ip) else: print("You don't write ip ?") port = simpledialog.askinteger("Input", "Port: ", parent=self.toplevel, minvalue=0, maxvalue=65353) if port is not None: print("Port: ", port) else: print("You don't write port ?") ndconnect(ip, port) messagebox.showinfo( 'Node', ("Connected Node on " + "IP:" + ip + " PORT: " + str(port) + "."))
def _finish_rec_by_subject(self, subject): """ finishes recording :param subject: Audio/ Video :return: None """ rec_type = AudioRecorderClass if subject == 'Audio' else VideoRecorderClass recordings = list( filter(lambda r: r.is_recording() and isinstance(r, rec_type), self.recordings)) if len(recordings) != 1: msg = f"There are multiple recordings right now.\n" \ f"Current recordings: {[r.get_path() for r in recordings]}\n" \ f"Please enter the index of the recording (1-{len(recordings)}):" ind = simpledialog.askinteger(title="Multiple recordings", prompt=msg) - 1 recordings[ind].stop_pause() recordings[ind].finish() else: recordings[0].stop_pause() recordings[0].finish()
def popupInput(s, drzewo): dane = simpledialog.askinteger('Wprowadz dane', s, minvalue=0, maxvalue=999) if s == 'Dodaj': if drzewo.wyszukaj(dane): messagebox.showerror('Error', 'Istnieje juz taki wezel') else: drzewo.dodaj(int(dane)) messagebox.showinfo('Sukces', 'Poprawnie dodano wezel') elif s == 'Usun': if drzewo.wyszukaj(dane): drzewo.usun(int(dane)) messagebox.showinfo('Sukces', 'Poprawnie usunięto wezel') else: messagebox.showerror('Error', 'Nie ma takiego wezla') elif s == 'Wyszukaj': if drzewo.wyszukaj(int(dane)): messagebox.showinfo('Sukces', 'Węzeł znajduje się w drzewie') else: messagebox.showerror('Error', 'Nie ma takiego wezla')
def lanceSimul(fich_select): fich = open(fich_select, "r") dat = fich.readlines() num_simu = float(fich_select[-5]) n = len(dat) #upload du fichier selectionner curlcommande = "curl -X POST -F filename=" + fich_select + " " + addresServ + "/uploadCIFile" process = sb.Popen(curlcommande.split(), stdout=sb.PIPE) output, error = process.communicate() #lancement de la simulation par le serveur Nmax = tks.askinteger("Input", "Combien de point voulez vous ?", parent=root) Tmax = tks.askfloat("Input", "Sur quel interval de temps ?", parent=root) curlcommande = "curl " + addresServ + "/simulation/" + str( Nmax) + "/" + str(Tmax) process = sb.Popen(curlcommande.split(), stdout=sb.PIPE) time.sleep( 3 ) #temps de pausse pour laisser le temps au serve de faire les calculs #creation du fichier de sauvegarde path = "plotdata/" + str(num_simu) os.mkdir(path) #recuperation des fichier for i in range(n): corp = "corp_" + str(1 + i) curlcommande = "curl " + addresServ + "/retourDonnees/" + corp + " --output plotdata/" + str( num_simu) + "/" + corp process = sb.Popen(curlcommande.split(), stdout=sb.PIPE) output, error = process.communicate() ask = message.askyesno("Question", "voulez vous ploter les donné?") if ask: plotSimu(float(num_simu))
def SetTimePopUp(event): correctInput = False dialogString = tk.StringVar() dialogString.set("How much time has passed?") while not correctInput: initialTime = tk.IntVar() initialTime.set(0) timeInteger = simpledialog.askinteger("Set Time",dialogString.get(), initialvalue=initialTime.get()) # check None in case termination with "windows cross" if timeInteger is None: break else: # check validity if timeInteger < 0 or abs(timeInteger) > master.IPTClock.stage.time(): correctInput = False dialogString.set("Insert valid time range!") else: correctInput = True if correctInput: SetStageStartTime(timeInteger)
def get_header_level(z_to_split): Tk().withdraw() zettel_links = get_zettel_links(z_to_split) # Change the list of zettel links into an easily readable string. instructions = 'Zettels found containing \'#split\':\n' for z_link in zettel_links: instructions = instructions + ' * ' + z_link + '\n' instructions = instructions + '\nEnter the header level to split by.' invalid_input = True while invalid_input: header_level = askinteger('Split zettel', instructions) if header_level is None: sys.exit(0) if header_level < 1 or header_level > 6: messagebox.showinfo(title='Split zettel', message='Header level must be within 1-6.') else: invalid_input = False return header_level
def repeat(): title('Repeating') n = simpledialog.askinteger("Ввод", "Количество повторений", parent=root, minvalue=0) if n is not None and len(pressedList) != 0: for j in range(n): ms = mouse.Controller() kb = pynput.keyboard.Controller() for i in range(len(pressedList)): if type(pressedList[i]) is list: pyautogui.moveTo(pressedList[i]) ms.press(mouse.Button.left) ms.release(mouse.Button.left) elif type(pressedList[i]) is float: time.sleep(pressedList[i]) else: kb.press(pressedList[i]) kb.release(pressedList[i]) title(default) else: title(default)
def MakeNewFile(): freq_array = array('f', []) # entries=input("How Many Entries? ") entries = simpledialog.askinteger('entries', 'How many entries?', parent=root) #x<11 #print ("Enter frequencies in Hz, with no decimal points") #fout = open("freq.dat", "a") #while True: for i in range(0, entries): # print i # freq=input("Frequency ") freq = simpledialog.askfloat('entry', 'enter frequency ' + str(i + 1), parent=root) freq_array = array("f", [freq]) #fout.write(freq) # frq=float(freq) with open("freqtest.dat", "ab") as x: # pickle.dump(frq, x)p freq_array.tofile(x) x.close()
def create_rectangle(): global img, edited_image, my_img_string, just_file_name, create_msg create_blank_page() rectangle_pt1 = re.split(regex_pattern, simpledialog.askstring("User Input", "Please Enter Rectangle Point1: x1, y1")) pt1 = (int(rectangle_pt1[0]), int(rectangle_pt1[1])) rectangle_pt2 = re.split(regex_pattern, simpledialog.askstring("User Input", "Please Enter Rectangle Point2: x2, y2")) pt2 = int(rectangle_pt2[0]), int(rectangle_pt2[1]) rectangle_color_string = re.split(regex_pattern, simpledialog.askstring("User Input", "Please Enter Line color in RGB mode: Ex. 255,0,0")) rectangle_color_string.reverse() rectangle_color = tuple([int(i) for i in rectangle_color_string]) rectangle_thickness = simpledialog.askinteger("User Input", "Please Enter rectangle thickness") img = cv2.rectangle(img, pt1, pt2, rectangle_color, rectangle_thickness) edited_image = img my_img_string = "Rectangle" just_file_name = my_img_string labelText.set(my_img_string) create_msg = "Rectangle" messagebox.showinfo("Create Successful", create_msg + " is Created, Click View to See the Image")
def login2(): R = 1 searchname = simpledialog.askstring("name", "Enter The Name") searchid = simpledialog.askinteger("admission no", "Enter The Id") name = searchname.upper() adm = searchid conn = sqlite3.connect('form.db') with conn: cursor = conn.cursor() find_ = ("SELECT * FROM details WHERE name=? AND admno=?") cursor.execute(find_, [(name), (adm)]) resultS = cursor.fetchall() if resultS: for i in resultS: print(R, ".", "ROOM NO:", i[0]) print(" ", "ADM NO:", i[1]) print(" ", "NAME:", i[2]) print(" ", "BRANCH:", i[3]) print(" ", "PLACE:", i[4]) print(" ", "MOB NO:", i[5]) print(" ", "DATE OF GOING:", i[6]) print(" ", "DATE OF COMING:", i[7]) R = R + 1
def show_subject(self, subject): mark_string = "" if subject == 1: mark_string = "Enter mark for Physics" elif subject == 2: mark_string = "Enter mark for Basic Electrical Engineering" else: mark_string = "Enter mark for Mathematics" mark = simpledialog.askinteger("Input", mark_string) if subject == 1: mark1_label = ttk.Label(self, text=mark) mark1_label.grid(row=1, column=2, padx=10, pady=10) app.mark1 = mark elif subject == 2: mark2_label = ttk.Label(self, text=mark) mark2_label.grid(row=2, column=2, padx=10, pady=10) app.mark2 = mark else: mark3_label = ttk.Label(self, text=mark) mark3_label.grid(row=3, column=2, padx=10, pady=10) app.mark3 = mark print(mark)
def take(tk): qf = askopenfile(parent=tk, title='Where is the quizfile?') if not qf: return kf = askopenfile(parent=tk, title='Where is the keyfile?') if not kf: return key = kf.read() quiz = qf.read() kf.close() qf.close() keylist = key.split('\n')[:-2] quizqs = quiz.split('\n\n')[:-1] print(quizqs, keylist) key = keylist quiz = quizqs if len(quiz) != len(key): showerror(title='Quiz', message='The key and quiz files do not match!') return record = [] for (q, a) in zip(quiz, key): useranswer = askinteger('Quiz %s' % quiz.index(q), q) if useranswer == int(a): showinfo('Answer', 'You are correct!') record.append(1) else: showinfo('Answer', 'You\'re wrong. The answer is %s' % a) record.append(0) score = (sum(record) / len(quiz)) * 100 showinfo('Percentage', 'You got %s questions correct!(%s%%)' % (sum(record), score)) rf = None while rf == None: rf = asksaveasfile(parent=tk, title='Where would you like to save your score?') print('%s%%\n%s' % (score, record), file=rf) rf.close()
def sample_dist(*args): nr = simpledialog.askinteger( "Input", "How many random numbers should be sampled? (Max 100000)", parent=root, minvalue=1, maxvalue=100000) rand_nrs = [] if distribution.get() == "Uniform Distribution": try: if a.get() >= b.get(): messagebox.showerror("Error", "Invalid values for a and/or b!") else: for x in range(0, nr): rand_nrs.append(random.uniform(a.get(), b.get())) except: messagebox.showerror("Error", "Invalid values for a and/or b!") elif distribution.get() == "Normal Distribution": try: if sigma.get() <= 0: messagebox.showerror("Error", "Invalid value for sigma!") else: for x in range(0, nr): rand_nrs.append(random.normalvariate( mu.get(), sigma.get())) except: messagebox.showerror("Error", "Invalid value for mu and/or sigma!") elif distribution.get() == "Exponential Distribution": try: if lamb.get() <= 0: messagebox.showerror("Error", "Invalid value for lambda!") else: for x in range(0, nr): rand_nrs.append(random.expovariate(lamb.get())) except: messagebox.showerror("Error", "Invalid value for lambda!") return rand_nrs
def playGameMousePressed(event, data): if data.mode == "playGame" and data.innerMode == None: if data.back[0] < event.x < data.back[0] + data.back[2]*2 and \ data.back[1] < event.y < data.back[1] + data.back[2]: data.mode = "splashScreen" data.timer = 0 data.innerMode = None data.loading = False elif data.width//3 - data.radius < event.x < data.width//3 + data.radius and \ data.height//2 - data.radius < event.y < data.height//2 + data.radius: answer = simpledialog.askinteger("Input", "What level do you want to Play?", parent=data.root, minvalue=1, maxvalue=3) """http://interactivepython.org/runestone/static/thinkcspy/GUIandEventDrivenProgramming/02_standard_dialog_boxes.html""" if answer is not None: data.level = answer if data.level == 1: data.edit = True data.currentBoard = data.boardOne elif data.level == 2: data.edit = True data.currentBoard = data.boardTwo elif data.level == 3: data.edit = True data.currentBoard = data.boardThree data.loading = True data.select = "playWorlds" elif data.width//1.5 - data.radius < event.x < data.width//1.5 + data.radius and \ data.height//2 - data.radius < event.y < data.height//2 + data.radius: data.loading = True data.select = "createWorlds" if (data.innerMode == "playWorlds"): playWorldsMousePressed(event, data) elif (data.innerMode == "createWorlds"): createWorldsMousePressed(event, data)
def on_button_clicked(button_array, button): if not button.hard_set: new_value = simpledialog.askinteger("Enter a value.", "Number between 1-9, 0 to clear", minvalue=0, maxvalue=9) if new_value is not None and new_value != 0: pot_value = structs.PotentialValue(button.row, button.column, button.block, new_value) if isNewValueValid(button_array, pot_value): button.set_value(new_value) else: #calculate why. conflict = utils.find( lambda b: b.row == button.row and b.value == new_value, button_array) if conflict is None: conflict = utils.find( lambda b: b.column == button.column and b.value == new_value, button_array) if conflict is None: conflict = utils.find( lambda b: isButtonInBlock( b, pot_value.row, pot_value.column, get_block_size(button_array)) and b.value == new_value, button_array) assert conflict is not None #there's a major issue in the logic if this hits. messagebox.showwarning( "Value is not valid.", "The value: " + str(new_value) + " is not a valid value for this location, it conflicts with the button's value at (row:" + str(conflict.row + 1) + ", column:" + str(conflict.column + 1) + "). Please try again.") elif new_value == 0: button.set_value(new_value) else: messagebox.showerror("Sudoku Solver", "May not unset initial condition.")
def check_if(r, c): q = simpledialog.askinteger( "input", "please input an integer between 1 and 9 both inclusive") if (crr[r][c] == q): global count arr[r][c] = q update() count = count + 1 var12 = "correct,keep up the good work,current streak =" + str(count) status.set(var12) status_bar.config(borderwidth=3, background="green", foreground="black") elif (q is None): status.set("you forgot to give input ") status_bar.config(borderwidth=3, background="pink", foreground="black") elif (q > 9): messagebox.showerror("Error", "your input was greater than 9") elif (q < 1): messagebox.showerror("Error", "your input was less than 1") else: count = 0 status.set("Incorrect,come on have 1 more try") status_bar.config(borderwidth=3, background="red", foreground="white")
def remove_entry_by_id(event): flagged_id = sd.askinteger("DELETE ENTRY", "Enter the Question ID:") if flagged_id != None: record = get_record_by_id(flagged_id) if record == None: mb.showwarning( APP_TITLE, "No results found, please check the id and enter again.") else: answer = mb.askyesno( APP_TITLE + ": CAUTION", f""" Are you sure you want to remove the record? Question: {record[1]} Correct Answer: {record[2]} Wrong Answer #1: {record[3]} Wrong Answer #2: {record[4]} Wrong Answer #3: {record[5]} Press YES to continue. """) if answer: remove_record(flagged_id) mb.showinfo(APP_TITLE, "Successfully deleted.") update_entry_count()
def shrink_size(): global directory # check if user has not selected a folder location if directory is "": messagebox.showerror(title="Error!", message="No folder has been selected!") return else: # a folder location has been selected result = check4images() # checks if folder has images if result is False: return else: # folder has images so ask user for resize percentage! # ask for percentage reduction in image dimensions reduction_percentage = simpledialog.askinteger(title="Reduce All Image Dimensions By...", prompt="Enter a whole number for the percentage you wish to"+\ " reduce all image's size by:") # check to make sure user input is valid: False = not valid, True = valid valid_int = check_reduction(reduction_percentage) if valid_int is True: # ask user for confirmation of reduction_percentage ask4confirmation = messagebox.askyesno( title="Confirmation", message="Reduce all images' size by {}%?".format( reduction_percentage), icon="question") if ask4confirmation is True: # do the resizing w/ reduction_percentage if ask4confirmation is yes resize_it(reduction_percentage) # give user confirmation messagebox.showinfo(title="Success!", message="Images have been resized!") cur_progress.set(0) select_button["state"] = ACTIVE resize_button["state"] = ACTIVE status["text"] = "Select a folder." directory = "" # wipe folder location
def new_scene(self): for widget in self.winfo_children(): widget.destroy() self.init_UI() self.editor_type = 'scene' # filetypes = [('all files', '.*'), ('yamls', '.yaml')] # savepath = filedialog.asksaveasfilename(parent=self, # initialdir='../game/data/', # title="Please select a file to save the scene:") if self.current_scene is not None and self.current_paint_stroke > 0: response = messagebox.askyesno('Discard Changes?', '''If you create a new scene now, your existing changes will be discarded. Do you really want to discard these changes?''') if not response: return name = simpledialog.askstring('Name', 'What is the name of the new scene?', parent=self) length = simpledialog.askfloat('Length', 'How long will the scene be, in meters?', parent=self) width = simpledialog.askfloat('Width', 'How wide will the scene be, in meters?', parent=self) self.grid_size = simpledialog.askinteger('Grid Size', 'How many centimeters per grid?', parent=self, initialvalue=100, minvalue=1) length *= self.grid_size width *= self.grid_size length = round(length) width = round(width) self.bitmap = np.zeros((length, width, 4), dtype=np.uint8) self.build_canvas(length*self.scaling_factor, width*self.scaling_factor) # img = ImageTk.PhotoImage(image=Image.fromarray(self.current_scene.layout)) # self.scene_view.create_image((0, 0), anchor='nw', image=img) self.build_left_materials_notebook() self.build_left_objects_notebook() self.build_left_materials() self.build_right_materials_notebook() self.build_right_objects_notebook() self.build_right_materials() self.build_right_objects() self.build_bottom_bar()
def open_file_to_train(self): start = time.time() path: list[str] = filedialog.askopenfilenames(parent=self, title="Choose a file") birads_type: int = simpledialog.askinteger("Input", "What's the BIRADS type?", parent=self) images: list[str] = [] for file in path: if (file.find(".png") != -1): images.append(file) shuffle(images) list_portion_number: int = math.ceil(len(images) * 0.75) data_store: list[str] = images[0:list_portion_number] no_store: list[str] = images[list_portion_number:len(path)] image_characteristics = [] for image in data_store: md = MainDescribe(birads_type, path=image) image_characteristics = image_characteristics + md.generate_characteristics( ) csv_data = CsvUtil("{}_calculated.csv".format(birads_type), [ "id", "name", "resolution", "tones", "radius", "direction_vertical", "direction_horizontal", "homogeneity", "entropy", "contrast" ]) csv_nodata = CsvUtil("{}_ignored.csv".format(birads_type), ["name"]) csv_data.write_dict(image_characteristics) csv_nodata.write_str_list(no_store) print("done!") end = time.time() print("Tempo de execução para crianção de métricas: {}".format( end - start, ".2f"))
def median_filter(): # for median filtered image global oimg, mimg if len(oimg): kernel = simpledialog.askinteger("Input", "Enter Kernel Value for Median Blur", minvalue=1, initialvalue=5) if kernel and kernel % 2 == 1: mimg = cv2.medianBlur(oimg, kernel) cv2.imwrite('images/runtime-images/cv2out.png', mimg) update_modified_image() elif kernel: show_error( "Error", "Kernel value can only be positive odd interger.\ \nUsing Default Kernel value: 5") kernel = 5 mimg = cv2.medianBlur(oimg, kernel) cv2.imwrite('images/runtime-images/cv2out.png', mimg) update_modified_image() else: return else: show_error("Error", "Please open an image first.")
def encrypt_window(message): global key_encrypt key_encrypt = askinteger('Enter Integer', 'Please enter an integer') def encrypt(message, key_encrypt): encrypted_message = '' original_message = message # this key is used for shifting of alphabets. # below is the algorithm for encryption of message. for x in original_message: if x in alphabets: index = alphabets.find(x) new_position = (key_encrypt + index) % 26 encrypted_character = alphabets[new_position] encrypted_message += encrypted_character else: encrypted_message += x new_master = Tk() Label(new_master, text="Your Encrypted Message is:\n").grid(row=3) Label(new_master, text=encrypted_message).grid(row=4) encrypt(message, key_encrypt)
def init_filelist_listbox(self): self.set_info('初始化视频列表...') global video_list if not os.path.exists(conf_path + 'video_list.txt'): self.set_info('正在创建视频列表...') global work_path global DEEP work_path = filedialog.askdirectory(title='选择视频跟目录') if work_path == '': raise Exception('work_path must be seleted') DEEP = int( simpledialog.askinteger('视频目录:' + work_path, '请输入视频目录最大深度')) print(DEEP) new_video_list(self) file = open(conf_path + 'video_list.txt', 'r', encoding='utf-8') content = file.read().strip() file.close() video_list = content.split('\n') self.search() if video_list[0] == '': self.set_info('已加载{}个视频'.format(0)) else: self.set_info('已加载{}个视频'.format(len(video_list)))
def start(): global train_dataset_len, train_dim, class_number, X, y, NN test_size = simpledialog.askfloat( "Set test size", "Input the test size(0 ~ 0.9), which means the size of samples used to test model's accuracy: ", initialvalue=0.2, minvalue=0, maxvalue=0.9) test_samples = int(train_dataset_len) * test_size train_samples = train_dataset_len - test_samples info_label[ "text"] = "Train Data Size: %6d\nTest Data Size: %6d" % ( train_samples, test_samples) epoch = simpledialog.askinteger( "Set Epoch", "Input the Epochs(0~INF), which mean the iteration of training: ", initialvalue=8, minvalue=1) max_value = np.max(X) print(max_value) with open("max_value.txt", 'w') as f: f.write(str(max_value)) X = X / max_value X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size) NN = NeuralNetework() NN.create_model(train_dim, class_number) y_train = to_categorical(y_train) y_test = to_categorical(y_test) NN.train(X_train, y_train, X_test, y_test, epochs=epoch, batch_size=1) print( "\nFinished Model Training! Press 'Save Model' Button to save this model.\n" )
def myy(self,x1,x2,x3): conn = sqlite3.connect('master.db') c = conn.cursor() if x1==1: answer = simpledialog.askinteger("Input", "Enter the Quantity",minvalue=1, maxvalue=100) if answer is None: self.destroy else: def select_my_table(answer,item_x,cd): c.execute("SELECT Sub_r_name,Pr_id,Sub_pr_id FROM sub_product_id WHERE Sub_pr_id = (?) AND Pr_id = (?)",(item_x,cd)) data = c.fetchone() c.execute("SELECT SP,Tax FROM pr_price WHERE Sub_pr_id = (?) AND Tax > (?)",(item_x,0)) data_2 = c.fetchall() conn.commit() tree = ttk.Treeview(self,columns = Mainwindow.heading,show = 'headings') vsb = ttk.Scrollbar(orient="vertical",command=tree.yview) tree.configure(yscrollcommand=vsb.set) tree.place(x=950,y=200,height=230,width=340) vsb.place(x=1290,y=200,height=230) self.recall(data,data_2,tree,answer) select_my_table(answer,x2,x3) c.close() conn.close()
def onCountdownSec(self, event): secs = askinteger('Countdown', 'Seconds?') if secs: self.countdownSeconds = secs
def onCountdownMin(self, event): secs = askinteger('Countdown', 'Minutes') if secs: self.countdownSeconds = secs * 60
from tkinter import simpledialog, Tk, messagebox import math # Write a Python program that asks the user for the radius of a circle. # Next, ask the user if they would like to calculate the area or circumference of a circle. # If they choose area, display the area of the circle using the radius. # Otherwise, display the circumference of the circle using the radius. if __name__ == '__main__': window = Tk() window.withdraw() radius = simpledialog.askinteger('Radius', 'Please enter a radius for your circle') input = simpledialog.askstring('Area or Circumference', 'Would you like the area or circumference?') if input.lower() == 'area': calculation = radius*radius*math.pi messagebox.showinfo('Area', 'The area is ' + str(calculation)) elif input.lower() == 'circumference': calculation = 2*math.pi*radius messagebox.showinfo('Circumference', 'The circumference is ' + str(calculation)) else: messagebox.showerror('Option Not Found', "Sorry, I don't understand")