我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用tkinter.messagebox.showinfo()。
def translate(self, text=None): if len(self.language_tabs) < 1: msg.showerror("No Languages", "No languages added. Please add some from the menu") return if not text: text = self.english_entry.get(1.0, tk.END).strip() url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}" try: for language in self.language_tabs: full_url = url.format("en", language.lang_code, text) r = requests.get(full_url) r.raise_for_status() translation = r.json()[0][0][0] language.translation_var.set(translation) except Exception as e: msg.showerror("Translation Failed", str(e)) else: msg.showinfo("Translations Successful", "Text successfully translated")
def loadPiecesFile(): global movesString global piecesString global status filename = filedialog.askopenfilename() if not filename.endswith('.txt'): messagebox.showinfo("Visualizer error", "Filetype must be a .txt") else: with open(filename, 'r') as infile: piecesString = infile.read().replace('\n', '') if piecesString is not None and movesString is not None: status.set("Pieces: Loaded\nMoves: Loaded") generateFrames(piecesString,movesString) elif movesString is None: status.set("Pieces: Loaded\nMoves: Not Loaded")
def loadMovesFile(): global movesString global piecesString global status filename = filedialog.askopenfilename() if not filename.endswith('.txt'): messagebox.showinfo("Visualizer error", "Filetype must be a .txt") else: with open(filename, 'r') as infile: movesString = infile.read().replace('\n', '') if piecesString is not None and movesString is not None: status.set("Pieces: Loaded\nMoves: Loaded") generateFrames(piecesString,movesString) elif piecesString is None: status.set("Pieces: Not Loaded\nMoves: Loaded")
def install_zip(self): pack = filedialog.askopenfile("r") found_pack = False if pack: with zipfile.ZipFile(pack.name, "r") as z: for file in z.namelist(): if file == "pack.mcmeta": # messagebox.showinfo("Information", "Found 'pack.mcmeta'.") found_pack = True pack.close() if found_pack: try: shutil.move(pack.name, self.resourcepack_location) except shutil.Error: messagebox.showerror("Error", "This pack is already installed.") else: messagebox.showerror("Error", "Could not find 'pack.mcmeta'.")
def zip_file(self): amount = functions.folder_files(self.parent.directory) progress = dialog.ProgressWindow(self.parent, title="Zipping Pack", maximum=amount) count = 0 with zipfile.ZipFile(self.parent.directory + ".zip", "w") as z: for root, dirs, files in os.walk(self.parent.directory.replace("\\", "/"), topdown=True): new_root = root.replace("\\", "/").split("/") # print(root, dirs, files) for name in files: z.write(os.path.join(root, name), "/".join(new_root[new_root.index(self.parent.directory.split("/")[-1]) + 1:]) + "/" + name) count += 1 progress.variable_name.set("Current File: " + name) progress.variable_percent.set("{}% Complete".format(round(100 * float(count) / float(amount)))) progress.variable_progress.set(progress.variable_progress.get() + 1) z.close() progress.destroy() messagebox.showinfo(title="Information", message="Zipping complete.")
def Kind_detail_view_left(self, sel): """ Find the selected left hand object from a user selection with left button in the kind_table that is displayed in the kind_tree view.""" description_text = ['description', 'beschrijving'] obj_descr_title = ['Information about ', 'Informatie over '] cur_item = self.kind_tree.focus() item_dict = self.kind_tree.item(cur_item) values = list(item_dict['values']) #print('Kind_detail_left:', cur_item, values) #[0], values[1], values[2:] selected_object = self.Gel_net.uid_dict[str(values[0])] # If info_kind is a description then display the destription in messagebox if values[7] in description_text: print('Information {} is not presented on a carrier but is as follows:\n {}'.\ format(values[4], selected_object.description)) messagebox.showinfo(obj_descr_title[self.lang_index] + selected_object.name, \ selected_object.description) else: print('Display kind details of: {}'.format(selected_object.name)) self.Define_and_display_kind_detail_view(selected_object) if len(self.Gel_net.info_model) > 0: self.Define_and_display_documents() #------------------------------------------------------------------------
def checkListenTask(self): self.listener.unschedule_all() if self.listenDirEnableFlag.get(): print("enable") listen_dir = os.path.abspath(self.listenDirPath.get()) try: self.listener.schedule(self._listen_handler, listen_dir, recursive = True) except Exception as e: messagebox.showinfo("listen dir {dirname} failed" .format(dirname = listen_dir), "{reason}".format( reason = traceback.format_exception(*sys.exc_info()) ) ) else: print("disable")
def chooseDialogDir(self): self.chooseDirPath = filedialog.askdirectory( initialdir = self.chooseDirPath, parent = self, title = "Select Directory contains .SPE files", ) print("select:", self.chooseDirPath) if len(self.chooseDirPath) == 0: return self.chooseDirOutDir = filedialog.askdirectory( initialdir = self.chooseDirPath, parent = self, title = "Select output Directory", mustexist = False, ) # TODO check wirte permission first if not self.checkDir(self.chooseDirOutDir): return filenames = yieldFilesUnderDirectory(self.chooseDirPath, match = "*.SPE") if filenames is None: messagebox.showinfo("Convert result", "No .SPE files under this directory") return self.convertFiles(filenames, self.chooseDirOutDir, oldPrefix = self.chooseDirPath)
def next_match(self, event=None): try: current_target, current_target_end = self.match_coordinates[self.current_match] self.main_text.tag_remove("sel", current_target, current_target_end) self.main_text.tag_add("findmatch", current_target, current_target_end) except IndexError: pass try: self.current_match = self.current_match + 1 next_target, target_end = self.match_coordinates[self.current_match] except IndexError: if len(self.match_coordinates) == 0: msg.showinfo("No Matches", "No Matches Found") else: if msg.askyesno("Wrap Search?", "Reached end of file. Continue from the top?"): self.current_match = -1 self.next_match() else: self.main_text.mark_set(tk.INSERT, next_target) self.main_text.tag_remove("findmatch", next_target, target_end) self.main_text.tag_add("sel", next_target, target_end) self.main_text.see(next_target)
def file_save(self, event=None): if not self.active_ini: msg.showerror("No File Open", "Please open an ini file first") return for section in self.active_ini: for key in self.active_ini[section]: try: self.active_ini[section][key] = self.ini_elements[section][key].get() except KeyError: # wasn't changed, no need to save it pass with open(self.active_ini_filename, "w") as ini_file: self.active_ini.write(ini_file) msg.showinfo("Saved", "File Saved Successfully")
def add_button(self, functionname, function, args=(), kwargs=None): # see http://stackoverflow.com/q/1132941 if kwargs is None: kwargs = {} # the call_string will be like "messagebox.showinfo('Bla Bla', 'Bla')" parts = [] for arg in args: parts.append(repr(arg)) for key, value in kwargs.items(): parts.append(key + "=" + repr(value)) call_string = "%s.%s(%s)" % (self.modulename, functionname, ', '.join(parts)) callback = functools.partial(self.on_click, call_string, function, args, kwargs) button = tk.Button(self.frame, text=functionname, command=callback) button.pack()
def crdt_write(master,amt,accnt,name): if(is_number(amt)==0): messagebox.showinfo("Error","Invalid Credentials\nPlease try again.") master.destroy() return fdet=open(accnt+".txt",'r') pin=fdet.readline() camt=int(fdet.readline()) fdet.close() amti=int(amt) cb=amti+camt fdet=open(accnt+".txt",'w') fdet.write(pin) fdet.write(str(cb)+"\n") fdet.write(accnt+"\n") fdet.write(name+"\n") fdet.close() frec=open(str(accnt)+"-rec.txt",'a+') frec.write(str(strftime("[%Y-%m-%d] [%H:%M:%S] ",gmtime()))+" "+str(amti)+" "+str(cb)+"\n") frec.close() messagebox.showinfo("Operation Successfull!!","Amount Credited Successfully!!") master.destroy() return
def calculated_moe(self): """ Show the calculated MOE """ weight = float(self.kayu_weight) length = float(self.kayu_length) thick_x = float(self.kayu_thick_x) thick_y = float(self.kayu_thick_y) naturfreq = float(self.kayu_naturfreq) / 1000 self.kayu = modules.Kayu(weight, length, \ thick_x, thick_y) self.kayu.set_freq(naturfreq) moe = self.kayu.get_moe() woodname_str = "The " + self.kayu_name + " wood with\n" naturfreq_str = "Natural Freq = " + str(self.kayu.get_freq()) + FREQ_UNIT + "\n" length_str = "Length = " + str(self.kayu.length) + LENGTH_UNIT + "\n" density_str = "Density = " + str(self.kayu.density) + DENSITY_UNIT + "\n" moe_str = "Has MOE = " + str(moe) + MOE_UNIT +"\n" moe_sni = "Has SNI CLASS = " + modules.sni_class(moe) +"\n" messagebox.showinfo("Results!", woodname_str + naturfreq_str \ + length_str + density_str + moe_str + moe_sni)
def showInfo(self): messagebox.showinfo('EWB Drone Nav Algo GUI',""" Welcome to the EWB Drone Navigation Algorithm GUI! First, click to set the boundary vertices of your region, without clicking on the first vertex again at the end. Then, click 'Draw Path', which will prompt you to enter the stride length in pixels. Enter the desired length (be reasonable!) and hit OK. Alternatively, provide a stride length in the command prompt by running `python display.py [stride]` where [stride] is the desired length. The algorithm should display the planned path through the region. Hit 'Reset' to reset the screen. """)
def main(): # ?????????,?????Tkinter????????Tk??.??????withdraw()?????? tk = tkinter.Tk() tk.withdraw() # ????? print(dir(mb)) # ??,?????????,??ok,????????????.??????????????,??????????. # ??,???Cancel?,??????None mb.showinfo("Title", "Your message here") mb.showerror("An Error", "Oops!") mb.showwarning("Title", "This may not work...") mb.askyesno("Title", "Do you love me?") mb.askokcancel("Title", "Are you well?") mb.askquestion("Title", "How are you?") mb.askretrycancel("Title", "Go again?") mb.askyesnocancel("Title", "Are you well?")
def build_menus(self, top): menus = (("Item", (("New", self.ev_new_item), ("Edit", self.ev_edit_item), ("Delete", self.ev_delete_item), )), ("Member", (("New", self.ev_new_member), ("Edit", self.ev_edit_member), ("Delete", self.ev_delete_member), )), ("Help", (("Help", self.ev_help), ("About", lambda: mb.showinfo( "Help About", "Lender application\nAuthor: Alan Gauld""") )))) self.menu_bar = tix.Menu(top) for menu in menus: m = tix.Menu(top) for item in menu[1]: m.add_command(label=item[0], command=item[1]) self.menu_bar.add_cascade(label=menu[0], menu=m) return self.menu_bar
def ev_click(row, col): global status if status["text"] == "Game Over": mb.showerror("Game over", "Game over!") return game = cells2game() index = (3 * row) + col result = oxo_logic.user_move(game, index) game2cells(game) if not result: result = oxo_logic.computer_move(game) game2cells(game) if result == "D": mb.showinfo("Result", "It's a Draw!") status["text"] = "Game Over" elif result == "X" or result == "O": mb.showinfo("Result", "The winner is: {}".format(result)) status["text"] = "Game Over"
def debugbutton(self): width = 8 msg = '' for row in range(len(self.root.data[0])): for column in range(len(self.root.data)): element = str(self.root.data[column][row]) if len(element) < width: element += ' ' * (width - len(element)) msg += element if column == len(self.root.data) - 1: msg += '\n' #messagebox.showinfo(message=msg) #messagebox.showinfo(message=str(serial.Serial.inWaiting(self.root.ser))) #messagebox.showinfo(message=self.root.ani) #If this script is executed, just run the main script
def _do_reset(): if not _needs_reset: messagebox.showinfo("Reset Settings", "You are already using the default settings.") return if not messagebox.askyesno( "Reset Settings", "Are you sure you want to reset all settings?", parent=_dialog): return for section in _sections.values(): for key, info in section._infos.items(): if info.reset: section[key] = info.default messagebox.showinfo( "Reset Settings", "All settings were reset to defaults.", parent=_dialog)
def thread_dowload(self): self.stop.set("??") select_var = self.var.get() if select_var in [1,2,3]: for i in range(1): th=threading.Thread(target=self.Jandan,args=(i,)) th.setDaemon(True) th.start() elif select_var in [4,5]: for i in range(1): th=threading.Thread(target=self.Doutula,args=(i,)) th.setDaemon(True) th.start() elif select_var in [6,7,8,9,10]: for i in range(1): th=threading.Thread(target=self.Budejie,args=(i,)) th.setDaemon(True) th.start() else: messagebox.showinfo(title="??",message="???????????")
def get_name(): name = names.get() select_var = var.get() signature_ttf = ["jfcs.ttf","qmt.ttf","bzcs.ttf","lfc.ttf","haku.ttf","zql.ttf","yqk.ttf"] if not name: messagebox.showinfo(title="??",message="??????!") elif select_var == 1: downloading(name,signature_ttf[0]) elif select_var == 2: downloading(name,signature_ttf[1]) elif select_var == 3: downloading(name,signature_ttf[2]) elif select_var == 4: downloading(name,signature_ttf[3]) elif select_var == 5: downloading(name,signature_ttf[4]) elif select_var == 6: downloading(name,signature_ttf[5]) elif select_var == 7: downloading(name,signature_ttf[6]) else: messagebox.showinfo(title="??",message="?????????!")
def apply_settings(settings_list): #rewrite in JSON data = {} print(settings_list) data['color'] = settings_list[0] data['exit'] = settings_list[1] data['minimize'] = settings_list[4] data['width'] = settings_list[2] data['height'] = settings_list[3] json_data = json.dumps(data) json_file = open('settings.json', 'w') json_file.write(json_data) json_file.close() messagebox.showinfo("WinGuake", "Settings will be applied on next WinGuake restart.") sys.exit() #print(os.path.dirname(os.path.abspath(__file__)))
def __validates(self, dt_init, dt_final, nosql, url, port): bool_dt = False if re.search(r'^\d\d/\d\d/\d\d\d\d$', dt_init) != None and re.search(r'^\d\d/\d\d/\d\d\d\d$', dt_final) != None: try: dt = datetime.date(int(dt_init[6:10]), int(dt_init[3:5]), int(dt_init[:2])) dt = datetime.date(int(dt_final[6:10]), int(dt_final[3:5]), int(dt_final[:2])) except ValueError: pass else: bool_dt = True bool_nosql = (nosql == 'Selecione...' and url == '' and port == '') or (nosql != 'Selecione...' and (re.search(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', url) != None) and (re.search(r'^\d{1,5}$', port) != None)) if bool_dt and bool_nosql: return True msg = '' if not bool_dt: msg += '"Data inicial" ou "Data final" inválida ou fora do padrão 00/00/0000\n' if not bool_nosql: msg += 'Verifique:\nSeleção do NoSQL\npadrão 0.0.0.0 para "URL"\nsomente números para "Porta"\n' messagebox.showinfo('scrpr4dou', msg) return False
def __init_download(self): if not self.__validates(self.entry1_value.get(), self.entry2_value.get(), self.combobox_value.get(), self.entry4_value.get(), self.entry5_value.get()): return self.btn1_gui.state(['disabled']) self.btn2_gui.state(['disabled']) self.btn3_gui.state(['disabled']) self.entry1_gui.state(['disabled']) self.entry2_gui.state(['disabled']) self.entry4_gui.state(['disabled']) self.entry5_gui.state(['disabled']) self.combobox_gui.state(['disabled']) self.lbl7_value.set('\nBaixando...') messagebox.showinfo('scrpr4dou', 'Iniciando download, aguarde...') global col col = scrpr4dou.Collection(self.combobox_value.get(), self.entry4_value.get(), self.entry5_value.get(), self.entry1_value.get(), self.entry2_value.get()) if col.to_local(datetime.datetime.now()): if self.combobox_value.get() != 'Selecione...': self.btn2_gui.state(['!disabled']) messagebox.showinfo('scrpr4dou', 'Download concluído') self.lbl7_value.set('')
def __init_ingest(self): self.lbl7_value.set('\nInserindo...') messagebox.showinfo('scrpr4dou', 'Iniciando inserção, aguarde...') self.btn2_gui.state(['disabled']) if col.to_nosql(): messagebox.showinfo('scrpr4dou', 'Inserção concluída') else: messagebox.showinfo('scrpr4dou', 'Problemas na inserção') self.lbl7_value.set('') self.__clear_fields self.btn1_gui.state(['!disabled']) self.btn2_gui.state(['!disabled']) self.btn3_gui.state(['!disabled']) self.entry1_gui.state(['!disabled']) self.entry2_gui.state(['!disabled']) self.entry4_gui.state(['!disabled']) self.entry5_gui.state(['!disabled']) self.combobox_gui.state(['!disabled'])
def setConfigs(self): ''' Sets self.app_data info via a user provided pickle file in same directory ''' try: inFile = open('Configs.pkl', 'rb') except FileNotFoundError: messagebox.showinfo(title='Error', message='Configs.pkl not found please create Config file first.') self.show_frame(ConfigsPage) else: pickleData = [] for i in range(4): pickleData.append(pickle.load(inFile)) inFile.close() self.app_data['baseURL'].set(pickleData[0]) self.app_data['apiURL'].set(pickleData[1]) self.app_data['account'].set(pickleData[2]) self.app_data['token'].set(pickleData[3]) self.show_frame(PageTwo)
def genTeachReport(self): ''' Creates a CSV file with name, loginID, and group scores for each student in app_data fullGBook. Headers are included. ''' csvOut = [] heads = ['name','login_ID',] for i in self.app_data['fullGBook'][0]['results']: heads.append(i['title']) for i in self.app_data['fullGBook']: toAdd = [] toAdd.append(i['name']) toAdd.append(i['login_id']) for k in i['results']: for j in heads: if j == k['title']: toAdd.append(k['mean']) csvOut.append(toAdd) with open('StandardsReport.csv', 'w', newline='') as csvfile: writeOut = csv.writer(csvfile, delimiter=',',dialect='excel') writeOut.writerow(heads) for i in csvOut: writeOut.writerow(i) messagebox.showinfo(title='Export', message='Data exported to CSV')
def uploder(self): code = self.lfc_field_1_t.get('0.0', 'end') code = code.encode(encoding="utf-8") code = base64.urlsafe_b64encode(code) url = "http://" + HOST + ":" + PORT + "/postcode?code=" + str(code) try: req = requests.get(url) if req.text == "200": messagebox.showinfo("??", "????") # ????? self.lfc_field_1_t.delete('0.0', 'end') else: messagebox.showinfo("??", "????????") except: messagebox.showinfo("??", "????????") # ???? ?base64????
def upfile(self): url = "http://" + HOST + ":" + PORT + "/upfile" # ??????? filename = filedialog.askopenfilename() self.lfc_field_1_t.delete('0.0', 'end') self.lfc_field_1_t.insert('0.0', "??????......") try: files = {'file': open(str(filename), 'rb')} req = requests.post(url, files=files) if req.status_code == 200: messagebox.showinfo("??", "????") else: messagebox.showinfo("??", "????????") except: messagebox.showinfo("??", "????????") finally: self.lfc_field_1_t.delete('0.0', 'end') # ????
def downfile(self): try: # ??????????????_??????????? filename = filedialog.asksaveasfilename() self.lfc_field_1_t.delete('0.0', 'end') self.lfc_field_1_t.insert('0.0', "??????......\n") filename = filename + '.' + \ requests.get("http://" + HOST + ":" + PORT + "/downfiletype").text self.lfc_field_1_t.insert('0.0', "?????????......") req = requests.get("http://" + HOST + ":" + PORT + "/downfile") if req.status_code == 200: with open(filename, 'wb') as savefile: savefile.write(req.content) messagebox.showinfo("??", "????") else: messagebox.showinfo("??", "????????") except: messagebox.showinfo("??", "????????") finally: self.lfc_field_1_t.delete('0.0', 'end')
def scan(self): self.txt.delete(0.0, END) self.txt.insert(0.0, ('Scanning ' + self.srvr.get() + ' ... \n')) #The beginning of PSresult.txt port_file = open("PSresult.txt", "w") port_file.write("\n##Scanned " + self.srvr.get() + ': ##\n') #Beginning of the for loop: for port in range(int(self.start.get()), int(self.end.get()) + 1): if self.pscan(port): msg = "Port " + str(port) + ' Is open \n' self.txt.insert(float(port) + 1, msg) port_file.write(msg) else: self.txt.insert(float(port) + 1, 'Port ' + str(port) + ' is closed! \n') msg = "Port " + str(port) + ' Is closed \n' port_file.write(msg) port_file.close() messagebox.showinfo(title='Cissa Port Scanner', message='Your Scan is finished. Happy Hacking :)')
def hello(self): name = self.nameInput.get() or 'world' messagebox.showinfo('Message', 'Hello, %s' %name)
def infoBox(self, title, message): self.topLevel.update_idletasks() MessageBox.showinfo(title, message) self.__bringToFront()
def __init__(self, response=str, text="", title=None, accept=0, **options): if response is bool: self.dialog = [askyesno, askokcancel, askretrycancel][accept] else: self.dialog = {None:showinfo, str:askstring, int:askinteger, float:askfloat, 0:askopenfilename, 1:asksaveasfilename, 2:askdirectory}[response] self.options = options.copy() if "initialdir" in options: self.options["initialdir"] = abspath(options["initialdir"]) if type(response) is int: self.args = tuple() if title: self.options["title"] = title else: if title is None: title = "Info" if response is None else "Confirm" if response is bool else "Input" self.args = title, text
def show_result(): messagebox.showinfo("calcylator",str("game over"))
def quitProgram(): tkMessageBox.showinfo(productName, coremeraco.constructExitStatement()) if sound: sound.stop() sys.exit() # Just running exit() doesn't work with PyInstaller
def anunciar_ganador(self, data): messagebox.showinfo("¡Atención!", message=data) # Handle Events
def hello(self): name = self.nameInput.get() or 'world' messagebox.showinfo('Message', 'Hello, %s!' % name)
def _msgBox(): msg.showinfo('Python Message Info Box', 'A Python GUI created using tkinter:\nThe year is 2017.') # Add another Menu to the Menu Bar and an item