def before_write_instru_info(self, instru_info: InstruInfoComponent): super().before_write_instru_info(instru_info) root = Tk() root.withdraw() name = simpledialog.askstring("Action", "Enter NDAR instrument name (without version and not case sensitive)") version = simpledialog.askstring("Action", "Enter NDAR instrument version") respondent = simpledialog.askstring("Action", "Enter the respondent for this instrument. (e.g, twin, cotwin)") if name is not None: # No input check right now name = name.lower() instru_info.instru_info.instru_name = name self.instru_info.instru_name = name if version is not None: # A '0' is added to the version string because NDAR requires # single digit versions numbers to have a leading '0' if len(version) == 1: version = "0" + version instru_info.instru_info.version = version self.instru_info.version = version if respondent is not None: instru_info.instru_info.respondent = respondent self.instru_info.respondent = respondent root.destroy()
def CheckServiceAvailability_Button(self): 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?") CheckServiceAvailabilityInstance = CheckServiceAvailability(Input_Date_value, Input_Time_value, InputService_value) CheckServiceAvailabilityInstance.Check()
def DislayAvailableService_Button(self): # Input the information Input_Date_value = simpledialog.askstring("test","Please enter date: ") Input_StartTime_value = simpledialog.askstring("test","Please enter start time: ") AS = AvailableService(Input_Date_value, Input_StartTime_value) AS.Check()
def add_extra_content_to_data_table(self, data_table): # Read in multiple data tables data_table_names = [] # while True: # data_table_name = input("Which database tables are you going to pull data from (press Enter to end): ") # if data_table_name == "": # break # data_table_names.append(data_table_name) root = Tk() root.withdraw() data_table_name = simpledialog.askstring("Action", "Add datatable name for this template. Press cancel to end inputting") while True: if data_table_name is None: break data_table_names.append(data_table_name) data_table_name = simpledialog.askstring("Action", "Add another datatable name for this template. Press cancel to end inputting") root.destroy() content = ["", data_table.DATA_TABLE_KEY] + data_table_names data_table.content.append(content) self.source.data_table_names = data_table_names
def setMultiplayer(): global gameTypeAi, client, playersTurn, oppositePlayer gameTypeAi = False root = Tk() root.withdraw() root.resizable(0,0) #Ask the user for an ip address and a port, if blank set to 'localhost' and '12345' ip = str(sd.askstring("IP Address", "Enter the ip address you want to connect to")) port1 = sd.askstring("Port Number", "Enter the port number you want to connect to") if (ip == ""): ip = 'localhost' if (port1 == ""): port1 = 12345 #Server Connections client = socket.socket() port = int(port1) client.connect((ip, port)) #Receive a message from the server defining which player you are 'X' or 'O' assign = client.recv(1024) assign = assign.decode('utf-8').rstrip('\r\n') if assign == "X": playersTurn = "X" oppositePlayer = "O" elif assign == "O": playersTurn = "O" oppositePlayer = "X" print("You are player " + playersTurn) header.configure(text="Tic Tac Toe\nYou are player " + playersTurn) #'X' goes first to if you are 'O' the you have to wait by going straight to the recMove function if playersTurn == "O": recMove()
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 make_widgets(self): MLabel(self, text='简单对话框演示') self.label = MLabel(self, text='等待测试...') MButton(self, text="输入字符串", command=lambda: self.print_result(simpledialog.askstring('Input', 'Your name: '))) MButton(self, text="输入整数", command=lambda: self.print_result(simpledialog.askstring('Input', 'Your age: '))) MButton(self, text="输入浮点数", command=lambda: self.print_result(simpledialog.askstring('Input', 'Your height: ')))
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 getPassword(prompt = '', confirm = 0): while 1: try1 = tkSimpleDialog.askstring('Password Dialog', prompt, show='*') if not confirm: return try1 try2 = tkSimpleDialog.askstring('Password Dialog', 'Confirm Password', show='*') if try1 == try2: return try1 else: tkMessageBox.showerror('Password Mismatch', 'Passwords did not match, starting over')
def go_to_lilis_parsing(self): """how many artist do you want to parse""" number_from = simpledialog.askstring('Number', 'How many artists?/FROM') if number_from is not None: number_from = int(number_from) print(number_from) number_to = int(simpledialog.askstring('Number', 'How many artists?/TO')) if number_to is not None: number_to = int(number_to) print(number_to) self.db_creator.parse_file(number_to, number_from)
def saveas_command(p): new_target = filedialog.asksaveasfilename(defaultextension='.etxt', filetypes=[(s_Document, '*.etxt'),], title=s_MenuFileSave) if not new_target: return p.password = None pw1, pw2 = 1, 2 while pw1 != pw2: pw1 = simpledialog.askstring("Passphrase", s_AskPassword+s_Password, show='*') # Annulla il loop con la prima pw vuota if pw1 == '': return pw2 = simpledialog.askstring("Passphrase", s_RepeatPassword+s_Password, show='*') p.password = pw1 p.target_etxt = new_target p.save_command()
def add_Sheet(self, sheetname=None, sheetdata=None): """Add a new sheet - handles all the table creation stuff""" def checksheet_name(name): if name == '': messagebox.showwarning("Whoops", "Name should not be blank.") return 0 if name in self.sheets: messagebox.showwarning("Name exists", "Sheet name already exists!") return 0 names = [self.notebook.tab(i, "text") for i in self.notebook.tabs()] noshts = len(names) if sheetname == None: sheetname = simpledialog.askstring("New sheet name?", "Enter sheet name:", initialvalue='sheet'+str(noshts+1)) checksheet_name(sheetname) page = Frame(self.notebook) self.notebook.add(page, text=sheetname) #Create the table and model if data present if sheetdata != None: model = TableModel(sheetdata) self.currenttable = MyTable(page, model) else: self.currenttable = MyTable(page) #Load preferences into table self.currenttable.loadPrefs(self.preferences) #This handles all the canvas and header in the frame passed to constructor self.currenttable.createTableFrame() #add the table to the sheet dict self.sheets[sheetname] = self.currenttable self.saved = 0 return sheetname
def do_edit_link (self, tag): """ effective procedure for editing a relationship link label; """ # param controls if self.TAG_RADIX_LINK in tag: # inits _group = self.canvas_groups[tag] _text_id = _group["text"] _name0 = self.get_name_from_tag(_group["tag0"]) _name1 = self.get_name_from_tag(_group["tag1"]) # get new text _new_text = SD.askstring( _("Characters relationship"), _("Relationship '{from_name}' <---> '{to_name}'") .format(from_name=_name0, to_name=_name1), initialvalue=self.itemcget(_text_id, "text"), parent=self, ) # got something? if _new_text: # update label self.update_label(_group, text=_new_text) # update canvas self.update_canvas()
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 getid(self, event): if not self.br_state: return self.id_input_status=True pid = simpledialog.askstring('员工编号','请输入8位ID') if pid is None or len(pid)==0: return try: card_id=EmployeeCardInfo.get((EmployeeCardInfo.employee==pid)&(EmployeeCardInfo.is_active==True)).card self.card_id.set(card_id) except EmployeeCardInfo.DoesNotExist: self.card_id.set('None') #messagebox.showwarning("提示", "数据库中没有阁下的ID card的记录,请通知管理员添加") try: employee_line= Employee.get(Employee.employee==pid) self.num_counter=30 self.c_status=True except Employee.DoesNotExist: self.c_status=False self.card_id.set("") self.employee_info.set("") self.s_user="" messagebox.showerror("错误", "数据库中无阁下相关信息,请通知管理员增加人员信息") return self.id_input_status=False self.s_user=employee_line.employee+"-"+employee_line.name self.employee_info.set(self.s_user)
def create_room(self): """ Shows dialog and creates a new room with provided name. """ room_name = askstring("Create room", "New room name:") if room_name: super(MainApplication, self).create_room(room_name)
def ImportPortfolio(): """File -> Portfolio Read the portfolio from a file""" with open(PORTFOLIO, 'w') as f: portfolio = GetPortfolio() keys = portfolio.keys() count = 1 for stock in sorted(keys): if portfolio[stock]['units'] > 0.1: found = False while not found: symbol = askstring('Symbols', '(%d/%d) Enter symbol for:\n%s' % \ (count, len(keys), stock)) if symbol != None: price = GetPriceForSymbol(symbol) if price > 0.0: if askyesno(symbol, 'Is %.2f correct?' % (price * 0.01)): scaling = 0.01 else: scaling = 1.0 f.write(Stock(symbol, stock, 'TICKER', 0.01, 0.00, '20130811202000', scaling ).ToCSV()) found = True else: if not askretrycancel('Symbols', 'Cannot find symbol %s' % \ symbol): found = False else: found = True count += 1
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 setCLCWcallback(self): """Called when the SetCLCW menu entry is selected""" clcwStr = simpledialog.askstring(title="CLCW Dialog", prompt="CLCW Report Value (0...255):", initialvalue="0") if clcwStr != None: self.notifyModelTask(["SETCLCW", clcwStr])
def change_name_dialog(self,*args): new_name = tksimpledialog.askstring("rename collection",self.collection.name) if new_name: # make sure new name isn't already in use/won't interfere with sequence creation split_name = new_name.split("_") if len(split_name) > 1: check_name = "_".join(split_name[:-1]) else: check_name = new_name if check_name in self.mainframe.collections: if tkmessagebox.showwarning(">:(","name is already in use, please try again"): self.change_name_dialog() else: # remove old collection old_name = self.collection.name if old_name in self.mainframe.collections: del self.mainframe.collections[old_name] self.mainframe.searcher.col_index.remove_word(old_name) # change name self.collection.name = new_name self.collection_label.configure(text=new_name) # add new collection self.mainframe.collections[new_name] = self.collection self.mainframe.searcher.col_index.add_word(new_name) self.mainframe.cat_needs_refresh = True self.mainframe.collection_tab.tree_reset() self.check_next_prev()
def menuMessage(self, event=None): # Dialog box asking for date, and then print the epoch in the text filename date = str(simpledialog.askstring("Special Message", "How long would you like the message to remain on the home page?\n(Please type a date in this exact format: 'June 3, 2016').")) if date == 'None': pass else: try: pattern = '%B %d, %Y' epoch = int(time.mktime(time.strptime(date, pattern))) filename = 'message{}.txt'.format(epoch) # Get rid of previous message text files for file in glob.glob("message*.txt"): os.remove(file) # Open the new text file in Notepad with boilerplate instructions already inserted file = open(filename, 'a') file.write( '<!--\n\nType the HTML code for your message below, and then save and close the text file.\n' 'The message will appear above the upcoming movies next time you update the website,\n' 'and will remain there until the date you specified.\n\n' '(These instructions will not appear on the website.)\n\n-->') file.close() os.system('start '+filename) except: self.wrongFormat()
def 標記取代(self,event=None): """ 抓取所選取範圍的單字並默認其為查詢的預設字 根據使用者輸入字串查詢目前游標所在的文件區塊 將查詢結果全部標記 文件區根據目前焦點決定(都沒有則為文件區1) """ focused_on = self.root.focus_get() 文字區= "文件區1" if focused_on == self.text else "文件區2" if focused_on != self.text and focused_on != self.text2: focused_on = self.text 文字區= "文件區1" target = askstring('取代...', '將標記取代為?',initialvalue="變數名") 記數=0 if target != None: 標記範圍= focused_on.tag_ranges("查詢字") for i in range(len(標記範圍)-1,0,-2): 記數+=1 focused_on.delete(標記範圍[i-1],標記範圍[i]) focused_on.insert(標記範圍[i-1],target) endpos=str(標記範圍[i-1])+'+%dc' % len(target) # print(endpos) focused_on.tag_add("查詢字", 標記範圍[i-1],endpos ) focused_on.tag_config("查詢字", background="yellow", foreground="blue") if 記數!= 0: messagebox.showinfo('取代...','總共取代為 %s 共有 %d 個'%(target,記數)) self.輸出結果.config(text="%s將標記字串取代為%s"%(文字區,target),fg= "black") else: self.輸出結果.config(text="%s無要取代的文字"%(文字區),fg= "black")
def savePreset(main, filename=None): if filename is None: root = Tk() root.withdraw() filename = simpledialog.askstring(title='Save preset', prompt='Save config file as...') root.destroy() if filename is None: return config = configparser.ConfigParser() fov = 'Field of view' config['Camera'] = { 'Frame Start': main.frameStart, 'Shape': main.shape, 'Shape name': main.tree.p.param(fov).param('Shape').value(), 'Horizontal readout rate': str(main.HRRatePar.value()), 'Vertical shift speed': str(main.vertShiftSpeedPar.value()), 'Clock voltage amplitude': str(main.vertShiftAmpPar.value()), 'Frame Transfer Mode': str(main.FTMPar.value()), 'Cropped sensor mode': str(main.cropParam.value()), 'Set exposure time': str(main.expPar.value()), 'Pre-amp gain': str(main.PreGainPar.value()), 'EM gain': str(main.GainPar.value())} with open(os.path.join(main.presetDir, filename), 'w') as configfile: config.write(configfile) main.presetsMenu.addItem(filename)
def sess(*_): global COOKIES cookiestr = simpledialog.askstring("导入Cookie", "请输入以分号分隔的Cookie字符串:") COOKIES = {x.partition("=")[0]: x.partition("=")[2] for x in cookiestr.split(";") if x} for w in workers.values(): w.cookies = COOKIES w.update_cookies()
def __DoSearch(self): """this is callback method of menu 'search for'. it pops upa dialog to let you input the keyword. """ mystr = askstring("search for","please enter one keyword:") if mystr: self.__temp = mystr if self.__countofLefttree <=0: self.__astr.set("there is no item listed in the libs view.please check.") return threads=[] mutex = threading.Lock() for i in self.lf.treeView.get_children(): filename = os.path.join(self.__workdir,self.lf.treeView.item(i,'text')) thread = MultipleSearch(mutex,filename,mystr) thread.start() threads.append(thread) for thread in threads: thread.join() output = 'trying to search for \'' + mystr + '\':\r\n' mystr = '' for i in threads: (fn,count) = i.ShowResult() (fd,name)= os.path.split(fn) if count>0: mystr += 'in file \'' + os.path.join(os.path.abspath(fd), name) + '\', ' + str(count) + ' hits.\r\n' if mystr=='': mystr = 'there is no hit.\r\n' output+=mystr self.__lt.config(state = NORMAL) self.__lt.delete('1.0',END) self.__lt.insert('1.0',output) self.__lt.config(state=DISABLED)
def manifestName(self): self.manifestNamePattern = simpledialog.askstring(_("Archive manifest file name pattern"), _("Provide non-standard archive manifest file name pattern (e.g., *taxonomyPackage.xml). \n" "Uses unix file name pattern matching. \n" "Multiple manifest files are supported in archive (such as oasis catalogs). \n" "(If blank, search for either .taxonomyPackage.xml or catalog.xml). "), initialvalue=self.manifestNamePattern, parent=self)
def save(self, event): f = simpledialog.askstring("Save", "filename") if not f: return getnum = lambda k: int(list(filter(None, re.findall("\d*", self.canvas.gettags(k)[0])))[0]) positions = {getnum(k): self.canvas.coords(k) for k in self.canvas.find_withtag("node_oval")} with open(f, "w") as fl: pprint([self.connections, self.nodes, positions], fl, indent=2)
def finish(): answer = messagebox.askyesno("Quiting ","are you sure yaar quit mat karo bhai bhut mehnat kiya hai") if answer == True: name = simpledialog.askstring("BYe!","Please enter your name") if name is None or name == "": name = "Userjee" messagebox.showinfo("BYE","have a good day"+name) root.destroy()
def onSaveAs(self, forcefile=None): filename = forcefile or self.my_asksaveasfilename() if not filename: return text = self.getAllText() encpick = None # even if read/inserted as bytes # try known encoding at latest Open or Save, if any if self.knownEncoding and ( # enc known? (forcefile and self.savesUseKnownEncoding >= 1) or # on Save? (not forcefile and self.savesUseKnownEncoding >= 2)): # on SaveAs? try: text.encode(self.knownEncoding) encpick = self.knownEncoding except UnicodeError: pass if not encpick and self.savesAskUser: self.update() # else dialog doesn't appear in rare cases askuser = askstring('SimpleEditor', 'Enter Unicode encoding for save', initialvalue=(self.knownEncoding or self.savesEncoding or sys.getdefaultencoding() or '')) if askuser: try: text.encode(askuser) encpick = askuser except (UnicodeError, LookupError): # LookupError: bad name pass if not encpick and self.savesEncoding: try: text.encode(self.savesEncoding) encpick = self.savesEncoding except (UnicodeError, LookupError): pass # try platform default (utf8 on windows) if not encpick: try: text.encode(sys.getdefaultencoding()) encpick = sys.getdefaultencoding() except (UnicodeError, LookupError): pass if not encpick: showerror('SimpleEditor', 'Could not encode for file ' + filename) else: try: file = open(filename, 'w', encoding=encpick) file.write(text) file.close() except: showerror('SimpleEditor', 'Could not write file ' + filename) else: self.setFileName(filename) self.text.edit_modified(0) self.knownEncoding = encpick
def onOpen(self, loadFirst='', loadEncode=''): if self.text_edit_modified(): if not askyesno('SimpleEditor', 'Text has changed: discard changes?'): return file = loadFirst or self.my_askopenfilename() if not file: return if not os.path.isfile(file): showerror('SimpleEditor', 'Could not open file ' + file) return text = None if loadEncode: try: text = open(file, 'r', encoding=loadEncode).read() self.knownEncoding = loadEncode except (UnicodeError, LookupError, IOError): # lookup: bad name pass if text == None and self.opensAskUser: self.update() # else dialog doesn't appear in rare cases askuser = askstring('SimpleEditor', 'Enter Unicode encoding for open', initialvalue=(self.opensEncoding or sys.getdefaultencoding() or '')) if askuser: try: text = open(file, 'r', encoding=askuser).read() self.knownEncoding = askuser except (UnicodeError, LookupError, IOError): pass if text == None and self.opensEncoding: try: text = open(file, 'r', encoding=self.opensEncoding).read() self.knownEncoding = self.opensEncoding except (UnicodeError, LookupError, IOError): pass if text == None: try: text = open(file, 'r', encoding=sys.getdefaultencoding()).read() self.knownEncoding = sys.getdefaultencoding() except (UnicodeError, LookupError, IOError): pass if text == None: try: text = open(file, 'rb').read() text = text.replace(b'\r\n', b'\n') self.knownEncoding = None except IOError: pass if text == None: showerror('SimpleEditor', 'Could not decode and open file ' + file) else: self.setAllText(text) self.setFileName(file) self.text.edit_reset() self.text.edit_modified(0)
import turtle from tkinter import messagebox, simpledialog, Tk import math # Goal: Write a Python program that asks the user for the radius # of a circle and displays the area of that circle. # The formula for the area of a circle is πr^2. # See example image in package to check your output. if __name__ == '__main__': window = Tk() window.withdraw() # Ask the user for the radius in pixels and store it in a variable # simpledialog.askinteger() radi = simpledialog.askstring(title='Greeter', prompt="What do you want the radius to be") # Make a new turtle isaac = turtle.Turtle() # Have your turtle draw a circle with the correct radius # my_turtle.circle() isaac.circle(radius=int(radi), extent=360, steps=100) # Call the turtle .penup() method isaac.penup() # Move your turtle to a new x,y position using .goto() isaac.goto(10, 10) # Calculate the area of your circle and store it in a variable, you can use math.pi radii = int(radi) area = math.pi * radii * radii # Write the area of your circle using the turtle .write() method # myTurtle.write(arg="area = " + str(area), move=True, align='left', font=('Arial',8,'normal')) isaac.write(arg="area = " + str(area),
def ValidIPSubNetPair(ipAddress, subnetMask, line, tkinter_object): """ Given a full IPV4 Address and a subnet, this function compares the two and makes sure they are a valid pairing. The user is prompted for input when correcting some errors :param ipAddress: string :param subnetMask: string :param line: a list containing a single string which is the line being read :param tkinter_object: used to gather input through a gui :return: bool representing if the pairing is valid. False prevents line from being written in main """ try: IpOctetes = ipAddress.split('.') SubnetOctetes = subnetMask.split('.') if (len(IpOctetes) != 4 or len(SubnetOctetes) != 4): print("invalid arg provided to IP verifier") return False else: for index in range(len(SubnetOctetes) - 1, -1, -1): if (int(SubnetOctetes[index]) == 0 and int(IpOctetes[index]) != 0): print("Error: Octete", index + 1, "in IP should be 0, not", IpOctetes[index]) # use index to find correct period for index for changing octete to zero newIP = "" if index == 3: # octete 4 newIP = ipAddress[0:findNth(ipAddress, ".", 3) + 1] + "0" elif index == 2: # octete 3 prevP = findNth(ipAddress, ".", 2) # start of octete 3 nextP = findNth(ipAddress, ".", 3) # end of octete 3 newIP = ipAddress[0:prevP + 1] + "0" + ipAddress[nextP:] elif index == 1: # octete 2 prevP = findNth(ipAddress, ".", 1) # start of octete 2 nextP = findNth(ipAddress, ".", 2) # end of octete 2 newIP = ipAddress[0:prevP + 1] + "0" + ipAddress[ nextP:] # update line else: # octete 1 nextP = findNth(ipAddress, ".", 1) # end of octete 1 newIP = "0" + ipAddress[nextP:] # update line line[0] = line[0].replace(ipAddress, newIP) IpOctetes[index] = "0" # update octete list ipAddress = newIP #return False if (int(SubnetOctetes[index]) == 254 or int(SubnetOctetes[index]) == 255): continue # subnets 31 and 32 are okay be default, no check needed if (int(SubnetOctetes[index]) != 0): # print(SubnetOctetes[index]) if (OcteteComparer(int(IpOctetes[index]), int(SubnetOctetes[index]), line) ): # continue if no errors detected, else return false continue else: print( "\nInvalid IP subnet pair detected on the line: ", line[0]) error_str = "Invalid IP subnet pair detected on the line: \n" + line[ 0] + "\n" + "type 1 to edit IP, 2 to edit subnet, or any other number to delete line: " userChoice = simpledialog.askinteger( "Modify IP/subnet pair", error_str, parent=tkinter_object) if (userChoice == 1): # edit IP ip_str = "input the new ip in the format of 4 octetes seperated by periods.\n Current line: " + line[ 0] new_ip = simpledialog.askstring( "Modify IP/subnet pair", ip_str, parent=tkinter_object) line[0] = line[0].replace( ipAddress, new_ip) # swap in new ip for old ip return True elif (userChoice == 2): # edit subnet sub_str = "input the new subnet in the format of 4 octetes seperated by periods.\n Current line: " + line[ 0] new_subnet = simpledialog.askstring( "Modify IP/subnet pair", sub_str, parent=tkinter_object) line[0] = line[0].replace( subnetMask, new_subnet) # swap in new ip for old ip return True return False return True except: print("\nError in ValidIPSubNetPair function")
print(filename) if filename.endswith('0.bmp'): source_image_path = os.path.join(source_path, filename) img = cv2.imread(source_image_path) #move below source_image_path to enable file location elsewhere than main rect = crop.cropping_points2(img) print(rect) if not np.any(rect): print('no save') os.remove(source_image_path) continue # print(rect) small_image = transform.image_transform(img, dest_path, rect) # print(small_image_path) # cv2.imshow('small' , small_image) answer = simpledialog.askstring("Input", "1: OK\n 2:Seaweed \n 3: Other issue\n 4: Faulty cropping-dont save\n 5:Quit", parent=application_window) if answer == '5': exit() elif answer == '4': continue # cv2.waitKey(0) small_image_name = filename[0:14]+'.'+answer+'.jpg' small_image_path = os.path.join(dest_path, small_image_name) os.remove(source_image_path) print(small_image_path) print('source: ', source_image_path) cv2.imshow('small' , small_image) cv2.imwrite(small_image_path, small_image) cv2.destroyAllWindows()
def wrongId(): print('Wrong input.') sd.messagebox.showerror('Error', 'Wrong operation id') return def exitProg(): global work work = False uData = {'Operation': 'exit'} sendData(uData) sock.close() return def sendData(data): sock.send(json.dumps(data).encode()) data = sock.recv(1024) sd.messagebox.showinfo('Status', data.decode()) while work: print( 'Select operation: 1 - add, 2 - remove, 3 - change password, 4 - exit program' ) operationId = sd.askstring( "Select operation:", " 1 - add, 2 - remove, 3 - change password, 4 - exit program") operation = {'1': addUser, '2': removeUser, '3': changePass, '4': exitProg} operation.get(operationId, wrongId)()
def getUserInput(app, prompt): return simpledialog.askstring('getUserInput', prompt)
line = line.rstrip('\n') country, city = line.split('/') the_world[country] = city def write_to_file(country_name, city_name): with open('country_data.txt', 'a') as file: file.write('\n' + country_name + '/' + city_name) print('Ask the Expert = Capital Cities of the World') root = Tk() root.withdraw() the_world = {} read_from_file() while True: query_country = simpledialog.askstring('Country', 'Type the name of a country:') if query_country in the_world: results = the_world[query_country] messagebox.showinfo('Answer', 'The capital city of ' + query_country + ' is ' + results + '!') else: new_city = simpledialog.askstring('Teach me ', 'I don\'t know! ' + 'What is the capital city of ' + query_country + '?') the_world[query_country] = new_city write_to_file(query_country, new_city) root.mainloop()
def user_message(): message = simpledialog.askstring("Message", "Enter the message: ") return message
def consultarAlbum(self): nomeAlbum = simpledialog.askstring("Input", "Nome do Album: ", parent=self.root) self.ctrlAlbum.consultarAlbuns(nomeAlbum)
def consultarPlaylist(self): nomePlaylist = simpledialog.askstring("Input", "Nome da Playlist: ", parent=self.root) self.ctrlPlaylist.consultarPlaylists(nomePlaylist)
def findInFile(): findString = simpledialog.askstring("Find", "Enter Text")
def input(self, prompt, response): response.put(simpledialog.askstring(self.title(), prompt, parent=self))
def key(event): global root global img_list global img_index global photo_img global label_img global list_ids global w_canvas root.unbind_all('<Key>') img_path = img_list[img_index] if event.char in ('n', 'p'): if event.char == 'n': img_index = img_index+1 elif event.char == 'p': img_index = img_index-1 img_index = img_index % (len(img_list)-1) # display gt image # change canvas img_path = img_list[img_index] root.wm_title(img_path) img = Image.open(img_path) photo_img = ImageTk.PhotoImage(img) label_img.configure(image=photo_img) label_img.image = photo_img # checkPalette w_canvas.delete('all') displayLabels(img) if event.char in ('c','d','g','s'): if event.char == 'c': img_path = str.replace(img_path, 'gt', 'image') if event.char == 'd': img_path = str.replace(img_path, 'gt', 'depth') if event.char == 's': img_path = str.replace(img_path, 'gt', 'scribbles') root.wm_title(img_path) img = Image.open(img_path) photo_img = ImageTk.PhotoImage(img) label_img.configure(image=photo_img) label_img.image = photo_img if event.char == 'q': root.quit() exit() if event.char == 'x': old_index = simpledialog.askstring('Exchange color index', 'Color index to be changed: ') new_index = simpledialog.askstring('Exchange color index', str(old_index) + ' -> ') img = Image.open(img_path) img_indexed = np.array(img) img_indexed[np.where(img_indexed == int(old_index))] = int(new_index) # np.place(img_indexed, img_indexed==old_index, [new_index]) # img_indexed[img_indexed == old_index] = new_index img_new = Image.fromarray(img_indexed) img_new.putpalette(palette) photo_img = ImageTk.PhotoImage(img_new) label_img.configure(image=photo_img) label_img.image = photo_img # checkPalette w_canvas.delete('all') displayLabels(img_new) img_new.save(img_path) root.bind_all('<Key>', key)
def filename(): name = simpledialog.askstring("Filename", "Please enter the filename") return name
def onSaveVideo(): global lastVideoFilename initialFilenameValue = modelPath.split("/")[-2].split("-")[2] + "-" if lastVideoFilename != None: if lastVideoFilename[-2].isdigit(): lastNumber = int(lastVideoFilename[-2]) lastNumber += 1 initialFilenameValue = "%s-%d" % (lastVideoFilename[-2], lastNumber) else: initialFilenameValue = "%s-%d" % (lastVideoFilename, 0) videoFilename = simpledialog.askstring("Input", "Video filename:", parent=root, initialvalue=initialFilenameValue) if videoFilename is None: return lastVideoFilename = videoFilename currentPathResult = os.path.join(PATH_RESULT, videoFilename) videoFilename += ".mp4" videoFilename = os.path.join(PATH_RESULT, videoFilename) try: os.mkdir(currentPathResult) except: messagebox.showerror("Error", "Path already exist") return btnSaveVideo.grid_remove() progressBar['value'] = 0 progressBar.grid() root.update_idletasks() maxInterpolation = sliderTransition.get() cantInterpolations = calculateInterpolationPerPoint(maxInterpolation) totalFrames = np.sum(cantInterpolations) arrInterpolations = [] for pointFrom in range(0, pointList.size() - 1): pointTo = pointFrom + 1 #loop if pointFrom == pointList.size() - 1: pointTo = 0 cantInterpolation = cantInterpolations[pointFrom] x = np.array([0, 1]) y = np.vstack((pointsSaved[pointFrom], pointsSaved[pointTo])) f = interp1d(x, y, axis=0) arrInterpolation = f( np.linspace(0, 1, cantInterpolation + 1, endpoint=True)) arrInterpolations += list(arrInterpolation) batch_size = 20 for i in range(0, len(arrInterpolations), batch_size): end = i + batch_size if end > len(arrInterpolations): end = len(arrInterpolations) latentSamples = np.array(arrInterpolations[i:end]) generatedImages = generateFromGAN(latentSamples) for j, generated in enumerate(generatedImages): generatedImage = Image.fromarray(generated, 'RGB') currentFrame = i + j generatedImage.save("%s/%05d.png" % (currentPathResult, currentFrame)) progressBar['value'] = (currentFrame / len(arrInterpolations)) * 100 root.update_idletasks() # for i in range(0,len(arrInterpolation)): # if pointTo == 0 and i == len(arrInterpolation) - 1 : # break # latentSample = np.array([arrInterpolation[i]]) # generated = generateFromGAN( latentSample ) # generatedImage = Image.fromarray(generated[0], 'RGB') # currentFrame = np.sum( cantInterpolations[0:pointFrom] )+i+1 # generatedImage.save( "%s/%05d.png" % (currentPathResult,currentFrame) ) subprocess.call([PATH_IMAGES_TO_VIDEO, currentPathResult, videoFilename]) progressBar.grid_remove() root.update_idletasks() btnSaveVideo.grid() root.update_idletasks() subprocess.call(["vlc", videoFilename])
def ask_user(): ask = simpledialog.askstring("Task", "Do you want to encrypt or decrypt?") return ask
def consultarArtista(self): nomeArtista = simpledialog.askstring("Input", "Nome do Artista: ", parent=self.root) self.ctrlArtista.consultarArtista(nomeArtista)
def submitButtons(): babyName = "babyName.pckl" babyGender = "babyGender.pckl" selection = var.get() print(selection) ##### Boy Selection if selection == 1: if not os.path.exists(babyGender): fGender = open('babyGender.pckl', 'wb') pickle.dump("Boy", fGender) name = simpledialog.askstring("Input", "Awwe, well congrats on your little boy! \nWhat is your son's name?") fName = open('babyName.pckl', 'wb') pickle.dump(name, fName) tk.messagebox.showinfo(title="Welcome!!", message="Mommy and Daddy love you " + name) self.switch_frame(StartPage) else: b = open(babyName, 'rb') baby = pickle.load(b) #### Come Back And Add An Option to prompt if the user wants to continue anyway, deleting the old record tk.messagebox.showwarning(title="Watch out now!!", message="It looks like you have already set up little baby " + baby) MsgBox = tk.messagebox.askquestion ('Continue?','You can continue with the setup, it will delete ' + baby ,icon = 'warning') if MsgBox == 'yes': fGender = open('babyGender.pckl', 'wb') pickle.dump("Boy", fGender) name = simpledialog.askstring("Input", "Awwe, well congrats on your little boy! \nWhat is your son's name?") fName = open('babyName.pckl', 'wb') pickle.dump(name, fName) tk.messagebox.showinfo(title="Welcome!!", message="Mommy and Daddy love you " + name) self.switch_frame(StartPage) ##### Girl Selection elif selection == 2: if not os.path.exists(babyGender): fGender = open('babyGender.pckl', 'wb') pickle.dump("Girl", fGender) name = simpledialog.askstring("Input", "Awwe, well congrats on your little girl! \nWhat is your daughter's name?") fName = open('babyName.pckl', 'wb') pickle.dump(name, fName) tk.messagebox.showinfo(title="Welcome!!", message="Mommy and Daddy love you " + name) master.switch_frame(StartPage) else: b = open(babyName, 'rb') baby = pickle.load(b) #### Come Back And Add An Option to prompt if the user wants to continue anyway, deleting the old record tk.messagebox.showwarning(title="Watch out now!!", message="It looks like you have already set up little baby " + baby) MsgBox = tk.messagebox.askquestion ('Continue?','You can continue with the setup, it will delete ' + baby ,icon = 'warning') if MsgBox == 'yes': fGender = open('babyGender.pckl', 'wb') pickle.dump("Girl", fGender) name = simpledialog.askstring("Input", "Awwe, well congrats on your little girl! \nWhat is your daughter's name?") fName = open('babyName.pckl', 'wb') pickle.dump(name, fName) tk.messagebox.showinfo(title="Welcome!!", message="Mommy and Daddy love you " + name) master.switch_frame(StartPage) elif selection == 0: tk.messagebox.showwarning(title="Uh Oh! :/", message="Please make sure you selection something and try again :)") else: tk.messagebox.showwarning(title="Uh Oh! :/", message="Something went wrong :((")
country = country.lower() # Store the country name as the key and the country capital as the value in the data dictionary data[country] = capital return data def addInfo(country, capital): with open('capitals.txt', 'a') as file: # a for append file.write(f'\n{country}/{capital}') # Add a country and capital on a new line # Hide the window that Tkinter automatically creates root = Tk() root.withdraw() # Get info about capitals World = getInfo() # Start infinite loop while True: try: getCountry = simpledialog.askstring('Country', 'Type any country here:').lower() if getCountry in World: result = World[getCountry] messagebox.showinfo('Capital', 'The capital city of ' + getCountry + ' is ' + result) else: newCapital = simpledialog.askstring('Tell me...', 'I don\'t know that! What is the capital city of ' + getCountry + '?').lower().capitalize() addInfo(getCountry, newCapital) World[getCountry] = newCapital except AttributeError: print('Exited program') exit()
def choose(): root = Tk() root.withdraw() response = simpledialog.askstring('', 'Please enter a Filename') return response
def new(): status.set("menyiapkan kamera, silahkan tunggu beberapa saat...") # vid_cam = cv2.VideoCapture(0, cv2.CAP_DSHOW) # TODO 1 : Pilih Kamera (0 untuk kamera laptop & 1 untuk kamera USB) --> perhatikan variable vid-cam vid_cam = cv2.VideoCapture(0) face_detector = cv2.CascadeClassifier('face-detect.xml') # memberikan id untuk masing2 wajah # face_id = input("masukkan Id baru : ") mm = Tk().withdraw() face_id = simpledialog.askstring(title="Pelabelan Wajah", prompt="Masukkan Id :") # TODO 2 : Rubah variable "jumlah_pengambilan" untuk menentukan jumlah gambar training per wajah jumlah_pengambilan = 50 # inisialisasi jumlah gambar jumlah = 0 buatFolder("dataset/") # Membuat Perulangan untuk mengambil 100 gambar wajah while (True): # Mengambil video frame _, image_frame = vid_cam.read() # Merubah video frame menjadi gambar grayscale gray = cv2.cvtColor(image_frame, cv2.COLOR_BGR2GRAY) # Mendeteksi wajah pada videocam wajah = face_detector.detectMultiScale(gray, 1.3, 5) # mengambil gambar yang sudah di crop dan menyimpannya pada forder dataset for (x, y, w, h) in wajah: # Meng-crop hanya pada bagian wajah dengan sebuah kotak biru dengan ketebalan 2 cv2.rectangle(image_frame, (x, y), (x + w, y + h), (255, 0, 0), 2) persen_proses = 100/jumlah_pengambilan status.set("Pengambilan gambar {0:.0f}%".format(jumlah*persen_proses)) # nemabahkan nilai count (jumlah gambar pada id tertentu) jumlah += 1 # Menyimpan gambar yang telah di tangkap pada folder dataset dengan nama sesuai ID dan count cv2.imwrite("dataset/User." + str(face_id) + '.' + str(jumlah) + ".jpg", gray[y:y + h, x:x + w]) # Menampilkan video camera untuk untuk user yang akan di ambil gambar wajahnya cv2.imshow('Pengambilan Data Wajah', image_frame) # tekan q untuk menghentikan video frame if cv2.waitKey(100) & 0xFF == ord('q'): break # jika gambar yang diambi sudah mencapai 100 maka video frame akan berhenti secara otomatis elif jumlah > jumlah_pengambilan: break # menghentikan kamera vid_cam.release() # keluar dari semua jendela program cv2.destroyAllWindows() status.set("Pengambilan gambar selesai")
def prompt(message: str) -> str: return simpledialog.askstring(" ", message, parent=_tkmain)
def input_subject_id_gui(): ROOT = tk.Tk() ROOT.withdraw() return simpledialog.askstring(title='PyPlr Protocol', prompt='Enter Subject ID: ')
def removeUser(): print('Enter username') username = sd.askstring("Enter username:"******"Enter username") uData = {'Operation': 'remv', 'Login': username} sendData(uData) return
from tkinter import messagebox, simpledialog, Tk # Create an if-main code block, *hint, type main then ctrl+space to auto-complete if __name__ == '__main__': # Make a new window variable, window = Tk() window = Tk() # Hide the window using the window's .withdraw() method window.withdraw() # 1. Create a variable to hold the user's score. Set it equal to zero. user = 0 # ASK A QUESTION AND CHECK THE ANSWER que = simpledialog.askstring(title="Question", prompt="Is the sky blue?") # // 2. Ask the user a question # // 3. Use an if statement to check if their answer is correct if que == "yes": user+=1 # // 4. if the user's answer was correct, add one to their score que2 = simpledialog.askstring(title="Question", prompt="Is dirt brown") if que2 == "yes": user+=1 # MAKE MORE QUESTIONS. Ask more questions by repeating the above # // Option: Subtract a point from their score for a wrong answer que3 = simpledialog.askstring(title="Question", prompt="Is grass green") # // 2. Ask the user a question
def print_string(): res = askstring("Spam", "Egg label") print(res)
def name_change(self, playlist): pname = simpledialog.askstring('Avideom', 'Enter new playlist name:') os.rename(AVIDEOM_DIR + '/playlists/' + playlist, AVIDEOM_DIR + '/playlists/' + pname) return
def _decode(self, two_lines, bytes): "Create a Unicode string." chars = None # Check presence of a UTF-8 signature first if bytes.startswith(BOM_UTF8): try: chars = bytes[3:].decode("utf-8") except UnicodeDecodeError: # has UTF-8 signature, but fails to decode... return None, False else: # Indicates that this file originally had a BOM self.fileencoding = 'BOM' return chars, False # Next look for coding specification try: enc = coding_spec(two_lines) except LookupError as name: tkMessageBox.showerror( title="Error loading the file", message="The encoding '%s' is not known to this Python "\ "installation. The file may not display correctly" % name, parent = self.text) enc = None except UnicodeDecodeError: return None, False if enc: try: chars = str(bytes, enc) self.fileencoding = enc return chars, False except UnicodeDecodeError: pass # Try ascii: try: chars = str(bytes, 'ascii') self.fileencoding = None return chars, False except UnicodeDecodeError: pass # Try utf-8: try: chars = str(bytes, 'utf-8') self.fileencoding = 'utf-8' return chars, False except UnicodeDecodeError: pass # Finally, try the locale's encoding. This is deprecated; # the user should declare a non-ASCII encoding try: # Wait for the editor window to appear self.editwin.text.update() enc = askstring("Specify file encoding", "The file's encoding is invalid for Python 3.x.\n" "IDLE will convert it to UTF-8.\n" "What is the current encoding of the file?", initialvalue=encoding, parent=self.editwin.text) if enc: chars = str(bytes, enc) self.fileencoding = None return chars, True except (UnicodeDecodeError, LookupError): pass return None, False # None on failure
from tkinter import simpledialog, messagebox, Tk, Canvas windowWidth = 600 windowHeight = 600 root = Tk() canvas = Canvas(root, width=windowWidth, height=windowHeight, bg="#DDDDDD") canvas.grid() #1. Ask the user what color tomato they would like and save their response # You can give them up to three choices tasty = simpledialog.askstring( "", "what color would you like your tomato,powder blue,thistle,or tomato") #2. use if-else statements to draw the tomato in the color that they chose fill = "red" if tasty == "powder blue": fill = "powderblue" elif tasty == "thistle": fill = "thistle" elif tasty == "tomato": fill = "tomato" # you can modify the code below or draw your own tomato canvas.create_oval(75, 200, 400, 450, fill=fill, outline="") canvas.create_oval(200, 200, 525, 450, fill=fill, outline="") canvas.create_rectangle(275, 100, 325, 230, fill="green", outline="") root.mainloop()
def finish(): name=simpledialog.askstring("Enter name","what is your name") if name is not None: messagebox.showinfo("Welcome","Thankyou For Using This App "+name) root.destroy()
from tkinter import messagebox, simpledialog, Tk # Create an if-main code block if __name__ == '__main__': # Make a new window variable, window = Tk() window = Tk() # Hide the window using the window's .withdraw() method window.withdraw() # Ask the user for their name and save it to a variable # name = simpledialog.askstring(title='Greeter', prompt="What is your name?") Name = simpledialog.askstring(None, prompt='What is your name?') # Show a message box with your message using the .showinfo() method messagebox.showinfo(title='Nice to meet you.', message=Name + ', that is a nice name') # Print your message to the console using the print() function print('message inserted later') # Show an error message using messagebox.showerror() messagebox.showerror(None, message='message inserted later') # Run the window's .mainloop() method window.mainloop()