def makedb(self): conn = sqlite3.connect("registration.db") c = conn.cursor() table = "new_entries" try: query = "select * from %s" % table c.execute(query) workbook = Workbook("output.xlsx") sheet = workbook.add_worksheet() bold = workbook.add_format({'bold': True}) sheet.set_column('A:A', 5) sheet.set_column('B:B', 18) sheet.set_column('C:C', 8) sheet.set_column('D:D', 8) sheet.set_column('E:E', 13) sheet.set_column('F:F', 17) sheet.set_column('G:G', 5) sheet.write("A1", 'S.No', bold) sheet.write("B1", 'Name', bold) sheet.write("C1", 'Branch', bold) sheet.write("D1", 'Section', bold) sheet.write("E1", 'Phone no', bold) sheet.write("F1", 'Email', bold) sheet.write("G1", 'Size', bold) for r, row in enumerate(c.fetchall()): for c, col in enumerate(row): sheet.write(r + 1, c, col) workbook.close() conn.close() messagebox.showinfo(title="Registration", message="Successfully made excel file") except: messagebox.showerror(title="Registration", message="Database doesn't exist") return
def Event_PlaintextSave(self): #清空my_ErrorMsg self.my_ErrorMsg = "" #讀取檔案名稱 self.fileName = self.Entry_ReadFileName.get() if self.fileName == "": self.ErrorMessage("未選擇欲存檔檔案!") #讀取GUI明文欄位中的值 self.my_plaintext = self.Entry_TextDecryption.get() if self.my_plaintext == "": self.ErrorMessage("沒有明文!") #如沒有任何錯誤訊息則執行存檔 if self.my_ErrorMsg != "": messagebox.showerror(title="Error Message", message=self.my_ErrorMsg) elif self.my_ErrorMsg == "": self.depictionText["text"] = "執行明文存檔功能..." file = open(self.fileName, 'w') file.write(self.my_plaintext) file.close() self.depictionText["text"] = "明文存檔完畢!!"
def errorVar(self, var, val): """Ask user to set correct setting""" msg = "{0} is not correct :\n'{1}'\nPlease set it in Config" messagebox.showerror("WARNING !", msg.format(var, str(val))) return(True)
def goto_file_line(self, event=None): if self.file_line_progs is None: l = [] for pat in self.file_line_pats: l.append(re.compile(pat, re.IGNORECASE)) self.file_line_progs = l # x, y = self.event.x, self.event.y # self.text.mark_set("insert", "@%d,%d" % (x, y)) line = self.text.get("insert linestart", "insert lineend") result = self._file_line_helper(line) if not result: # Try the previous line. This is handy e.g. in tracebacks, # where you tend to right-click on the displayed source line line = self.text.get("insert -1line linestart", "insert -1line lineend") result = self._file_line_helper(line) if not result: tkMessageBox.showerror( "No special line", "The line you point at doesn't look like " "a valid file name followed by a line number.", parent=self.text) return filename, lineno = result edit = self.flist.open(filename) edit.gotoline(lineno)
def gui_login(): items = map(int, w.acc_list.curselection()) for idx in items: try: login_manager.login(w.acc_list.get(idx)) # TODO: write console cbs except URLError as e: messagebox.showerror("Error", e.msg)
def savefile(master, text): try: filename = filedialog.asksaveasfilename(filetypes=(("Text files", "*.txt"), ("All files", "*.*") )) if bAppendtxtwhensaving == 1: filename = filename + ".txt" if not filename == "": txtcontent = iolib.writetotextfile(text, filename) if txtcontent == 1: print("Something went wrong while saving : %s.\n Does this user have to approrite permissions to the file?" % (filename)) messagebox.showerror("Error", "Something went wrong while saving to: %s.\n Do you have the approrite permissions to the file?" % (filename)) else: conversionsaved=1 print("Saved conversion to %s." % (filename)) messagebox.showinfo("Saved", "Saved conversion to %s." % (filename)) # print(txtcontent) # debugging purposes. else: # print("passed") # debugging purposes. pass except Exception as e: print("Error while loading file picker.\n %s." % (str(e))) messagebox.showerror("Error", "Error while loading file save.\n %s." % (str(e))) filename = 1 return filename
def play_game(game): result = "" while not result: print_game(game) choice = input("Cell[1-9 or q to quit]: ") if choice.lower()[0] == "q": save = mb.askyesno("Save game", "Save game before quitting?") if save: oxo_logic.save_game(game) quit_game() else: try: cell = int(choice) - 1 if not (0 <= cell <= 8): # check range raise ValueError except ValueError: print("Choose a number between 1 and 9 or 'q' to quit ") continue try: result = oxo_logic.user_move(game, cell) except ValueError: mb.showerror("Invalid cell", "Choose an empty cell") continue if not result: result = oxo_logic.computer_move(game) if not result: continue elif result == "D": print_game(game) mb.showinfo("Result", "It's a draw") else: print_game(game) mb.showinfo("Result", "Winner is {}".format(result))
def checkmethod(option, window): selected=str(option) if selected == "()": messagebox.showerror("Error", "Please select an option.") logger.error("User chose option {}. But {} is an invaild option!".format(selected, selected)) elif "0" in selected: window.destroy() createconvertwindow(selected) elif "1" in selected: window.destroy() createconvertwindow(selected) elif "2" in selected: window.destroy() createconvertwindow(selected) elif "3" in selected: window.destroy() createconvertwindow(selected) elif "4" in selected: window.destroy() createconvertwindow(selected) elif "5" in selected: messagebox.showinfo("Information", "Every seperate hexadecimal has to be on a new line in order to be converted correctly.") window.destroy() createconvertwindow(selected) else: logger.error("User chose option {}. But {} is an invaild option!".format(selected, selected)) messagebox.showerror("Error", "{} is an invaild option, please try again.".format(selected))
def setloggingoptions(): while True: if os.path.exists("data//logs") == True: try: logfilename = 'data//logs//log_gui ({}).log'.format(time.strftime("%d-%m-%Y")) handler = logging.FileHandler(logfilename) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) if bLoggingenabled == 0: logging.basicConfig() else: logging.basicConfig(filename=logfilename, level=logging.DEBUG) logger.addHandler(handler) logger.handlers.pop() logger.debug('Started %s at %s on %s', appname, time.strftime("%H:%M:%S"), time.strftime("%d/%m/%Y")) logger.info('Running on {} version {} {}.'.format(platform.system(), platform.release(), platform.machine())) # cx_freeze? if appfrozen == True: logger.info("Currently running the frozen version. Compiled by cx_freeze.") else: logger.info("Currently running from the Python script.") logger.info("%s version (%s %s) started in directory: %s", appname, version, release, currentdir) break except Exception as e: messagebox.showerror("Error", "Cannot create log.\n Exception: %s\nTrying to create logs folder..." % (str(e))) try: os.mkdir("data//logs") except Exception as e: messagebox.showerror("Error", "Cannot create logs folder.\n Exception: %s" % (str(e))) else: os.mkdir("data//logs")
def loadfile(self, filename): try: # open the file in binary mode so that we can handle # end-of-line convention ourselves. with open(filename, 'rb') as f: two_lines = f.readline() + f.readline() f.seek(0) bytes = f.read() except OSError as msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False chars, converted = self._decode(two_lines, bytes) if chars is None: tkMessageBox.showerror("Decoding Error", "File %s\nFailed to Decode" % filename, parent=self.text) return False # We now convert all end-of-lines to '\n's firsteol = self.eol_re.search(chars) if firsteol: self.eol_convention = firsteol.group(0) chars = self.eol_re.sub(r"\n", chars) self.text.delete("1.0", "end") self.set_filename(None) self.text.insert("1.0", chars) self.reset_undo() self.set_filename(filename) if converted: # We need to save the conversion results first # before being able to execute the code self.set_saved(False) self.text.mark_set("insert", "1.0") self.text.yview("insert") self.updaterecentfileslist(filename) return True
def _onExecButton( self ): ''' **Private Method** Handler for Execute Button pressed. Checks that test file(s) have been selected. Resets the data in the GUI Interface class and the GUI fields. Disables the Execute Button widget. Initiates a new thread to run the Regression Test Suite. :return: n/a: ''' # Test that we have files to test f = SetupConfig().getTestFiles() if( isinstance( f, list ) == False or len( f ) < 1 ): messagebox.showerror( 'Uh-oh', 'No File(s) to test specified' ) return self._execButton.configure( state = 'disabled', bg = 'light gray' ) GuiIF().reset() self._updateResults() ExecThread().start()
def adding_bloggers(info=info): for entry in connections.keys(): entrydata = [] print(entry.get()) if len(entry.get()) <= 1: name = 'nothing' else: name = entry.get() entrydata.append(name) for connected in connections[entry]: if connected.get() == '': entrydata.append('nothing') else: entrydata.append(connected.get()) if entrydata != ['nothing', 'nothing', 'nothing', 'nothing', 'nothing', 'nothing']: to_write.append(str(','.join([name for name in entrydata]) + '\n')) screennames = sum(map(lambda x: 0 if x.split(',')[0] == 'nothing' else 1, to_write)) print(to_write) print(screennames) if to_write and screennames == len(to_write): file = open('%s/Desktop/natappy/bloggers.txt' % home, 'a') file.writelines(to_write) file.close() print(to_write) counter = 0 for el in to_write: print(counter, el) add_blogger_to_excel(el) counter += 1 second_window(root=root, info=info) elif to_write and screennames != len(to_write): messagebox.showerror('Give me screen name', 'Screen name is required!')
def connector(event): print(self.hostname) if self.ping(self.hostname): tkConnect.config(state='disabled') tkUsername.config(state='disabled') tkPassword.config(state='disabled') tkHostname.config(state='disabled') tkConnect.unbind("<ButtonRelease-1>") tkDisConnect.config(state='active') tkDisConnect.bind("<ButtonRelease-1>", disconnector) hostnamesaver(event) usernamesaver(event) tkLog.insert(0, 'Connected!' + " - Time: " + str(datetime.datetime.now().time())) tkCommandLine.config(state='normal') try: self.connectButton() tkLog.insert(0, str(datetime.datetime.now().time()) + " - INFO: Host is valid!") except: print("Host nem elérhető!") else: messagebox.showerror(title="Host error", message="Host doesn't found on network!") tkLog.insert(0, str(datetime.datetime.now().time()) + " - ERROR: Host doesn't found!") disconnector(self) try: if SC.get_transport().is_active(): print('Connection is still alive. - ' + str(datetime.datetime.now().time())) else: print('Connection is NOT alive. - ' + str(datetime.datetime.now().time())) self.disconnectButton(self) tkLog.insert(0, "ERROR: Host doesn't found!") except: print("ERROR! during get_transport().isalive()") disconnector(event) messagebox.showerror(title="Host error", message="Host doesn't found on network!") tkLog.insert(0, "INFO: Host is not valid!")
def execute_composition(self, composition): """""" """Executa operacoes com apenas um automato.""" selected_tabs_indexes = self.get_selected_checkbuttons() if len(selected_tabs_indexes) < 2: messagebox.showerror('Erro', 'Você deve selecionar ao menos dois automatos.') else: selected_automatons = [] for selected_tab_index in selected_tabs_indexes: tab = self.opened_tabs[selected_tab_index] automaton = tab.get_automaton() selected_automatons.append(automaton) aut_op = AutomatonOperation(selected_automatons[0]) automaton_name = composition #+ '_' + selected_tab.get_file_name() result_automaton = None if composition == 'product': result_automaton = selected_automatons[0] for i in range(1, len(selected_automatons)): result_automaton = aut_op.product_composition(result_automaton, selected_automatons[i]) elif composition == 'parallel_composition': result_automaton = selected_automatons[0] for i in range(1, len(selected_automatons)): result_automaton = aut_op.parallel_composition(result_automaton, selected_automatons[i]) else: print('Operacao invalida.') tab = Tab(result_automaton, automaton_name, self.tabbed_frame) self.add_tab(tab)
def stop_parsing(self): """Stop the results process""" if self.parser._scoreboard_parser is not None: messagebox.showwarning("Warning", "Parsing cannot be stopped while results a scoreboard.") return self.parsing_control_button.config(state=tk.DISABLED) self.parsing_control_button.update() if self.minimap_enabled.get() is True and self.minimap is not None: self.minimap.destroy() self.close_overlay() self.parser.stop() self.parsing_control_button.config(text="Start Parsing", command=self.start_parsing) time.sleep(0.1) try: self.parser.join(timeout=2) except Exception as e: messagebox.showerror("Error", "While real-time results, the following error occurred:\n\n{}".format(e)) raise self.watching_stringvar.set("Watching no file...") print("[RealTimeFrame] RealTimeParser reference count: {}".format(sys.getrefcount(self.parser))) self.parser = None self.close_overlay() DiscordClient().send_recent_files(self.window) self.window.update_presence() self.parsing_control_button.config(state=tk.NORMAL) self.data.set(self.DATA_STR_BASE.format("Not real-time results\n"))
def display_no_subprocess_error(self): tkMessageBox.showerror( "Subprocess Startup Error", "IDLE's subprocess didn't make connection. Either IDLE can't " "start a subprocess or personal firewall software is blocking " "the connection.", master=self.tkconsole.text)
def execute_operation(self, operation): """Executa operacoes com apenas um automato.""" if self.tabbed_frame.index('end') == 0: messagebox.showerror('Erro', 'Não há nenhum autômato aberto.') else: selected_tab_index = self.tabbed_frame.index('current') selected_tab = self.opened_tabs[selected_tab_index] automaton = selected_tab.get_automaton() aut_op = AutomatonOperation(automaton) automaton_name = operation + '_' + selected_tab.get_file_name() result_automaton = None if operation == 'accessibility': result_automaton = aut_op.accessibility() elif operation == 'trim': result_automaton = aut_op.trim() elif operation == 'co_accessibility': result_automaton = aut_op.co_accessibility() elif operation == 'minimization': result_automaton = aut_op.minimization() elif operation == 'convertion': result_automaton = aut_op.convertion() else: print('Operacao invalida.') tab = Tab(result_automaton, automaton_name, self.tabbed_frame) self.add_tab(tab)
def save_as(self): import tkinter.messagebox as messagebox import tkinter.filedialog as filedialog import my_constant import my_io import traceback try: if self.clan.h: path = filedialog.asksaveasfilename(**my_constant.history_opt) if path: my_io.append_history(None, path, mode='clear') for item in self.clan.hv: my_io.append_history(item, path, check_exist=False) messagebox.showinfo('保存成功!', '已保存至' + path) if self.clan.d: path = filedialog.asksaveasfilename(**my_constant.donate_opt) if path: my_io.append_donate(None, path, mode='clear') for item in self.clan.dv: my_io.append_donate(item, path, check_exist=False) messagebox.showinfo('保存成功!', '已保存至' + path) except Exception as e: traceback.print_exc() messagebox.showerror('出错了!', '保存失败') self.master.master.focus_force()
def report_error(title ,msg): """ :param title: string :param msg: string :return: none """ ttk.showerror(title, msg)
def checkRegistration(self): username = self.sRegisterUser.get() password = self.sRegisterPass.get() confirmedPassword = self.sRegisterConPass.get() email = self.sRegisterEmail.get() emailFormat = re.compile("\w*@gatech.edu") if password != confirmedPassword or emailFormat.match(email) == None: if password != confirmedPassword: self.sRegisterPass.set("") self.sRegisterConPass.set("") error = messagebox.showerror("Passwords Doesn't Match", "Re-enter Password") elif emailFormat.match(email) == None: self.sRegisterEmail.set("") error = messagebox.showerror("Email Format Error", "Enter a Valid GT Email") else: num1 = self.connect("SELECT * FROM User WHERE Username = \'%s\'" % username, "Return Execution Number") num2 = self.connect("SELECT * FROM User WHERE Email = \'%s\'" % email, "Return Execution Number") if num1 != 0 or num2 != 0: error = messagebox.showerror("Existed Username or Email", "Pick Another Username or Email") else: parameter = (username, email, password, 2016, "NULL", "student") sql = "INSERT INTO User(Username, Email, Password, Year, Major, UserType) VALUES (\'%s\' ,\'%s\', \'%s\', \'%s\', \'%s\', \'%s\')" % parameter self.connect(sql, "Insertion") message = messagebox.showinfo("Congratulations", "Registered Successfully") self.registrationWin.withdraw() self.loginWin.deiconify()
def h2d(self): import my_constant import tkinter.messagebox as messagebox import tkinter.filedialog as filedialog import my_io import traceback play = self.master.master.play if not self.clan.h: FileMenu.read_h(self) if not self.clan.h: return path = filedialog.asksaveasfilename(**my_constant.donate_opt) if path: try: my_io.append_donate(None, path, mode='clear') my_io.append_history(None, path + '.clh', mode='clear') for item in self.clan.hv: self.clan.imah.copyfrom(item) play.InitFlag[0] = True play.flash() play.InitFlag[0] = False my_io.append_donate(self.clan.imad, path, check_exist=False) my_io.append_history(self.clan.imah, path+ '.clh', check_exist=False) play.cls() except Exception as e: print('path=%s\n%s'%(path,e)) traceback.print_exc() messagebox.showerror('出错了!', '保存失败') else: messagebox.showinfo('保存成功!', '已保存至' + path)
def fileDialog(self, fileOptions=None, mode='r', openMode=True): defaultFileOptions = {} defaultFileOptions['defaultextension'] = '' defaultFileOptions['filetypes'] = [] defaultFileOptions['initialdir'] = '' defaultFileOptions['initialfile'] = '' defaultFileOptions['parent'] = self.root defaultFileOptions['title'] = '' if fileOptions is not None: for key in fileOptions: defaultFileOptions[key] = fileOptions[key] if openMode is True: file = askopenfilename(**defaultFileOptions) if file is not None and file is not '': try : self.compressionCore.openImage(file) self.compressionCore.imageSquaring(self.NValue.get()) except Exception: messagebox.showerror( _("Error"), "It's impossible open the image.") return self.updateGUI(original=True) else: file = asksaveasfilename(**defaultFileOptions) if file is not None and file is not '': try: self.compressionCore.compressedImage.save(fp=file, format="bmp") except Exception: messagebox.showwarning( _("Error"), "Fail to save compressed image. Please try again.")
def runUpdate() : ''' Call the xrandr command line tool to implement the changes ''' cmd = ["xrandr"] for x in self.displayObjs : cmd.append("--output") cmd.append(x.display) if x.enabled == True : cmd.append("--auto") else : cmd.append("--off") continue if x.primary == True and UI.getPrimary() != x.display : cmd.append("--primary") if x.resolution != "Default" : cmd.append("--mode") cmd.append(x.resolution) if self.mirror.get() == False and x.position[1] != "None" : pos = x.position if pos[0] == "Left of" : cmd.append("--left-of") elif pos[0] == "Right of" : cmd.append("--right-of") elif pos[0] == "Above" : cmd.append("--above") else : cmd.append("--below") cmd.append(x.position[1]) error = Popen(cmd, stderr = PIPE).communicate() error = error[1].decode("utf-8") if error != "" : messagebox.showerror(title = "Xrandr error", message = error)
def reset() : rmFilesFailed = False question = "The following files will be deleted:\n\n ~/.gtkrc-2.0\n ~/.config/gtk-3.0/settings.ini\n ~/.icons/default/index.theme\n\nDo you want to continue?" choice = messagebox.askyesno(title = "Reset", message = question) if choice : homeDir = os.path.expanduser('~') try : os.remove(homeDir + "/.gtkrc-2.0") except FileNotFoundError : pass except IOError : rmFilesFailed = True try : os.remove(homeDir + "/.config/gtk-3.0/settings.ini") except FileNotFoundError : pass except IOError : rmFilesFailed = True try : os.remove(homeDir + "/.icons/default/index.theme") except FileNotFoundError : pass except IOError : rmFilesFailed = True if rmFilesFailed : messagebox.showerror(title = "Error", message = "Errors occured whilst removing the settings files.") ui.varOpG2.set(getResource("gtk2", "gtk-theme-name")) ui.varOpG3.set(getResource("gtk3", "gtk-theme-name")) ui.varOpFont.delete(0, len(ui.varOpFont.get())) ui.varOpFont.insert(0, getResource("gtk2", "gtk-font-name")) ui.varOpIcons.set(getResource("gtk2", "gtk-icon-theme-name")) ui.varOpCursors.set(getResource("xdg_cursor", "Inherits")) ui.varOpButtonImages.set(getResource("gtk2", "gtk-button-images")) ui.varOpMenuImages.set(getResource("gtk2", "gtk-menu-images")) ui.varOpDarkTheme.set(getResource("gtk3", "gtk-application-prefer-dark-theme"))
def saveAs(): f = asksaveasfile(mode='w',defaultextension='.txt') t = text.get(0.0,END) try: f.write(t.rstrip()) except: showerror(title="Error",message="File save fail...")
def download_export(): if not report_name.get() or not scheme_round.get() \ or not api_key.get(): messagebox.showerror( title="Error", message="All fields are required.") return file_path = get_file_path() if not file_path: return # Run the given report! try: REPORTS_DICT[report_name.get()]( scheme_round.get(), api_key.get(), file_path) messagebox.showinfo( title="Done!", message="Download complete! File saved to\n%s" % file_path) except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() message = ''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)) messagebox.showerror( title="Error", message="We experienced an error:\n " + message)
def start_youtube_dl(self): # Start downloading the specified url if self._output_path.get(): output_path = self._output_path.get() else: try: output_path = os.path.dirname(os.path.abspath(__file__)) except NameError: import sys output_path = os.path.dirname(os.path.abspath(sys.argv[0])) output_tmpl = output_path + '/%(title)s-%(id)s.%(ext)s' options = { 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio/best', 'merge_output_format': 'mp4', 'socket_timeout': '15', 'progress_hooks': [self._logger.log], 'ignoreerrors': True, 'outtmpl': output_tmpl, } if self._extract_audio.get(): options['format'] = 'bestaudio/best', options['postprocessors'] = [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '3', }] dl = YoutubeDL(options) status = dl.download([self._video_url.get()]) if status != 0: mbox.showerror("youtube-dl error", "An error happened whilst processing your video(s)") else: mbox.showinfo("youtube-dl finished", "Your video(s) have been successfully processed")
def connect(self, event=None): """ Attempts to connect to a Bluetooth device. If there is a Bluetooth Error, we set 'self.error_message' to equal the error in question so we can then flag our GUI that there was an issue. If we have succesfully connected, we set 'self.sock' to equal to the connected socket, this is then passed into the GUI within the calling function. Parameters ---------- event : tkinter event We just need this to enable keybinding <Return> to function properly. """ try: port = int(self.port.get()) address = self.address.get() except ValueError: messagebox.showerror("Error","Port must be an integer") else: try: sock = bt.BluetoothSocket(bt.RFCOMM) sock.connect((address, port)) self.sock = sock self.address = address self.port = port except bt.btcommon.BluetoothError as e: self.sock = None self.error_message = e self.cancel()
def install_graphics(self, listbox): """ Installs a graphics pack. Params: listbox Listbox containing the list of graphics packs. """ if len(listbox.curselection()) != 0: gfx_dir = listbox.get(listbox.curselection()[0]) if messagebox.askokcancel( message='Your graphics, settings and raws will be changed.', title='Are you sure?'): result = self.lnp.install_graphics(gfx_dir) if result is False: messagebox.showerror( title='Error occurred', message='Something went wrong: ' 'the graphics folder may be missing important files. ' 'Graphics may not be installed correctly.\n' 'See the output log for error details.') elif result: if messagebox.askyesno( 'Update Savegames?', 'Graphics and settings installed!\n' 'Would you like to update your savegames to ' 'properly use the new graphics?'): self.update_savegames() else: messagebox.showerror( title='Error occurred', message='Nothing was installed.\n' 'Folder does not exist or does not have required files ' 'or folders:\n'+str(gfx_dir)) binding.update()
def login(self): if self.sLoginUser.get() == "" or self.sLoginPass.get() == "": error = messagebox.showerror("Blank", "Fill in All Blanks") else: parameters = (self.sLoginUser.get(), self.sLoginPass.get()) num = self.connect("SELECT * FROM User WHERE Username = \'%s\' AND Password = \'%s\'" % parameters, "Return Execution Number") if num == 0: error = messagebox.showerror("Invalid Credentials", "Please Register") else: sql = "SELECT * FROM User WHERE UserType = 'student' AND Username = \'%s\'" % self.sLoginUser.get() isAdmin = self.connect(sql, "Return Execution Number") self.user = self.sLoginUser.get() message = messagebox.showinfo("Congratulations", "Login Successfully") if isAdmin != 0: username = self.sLoginUser.get() sMajor = self.connect("SELECT Major FROM User WHERE Username = \'%s\'" % username, "Return Single Item") self.dMajor = StringVar() self.dMajor.set(sMajor[0]) self.operation() self.dYear = StringVar() self.dYear.set(self.connect("SELECT Year FROM User WHERE Username = \'%s\'" % username, "Return Single Item")[0]) else: self.chooseFunctionality()
def submit_button(): #Defines the code run when the submit button is pressed suc_parse = True #Create a boolean var entered_text = entry_text_entry.get() #Get the text from the entry box entry_text_entry.delete(0, "end") #Delete the text in the entry box try: #Try to parse the number number_parse = p.parse( entered_text) #Set number_parse to hold the parsed information except: #If an exception is raised while parsing the number, it will instead do the following print("An error parsing the entered phone number has occured") m.showerror( "Error", "Error: The phone number is either not international or invalid\n(Error Code: NUM_PARSE)" ) #Creates a dialogue box that tells the user there has been an error with an okay button suc_parse = False if suc_parse is True: print("Number:", number_parse) number_time = timezone.time_zones_for_number( number_parse) #Get the timezone for the number number_time_single = number_time[ 0] #Set number_time_single to the first value of the list of time zones print("Time Zone: ", number_time_single) number_car = carrier.name_for_number(number_parse, 'GB') #Get the number's carrier print("Carrier: ", number_car) number_loc = geocoder.description_for_number( number_parse, 'en') #Get the numbers location (Kinda creepy...) print("Location: ", number_loc) number_is_valid = str(p.is_valid_number( number_parse)) #Check if the number is a valid number print("Valid Number: ", number_is_valid) number_is_possible = str(p.is_possible_number( number_parse)) #Check if the number is possible print("Possible Number: ", number_is_possible) number_country_code = str(number_parse.country_code ) #Get the country code and make it a string print("Country Code: ", number_country_code) output_textbox.configure( state="normal" ) #Sets the output text box to normal to allow it to be edited by the program output_textbox.delete( "1.0", "end") #Delete all previous text from the text box output_textbox.insert( "1.0", "Output:") #Print "Output:" at the start of the textbox output_textbox.insert( "end", "\nNumber: " + entered_text ) #Prints the variables at the end of the last line in the textbox output_textbox.insert("end", "\nLocation: " + number_loc) #Ditto output_textbox.insert("end", "\nCountry Code: " + number_country_code) #Ditto output_textbox.insert("end", "\nTime Zone: " + number_time_single) #Ditto output_textbox.insert("end", "\nCarrier: " + number_car) #Ditto output_textbox.insert("end", "\nValid Number: " + number_is_valid) #Ditto output_textbox.configure( state="disabled" ) #Sets the output text box to be disabled to prevent the user typing in it else: output_textbox.configure(state="normal") output_textbox.delete("1.0", "end") #Ditto output_textbox.insert("1.0", "Output:") #Ditto output_textbox.insert("end", "\nError") #Ditto output_textbox.configure(state="disabled")
def buscar(self, cedula): for cliente in biblioteca.getClientes(): if cliente.getCedula() == cedula: return self.mostrarInfo(cliente) messagebox.showerror("Error", "Lector no encontrado")
def showErrorDialog(errorMessage): showerror(title="Error", message=errorMessage)
def show_error(self, cause, exception, message): messagebox.showerror(str(cause), str(str(exception) + '\n' + message)) driver.get("https://github.com/Robswc/tradingview-trainer/wiki/Errors")
def searching(self): st = (self.s.get()) if (st == ''): ms.showerror('Empty Search Field....', 'Please enter the item to be searched') st = st.lower() reading = pd.read_csv("items.csv") fields = [] rows = [] data = [] s1 = '' s2 = '' with open('items.csv', 'r') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: fields.append(row) break for row in csvreader: rows.append(row) for i in range(len(rows)): reading = pd.read_csv("items.csv") s1 = reading.iloc[i, 1] s1 = s1.lower() if (s1 == st): s2 = s1 break else: continue if (s2 == st and s2 != ''): self.vsb.pack_forget() self.vsb.forget() self.v.pack_forget() self.canv.pack_forget() self.v.forget() self.canv.forget() self.v1 = Frame(self.master, bg='powder blue') self.v1.pack(side="left", fill="both", expand=True) Label(self.v1, text=fields[0][0], borderwidth=2, relief="raised", font=('Times New Roman', 15, 'bold'), bg='cadet blue', bd=5, pady=15, padx=0).grid(row=0, column=0, sticky=E + W) Label(self.v1, text=fields[0][1], borderwidth=2, relief="raised", font=('Times New Roman', 15, 'bold'), bg='cadet blue', bd=5, pady=15, padx=20).grid(row=0, column=1, sticky=E + W) Label(self.v1, text=fields[0][2], borderwidth=2, relief="raised", font=('Times New Roman', 15, 'bold'), bg='cadet blue', bd=5, pady=15, padx=20).grid(row=0, column=2, sticky=E + W) Label(self.v1, text=fields[0][3], borderwidth=2, relief="raised", font=('Times New Roman', 15, 'bold'), bg='cadet blue', bd=5, pady=15, padx=20).grid(row=0, column=3, sticky=E + W) Label(self.v1, text=fields[0][4], borderwidth=2, relief="raised", font=('Times New Roman', 15, 'bold'), bg='cadet blue', bd=5, pady=15, padx=20).grid(row=0, column=4, sticky=E + W) Label(self.v1, text=rows[i][0], borderwidth=2, relief="raised", font=('Times New Roman', 15), bg='cadet blue', bd=5, pady=15, padx=100).grid(row=i + 1, column=0, sticky=E + W) Label(self.v1, text=rows[i][1], borderwidth=2, relief="raised", font=('Times New Roman', 15), bg='cadet blue', bd=5, pady=15, padx=100).grid(row=i + 1, column=1, sticky=E + W) Label(self.v1, text=rows[i][2], borderwidth=2, relief="raised", font=('Times New Roman', 15), bg='cadet blue', bd=5, pady=15, padx=100).grid(row=i + 1, column=2, sticky=E + W) Label(self.v1, text=rows[i][3], borderwidth=2, relief="raised", font=('Times New Roman', 15), bg='cadet blue', bd=5, pady=15, padx=100).grid(row=i + 1, column=3, sticky=E + W) Label(self.v1, text=rows[i][4], borderwidth=2, relief="raised", font=('Times New Roman', 15), bg='cadet blue', bd=5, pady=15, padx=100).grid(row=i + 1, column=4, sticky=E + W) back = Button(self.v1, text=' Back ', bd=5, font=('Times New Roman', 15, 'bold'), height=0, width=0, bg='sky blue', relief='raised', command=self.backing).place(x=700, y=150) a = Button(self.v1, text=' + ', bd=5, font=('Times New Roman', 15, 'bold'), height=0, width=0, bg='sky blue', relief='raised', command=self.addition).place(x=1250, y=70) s = Button(self.v1, text=' - ', bd=5, font=('Times New Roman', 15, 'bold'), height=0, width=0, bg='sky blue', relief='raised', command=self.subtraction).place(x=1320, y=70) elif (s2 != st and st != ''): ms.showerror('Try Again.....', 'No Entry Found')
def notify_missing_selection(self): messagebox.showerror("Nothing selected", "Select an item and try again!")
def reply_mail_func( username, password, receiver_email="", Subject="", message="", list_file=[], crypto_type=None, ): port = 587 smtp_server = "smtp.gmail.com" # Neu khong co nguoi nhan if receiver_email != "": # Neu message khong rong hoac co file dinh kem if message != "" or list_file[0] != "": bbc = receiver_email msg = MIMEMultipart() # msg = MIMEMultipart("alternative"); #Dùng khi gửi theo dạng html # Thông tin về From, To, Subject, Bcc của mail. msg["From"] = username msg["To"] = receiver_email msg["Subject"] = Subject msg["Bcc"] = bbc print("send mail") # Neu message khong rong if message != "": # Message của người gửi muốn người nhận nhận được body_mail = message # Định dạng message của mail theo kiểu plain text và lưu vào message_mail message_mail = MIMEText(body_mail, "plain", "utf-8") # part2 = MIMEText(html, "html") # Đính kèm nội dung mail đang được lưu trong par1 vào msg msg.attach(message_mail) # Neu co file dinh kem if list_file[0] != "": attachments = list_file # In same directory as script # sau khi print ra thì filepath bị split mỗi kí tự thành 1 phần tử của list => sai # cần fix lỗi chỗ này. for i in range(0, len(attachments)): file = attachments[i] file_basename = os.path.basename(file) # Open PDF file in binary mode with open(file, "rb") as attachment: # Add file as application/octet-stream # Email client can usually download this automatically as attachment file_mail = MIMEBase("application", "octet-stream") file_mail.set_payload(attachment.read()) # Encode file in ASCII characters to send by email encoders.encode_base64(file_mail) # Add header as key/value pair to attachment part file_mail.add_header( "Content-Disposition", "attachment", filename=("utf-8", "", file_basename), ) msg.attach(file_mail) all_message = msg.as_string() try: # Tạo một đối tượng SMTP, cho phép kết nối tới server của SMTP và cho phép sử dụng các phương thức của SMTP server = smtplib.SMTP(smtp_server, port) # Tạo kết nối SMTP không bảo mật và mã hóa nó với starttls() server.starttls() # Đăng nhập tài khoản gmail của người gửi server.login(username, password) # Tiến hành gửi mail từ người gửi tới người nhận, message được định dang theo string. server.sendmail(username, receiver_email, all_message) # Trong trường hợp có lỗi khi kết nối tới server của SMTP hoặc xảy ra bất kì lỗi gì trong quá trình xử lí # Sẽ xuất thông báo lỗi except Exception as e: print(e) finally: messagebox.showinfo("Success", "Sent!") server.quit() # Khong co message va file else: messagebox.showerror("Error", "The content is empty!") # Khong co nguoi nhan else: messagebox.showerror("Error", "Please specify at least one recipient.!")
e_eur.insert( 0, round(float(e_uah.get()) / float(JSON_object[1]['sale']), 2)) e_rub.insert( 0, round(float(e_uah.get()) / float(JSON_object[2]['sale']), 2)) except: messagebox.showwarning('Check the amount you entered') root.destroy() try: html = urllib.request.urlopen( 'https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5') data = html.read() JSON_object = json.loads(data) except: messagebox.showerror('Error', 'Error getting currency exchange rates') # Header Frame header_frame = Frame(root) header_frame.pack(fill=X) header_frame.grid_columnconfigure(0, weight=1) header_frame.grid_columnconfigure(1, weight=1) header_frame.grid_columnconfigure(2, weight=1) # Header h_currency = Label(header_frame, text='Сurrency', bg='#ccc', font='Arial 12 bold') h_currency.grid(row=0, column=0, sticky=EW)
def __init__(self): self.success = False tries = 0 while not self.success: # Used a try statement so that if there is a connection error then the program does not crash immediately try: self.conn = mydb.cursor() self.conn.execute( """CREATE TABLE IF NOT EXISTS USERS (USER_ID INT AUTO_INCREMENT PRIMARY KEY , USERNAME TEXT NOT NULL, ENCRYPT_PASS TEXT NOT NULL, SALT_VAL TEXT NOT NULL, ADMIN INTEGER NOT NULL, EMAIL VARCHAR(320) NOT NULL, TARGET TEXT);""" ) self.conn.execute( """CREATE TABLE IF NOT EXISTS QUIZ (QUIZ_ID INT AUTO_INCREMENT PRIMARY KEY, TOPIC TEXT NOT NULL, DATE_SET TEXT NOT NULL);""" ) self.conn.execute( """CREATE TABLE IF NOT EXISTS QUESTIONS (QUESTION_ID INT AUTO_INCREMENT PRIMARY KEY, QUESTION_TEXT TEXT NOT NULL, TIMER INT NOT NULL);""" ) self.conn.execute( """CREATE TABLE IF NOT EXISTS ANSWERS (ANSWER_ID INT AUTO_INCREMENT PRIMARY KEY, ANSWER_TEXT TEXT NOT NULL, CORRECT INTEGER NOT NULL, PARENT_QUESTION INT NOT NULL, FOREIGN KEY (PARENT_QUESTION) REFERENCES QUESTIONS(QUESTION_ID));""" ) self.conn.execute( """CREATE TABLE IF NOT EXISTS QUIZ_QUESTIONS (QUIZ_NUM INT, QUESTION_NUM INT, QUESTION_NUMBER INT NOT NULL, FOREIGN KEY (QUIZ_NUM) REFERENCES QUIZ(QUIZ_ID), FOREIGN KEY (QUESTION_NUM) REFERENCES QUESTIONS(QUESTION_ID));""" ) self.conn.execute( """CREATE TABLE IF NOT EXISTS ASSIGNED_QUIZ (QUIZ_ASSIGNED INT NOT NULL, USER INT NOT NULL, COMPLETE INT NOT NULL, SCORE TEXT, DATE_COMPLETED TEXT, FOREIGN KEY (QUIZ_ASSIGNED) REFERENCES QUIZ(QUIZ_ID), FOREIGN KEY (USER) REFERENCES USERS(USER_ID), PRIMARY KEY(QUIZ_ASSIGNED, USER));""" ) mydb.commit() self.current_questions = [] self.current_user = "" self.question_names = [] self.current_test = None self.quiz_details = [] self.question_id = [] self.answers = [] self.question_details = [] self.personal_progress = [] self.average_progress = [] self.success = True except ConnectionRefusedError: tries += 1 if tries == 3: messagebox.showerror( "Max Attempts Reached", "The max amount of attempts have been reached please try again later", ) else: msgbox = messagebox.askquestion( 'Try Again?", "It seems there was an error with the connection to the server' "\nWould you like to try again?", icon="warning", ) if msgbox == "no": exit()
def error(): messagebox.showerror("Error", "Ocurrio un error inesperado")
def casting(): global counting1 global counting2 global counting3 global counting4 global counting5 global counting6 global counting7 global counting8 global counting9 global counting10 if cb1.get()==1: counting1+=1 if cb2.get()==1: counting2+=1 if cb3.get()==1: counting3+=1 if cb4.get()==1: counting4+=1 if cb5.get()==1: counting5+=1 if cb6.get()==1: counting6+=1 if cb7.get()==1: counting7+=1 if cb8.get()==1: counting8+=1 if cb9.get()==1: counting9+=1 if cb10.get()==1: counting10+=1 if (counting1+counting2+counting3+counting4+counting5+counting6+counting7+counting8+counting9+counting10)!=4: if (counting1+counting2+counting3+counting4+counting5+counting6+counting7+counting8+counting9+counting10)>=4: messagebox.showerror('error','only select 4 members') counting1=0 counting2=0 counting3=0 counting4=0 counting5=0 counting6=0 counting7=0 counting8=0 counting9=0 counting10=0 elif (counting1+counting2+counting3+counting4+counting5+counting6+counting7+counting8+counting9+counting10)<=4: messagebox.showerror('error','plz select 4 members') else: messagebox.showinfo('success','vote casted successfully') window.destroy() import main_2
def capture_and_mark(self): sl = StudentsList(self.class_name) students, roll_numbers = sl.load_pkl_file() FaceDetectObj = FaceDetect(self.class_name) Yes = True No = False Cancel = None i = 0 while i <= 2: captured_image = None frame = None students_present = [] while len(students_present) == 0: captured_image, frame = capture() students_present = FaceDetectObj.recognize( captured_image, roll_numbers) if students_present == "No Training Data": return try: name_student_present = students[roll_numbers.index( students_present[0])] except: messagebox.showerror( "Error", "Recognized student not in database\nUnable to mark attendance" ) return response = messagebox.askyesnocancel( "Confirm your identity", students_present[0] + '\n' + name_student_present) if response is Yes: wb = excel.attendance_workbook(self.class_name) excel.mark_present(wb, students_present, self.class_name) img_path = os.path.join(os.getcwd(), 'images', self.class_name, "s" + students_present[0][-2:], os.path.basename(captured_image)) cv2.imwrite(img_path, frame) os.remove(captured_image) messagebox.showinfo("Attendance Confirmation", "Your attendance is marked!") break elif response is Cancel: break elif response is No: if i == 2: img_path = os.path.join(os.getcwd(), 'images', self.class_name, "unrecognized students", os.path.basename(captured_image)) cv2.imwrite(img_path, frame) messagebox.showinfo( "Unrecognized Student", "You were not recognized as any student of this class.\nYour attendance will be marked later if you really are" ) cv2.imwrite(img_path, frame) os.remove(captured_image) i += 1
def open_file(event): global current_dir file_ptr = filedialog.askopenfile(mode='r', filetypes=[('All Files', '*.*')], initialdir=current_dir, title="Open a file | THE_ARYA") if file_ptr: current_dir = file_ptr.name name = current_dir.split("/")[-1] file_type = name.split(".")[-1] # Check if Image file if file_type in imageTypes: try: editBox["image"] = current_dir editBox.delete(0.0, END) for record in lineNo.get_children(): lineNo.delete(record) root.title(" " + name) return except Exception: messagebox.showerror( f"\tUnsupported Image type", f"This image is not supported try {', '.join(imageTypes)}") return # Get the keyword list with open("keyWordsList.json", "r") as keyJson: global key_words, comment_line json_list = keyJson.read() json_list = json.loads(json_list) try: key_words = json_list[file_type]["keywords"] comment_line = json_list[file_type]["comments"] except KeyError: messagebox.showerror( "\tUnsupported file type", "Goto 'About' Menu to look at the supported file types.") return keyJson.close() lineNo["state"] = "normal" lineNo.delete(1.0, END) lineNo["state"] = "disabled" index = 1 name = current_dir.split("/")[-1] root.title(" " + name) editBox.delete(0.0, END) # Access line... one at a time for line in file_ptr.readlines(): # print(line.split(' ')) editBox.insert(END, line) # Check if line is a comment try: if (file_type == "html" or file_type == "html" ) and line.lstrip()[0] + line.lstrip()[1] in comment_line: editBox.tag_configure("comments", foreground="#EC8B5E", selectforeground='#000000') editBox.tag_add("comments", index + 0.0, "current") lineNo["state"] = "normal" lineNo.insert(END, str(index) + "\n") lineNo["state"] = "disabled" index += 1 continue if line.lstrip()[0] in comment_line: editBox.tag_configure("comments", foreground="#EC8B5E", selectforeground='#000000') editBox.tag_add("comments", index + 0.0, "current") lineNo["state"] = "normal" lineNo.insert(END, str(index) + "\n") lineNo["state"] = "disabled" index += 1 continue except IndexError: pass # Check for functions i = 0 while i < len(line): if line[i] == '(': if line[i - 1].isalnum() or line[i - 1] == "_": j = i - 1 while j >= 0 and (line[j].isalnum() or line[j] == "_" or line[j] == "."): j -= 1 start = str(index) + '.' + str(j + 1) end = str(index) + '.' + str(i) editBox.tag_add("functions", start, end) i += 1 # Check for keywords for key in key_words: i = index + 0.0 start = editBox.search(rf'{key}[\s:{{\n;(>]', index=i, regexp=True, forwards=True, stopindex=END) if start != "": word = editBox.get(start, start + " wordend") start_int = start.split('.')[0] start_deci = int(start.split('.')[-1]) if word == "<": i = start_deci while i < len(line) - 1 and line[i] != " " and line[ i] != ">": i += 1 end = start_int + "." + str(i + 1) else: end = start_int + "." + str(start_deci + len(word)) editBox.tag_remove("functions", start, end) editBox.tag_add("keywords", start, end) # Check for Strings i = 0 while i < len(line): if line[i] == '"': j = i + 1 while j < len(line) - 1 and line[j] != '"': j += 1 start = str(index) + '.' + str(i) end = str(index) + '.' + str(j + 1) editBox.tag_remove("functions", start, end) editBox.tag_remove("keywords", start, end) editBox.tag_add("strings", start, end) i = j + 1 else: i += 1 lineNo["state"] = "normal" lineNo.insert(END, str(index) + "\n") lineNo["state"] = "disabled" index += 1 file_ptr.close()
def create_account(self, user, password, conf_password, admin, email, target): if admin == "True": admin = 1 if target != "N/A": messagebox.showerror("Error", "Teachers should not have targets") else: admin = 0 if target == "N/A": messagebox.showerror("Error", "Students should have a target") regex_email = "^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" regex_pass = "******" if re.search(regex_email, email): if not self.search_user(user): if conf_password == password: if re.search(regex_pass, password): salt = str(uuid.uuid4()) salted_pass = password + str(salt) hashed_pass = hashlib.md5(salted_pass.encode()) coded_pass = str(hashed_pass.hexdigest()) sql = """INSERT INTO USERS(USERNAME,ENCRYPT_PASS,SALT_VAL,ADMIN,EMAIL,TARGET) VALUES(%s,%s,%s,%s, %s,%s) """ val = [user, coded_pass, salt, admin, email, target] self.conn.execute(sql, val) else: messagebox.showerror( "Error", "Passwords must contain\nat least one letter and one number", ) else: messagebox.showerror("Error", "Passwords do not match") else: messagebox.showerror("Error", "That username is already taken") else: messagebox.showerror("Error", "Email does not exist")
def validate_input(self): error_type = "Input Error" #licence_no validation if self.entries["licence_no"] == '' \ or len( self.entries["licence_no"] ) > 15: msg = "Invalid Licence #: Must not be blank " + \ "and no longer than 15 characters\nErr 0xa3-5" tm.showerror(error_type, msg) return #class validation if self.entries["class"] == '' or len(self.entries["class"]) > 10: msg = "Invalid Class: Must not be blank and no " + \ "longer than 10 characters\nErr 0xa3-6" tm.showerror(error_type, msg) return #issuing_date validation try: date1 = datetime.strptime(self.entries["issuing_date"], "%d-%b-%Y") except: msg = "Invalid Issuing Date: Format must be DD-MMM-YYYY\n" + \ "Ex: 04-OCT-2015\nErr 0xa3-7" tm.showerror(error_type, msg) return #Make sure issuing date isn't in the future if date1 > datetime.now(): msg = "Invalid Issuing Date: Issuing Date cannot be in the " + \ "future\nErr 0xa3-8" tm.showerror(error_type, msg) return elif date1.date() < datetime.now().date(): msg = "The Issuing Date is listed as before today. Is that correct?" if not tm.askyesno("Input Confirmation", msg): return #expiring_date validation try: date2 = datetime.strptime(self.entries["expiring_date"], "%d-%b-%Y") except: msg = "Invalid Expiring Date: Format must be DD-MMM-YYYY\n" + \ "Ex: 04-OCT-2015\nErr 0xa3-9" tm.showerror(error_type, msg) return #Make sure issuing date and expiring date make sense together if date1 >= date2: msg = "Invalid Expiring Date: Must be later than Issuing Date\n" + \ "Err 0xa3-10" tm.showerror(error_type, msg) return if self.condition_id_list[0].strip() == '' \ and len(self.condition_id_list) == 1: self.condition_id_list = [] #condition_id validation and conversion to integers for i in range(len(self.condition_id_list)): try: self.condition_id_list[i] = int(self.condition_id_list[i]) if not (-2147483648 <= self.condition_id_list[i] < 2147483648): raise except: msg = "Invalid Condition ID '" + \ self.condition_id_list[i] + "': Must be an " + \ "integer between -(2^31)-1 and (2^31)-1\nErr 0xa3-13" tm.showerror(error_type, msg) return #sin validation if self.entries["sin"] == '' or len(self.entries["sin"]) > 15: msg = "Invalid SIN: Must not be blank and no longer than 15 " + \ "characters\nErr 0xa3-11" tm.showerror(error_type, msg) return #photo validation try: self.entries["photo"] = open(self.entries["photo"], 'rb').read() except: msg = "Invalid Photo File: File not found\n" + \ "Example filepath: Pictures/MyPicture.gif\nErr 0xa3-12" tm.showerror(error_type, msg) return #No errors encountered return True
dest = "//ds1517/destinationfolder" thumbnailsize = 1024, 1024 # user interface config setup if interfaceBool == True: tk.Tk().withdraw() messagebox.showinfo("tif2jpg", "1. Declare source folder \n\n2. Declare destination folder \n\n3. Enjoy automatic tif to jpg conversion ") src = filedialog.askdirectory(initialdir=src) if src == "": messagebox.showerror("tif2jpg", "Error: no source directory given") quit("The program will end because there was no source directory given.") dest = filedialog.askdirectory(initialdir=dest) if dest == "": messagebox.showerror("tif2jpg", "Error: no destination directory given") quit("The program will end because there was no destination directory given.") # progress bar setup def progress(count, total, suffix=''): bar_len = 60 filled_len = int(round(bar_len * count / float(total)))
def FindWeather(self): """Method to fetch data from API and update the widgets""" # Storing weather API key APIKEY = "64ed795e86547751fa5c3491ff2e31c0" # Storing the Weather URL (base URL) to which the requests has to be sent weather_URL = "http://api.openweathermap.org/data/2.5/weather?" # Fetching the user input city city_name = self.city_name.get() """Concatenating API key with user input city name with weather URL(base URL) and storing the complete URL in requests_URL and setting units = metric means temperature will be shown in celsius""" requests_URL = weather_URL + "appid=" + APIKEY + "&q=" + city_name + "&units=metric" # Sending the requests to URL and Fetching and Storing the response response = requests.get(requests_URL) # Converting the response which is in json format data into python format weather_response = response.json() # Printing weather_response dictionary(optional) print(json.dumps(weather_response, indent=2)) # some values from above weather_response dictionary will be fetched and displayed in tk window # Checking if the value is not equal to 404 if weather_response['cod'] != 404: # Fetching and storing the value of "main" key from weather_response weather_para = weather_response['main'] # Fetching and storing the value of "coord" key from weather_response coordinates = weather_response['coord'] # Storing latitude and longitude from coordinates latitude = str(coordinates['lat']) longitude = str(coordinates['lon']) # Fetching and storing the value of "wind" key from weather_response wind = weather_response['wind'] # Storing the speed key value from wind wind_speed = str(wind['speed']) # Check if deg key present in 'wind' key of weather_response dictionary if 'deg' in wind.keys(): wind_direct = str(['deg']) else: wind_direct = '' # Fetching and storing the temperature value from weather_para temperature = str(weather_para['temp']) # Fetching and storing the pressure value from weather_para pressure = str(weather_para['pressure']) # Fetching and storing the humidity value from weather_para humidity = str(weather_para['humidity']) # Fetching and storing weather value which is a list from weather_response weather_desc = weather_response['weather'] # Storing the description value from 0 index item of weather_disc list weather_description = weather_desc[0]['description'] """SHOWING THE RESULT IN TKINTER""" self.city_coordinate_entry.insert( '0', 'LATITUDE: ' + latitude + ' LONGITUDE: ' + longitude) self.temp_entry.insert('0', temperature + ' °C') self.humidity_entry.insert('0', str(humidity) + ' %') self.wind_entry.insert( '0', 'SPEED:' + wind_speed + ' m/s ' + 'DIRECTION:' + wind_direct + ' deg') self.pressure_entry.insert('0', pressure + ' hPa') self.desc_entry.insert('0', weather_description) else: # If cod key value is 404 then city not found messagebox.showerror('ERROR', 'CITY NOT FOUND!')
def incVolumn(self,vol): if(mx.music.get_busy()): mx.music.set_volume(vol/100) else: messagebox.showerror(title='Error !',message='No Song Selected!')
0, round(float(e_uah.get()) / float(JSON_object[0]['sale']), 2)) e_eur.insert( 0, round(float(e_uah.get()) / float(JSON_object[1]['sale']), 2)) e_rur.insert( 0, round(float(e_uah.get()) / float(JSON_object[2]['sale']), 2)) except: messagebox.showwarning('Warning', 'Проверьте введенную сумму') try: html = urllib.request.urlopen( 'https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5') data = html.read() JSON_object = json.loads(data) except: messagebox.showerror("Error", 'Ошибка получения курсов валют') # Header Frame header_frame = Frame(root) header_frame.pack(fill=X) header_frame.grid_columnconfigure(0, weight=1) header_frame.grid_columnconfigure(1, weight=1) header_frame.grid_columnconfigure(2, weight=1) # Header h_currency = Label(header_frame, text="Валюта", bg="#ccc", font="Arial 12 bold") h_currency.grid(row=0, column=0, sticky=EW) h_buy = Label(header_frame, text="Покупка", bg="#ccc", font="Arial 12 bold")
def submit_form(self): #Get each input value self.entries = { "licence_no": self.licence_no_entry.get().strip(), "class": self.class_entry.get().strip(), "issuing_date": self.issuing_date_entry.get().strip(), "expiring_date": self.expiring_date_entry.get().strip(), "sin": self.sin_entry.get().strip(), "photo": self.photo_entry.get() } #Get the Condition IDs self.condition_id_list = self.condition_id_list_entry.get().split(",") #Check if input is valid if not self.validate_input(): return msg = "Are you sure you want to submit?" if not tm.askyesno("Submit Confirmation", msg): return cursor = self.userCx.cursor() error_type = "Submit Failure" #Create savepoint here and specify size of photo cursor.execute("SAVEPOINT App3Save") cursor.setinputsizes(photo=cx_Oracle.BLOB) #Try to insert Licence statement = "INSERT INTO drive_licence \ VALUES( :licence_no, :sin, :class, \ :photo, :issuing_date, :expiring_date )" try: cursor.execute(statement, self.entries) except cx_Oracle.DatabaseError as exc: cursor.execute("ROLLBACK to App3Save") error, = exc.args if error.code == 1: #Licence_no exists or person already has one #Test if licence already exists statement = "SELECT licence_no FROM drive_licence \ WHERE licence_no = :a" try: entry = self.entries["licence_no"].ljust(15) cursor.execute(statement, a=entry) except: #Unknown error tm.showerror(error_type, "Unexpected Error\nErr 0xa3-14") cursor.close() return if len(cursor.fetchall()) == 0: #Sin must be taken tm.showerror( error_type, "SIN '" + \ self.entries["sin"] + \ "' already has a licence\nErr 0xa3-15" ) else: #Licence was found, therefore it's already taken tm.showerror( error_type, "Licence # '" + \ self.entries["licence_no"] + \ "' is already in the database\nErr 0xa3-16" ) elif error.code == 2291: #sin does not exist tm.showerror( error_type, "SIN '" + \ str(self.entries["sin"]) + "' does not exist\nErr 0xa3-17") else: #Unknown error tm.showerror(error_type, error.message + "\nErr 0xa3-18") cursor.close() return #Try to insert Licence Restrictions statement = "INSERT INTO restriction VALUES( :a, :b )" for condition_id in self.condition_id_list: try: cursor.execute( statement, \ a=self.entries["licence_no"], b=condition_id ) except cx_Oracle.DatabaseError as exc: cursor.execute("ROLLBACK to App3Save") cursor.close() error, = exc.args if error.code == 1: #Duplicate exists tm.showerror( error_type, "Condition ID '" + \ str(condition_id) + \ "' entered more than once\nErr 0x3-19" ) elif error.code == 2291: #Licence exists -> ConditionID doesn't tm.showerror( error_type, "Condition ID '" + \ str( condition_id ) + "' does not exist\nErr 0xa3-20" ) else: #Unknown error tm.showerror(error_type, error.message + "\nErr 0xa3-21") return #SQL statements executed successfully cursor.close() self.userCx.commit() #Success message successInfo = "Licence # '" + self.entries["licence_no"] + \ "' has been added to the database\nSIN: " + \ self.entries["sin"] + "\nCondition IDs: " + \ ", ".join( str(i) for i in self.condition_id_list ) tm.showinfo("Success!", successInfo) self.destroy()
def connActivity(): #++++++++++++++++++CREATE THE FUNCTION THAT CONNECTS THE DEVICE WITH THE PC using the IPAddress#++++++++++++++++++ def connIP(): ipa = ip.get() #get ip address from entry widget por = sp.check_output("zaglarh tcpip " + port) output = sp.check_output("zaglarh connect " + ipa + ":" + port) confOutput = "b'connected to " + str(ipa) + ":" + port + "\\r\\n'" if confOutput == str(output): time.sleep(5) clearTerm(0) mb.showinfo("Device Connected", "You can pull it out now (^~^)\n Press OK to continue.") conn.destroy() bulkee() else: mb.showerror("Not Connected", "Try again!!!\n\nPS: Check that the IP ADDRESS is correct.\nAnd also that you're on the same network") #++++++++++++++++++CREATE FUNCTION TO SKIP CONNECTION PAGE#++++++++++++++++++ def skipConn(): conn.destroy() bulkee() #++++++++++++++++++Destroy login window and create connection page#++++++++++++++++++ login.destroy() conn = Tk() conn.title("Bulkee@Connection Page") conn.geometry("800x540+290+90") bgPic=PhotoImage(file="C:/Virtualenvironment/TeLon/Include/images/back.png") connLogo=PhotoImage(file="C:/Virtualenvironment/TeLon/Include/images/cn.png") connBackground = Label(conn, image=bgPic) connBackground.place(x=0, y=0, relwidth=1, relheight=1) #++++++++++++++++++Set Display Name#++++++++++++++++++ title = Label(conn, text = "CONNECT", font = ("times new roman", 30, "bold"), bg = "#2896e0", fg = "WHITE", bd = 10, relief = FLAT) title.place (x=0,y=0,relwidth=1) #++++++++++++++++++Create Connection Frame#++++++++++++++++++ connFrame = Frame (conn, bg="WHITE") connFrame.place(x=245, y=260) logoL = Label(connFrame, image = connLogo, bg = "white", bd = 0).grid(row = 0, columnspan = 2, padx = 100, pady = 20) #++++++++++++++++++Handle error that occurs if the device isnt attached with USB#++++++++++++++++++ try: #++++++++++++++++++STRING MANIPULATION TO GET REAL IP ADDRESS FROM dumped IP Info#++++++++++++++++++s byteIP = sp.check_output("zaglarh shell ip route") stringIP = str(byteIP).rpartition("src") rIP = stringIP[2] #get the third item in the tuple rrIP = rIP.rpartition("\\r\\n") ipAdd = rrIP[0] #get the first item in the new partition devName = sp.check_output("zaglarh shell getprop transsion.device.name") #++++++++++++++++++Initialize a text class to insert texts in the current window#++++++++++++++++++ text = Text(conn, width = 70, height = 10, wrap = WORD) text1 = sp.check_output("zaglarh devices") text2 = "PS: If you device isnt connected, kindly get your IP Address(" + ipAdd + ") below and place it in the to box connect. Or skip if your device is present.\n\n<-------------------------------------------------------------------->\n" text3 = sp.check_output("zaglarh shell ip route") text.insert(INSERT, text1) text.insert(INSERT, text2) text.insert(INSERT, text3) text.place(x=115, y=100) ip = StringVar() # Create StringVar variable to store the ip address. pType = StringVar() #Create variable to store the phone type ipEntry = Entry (connFrame, bg = "WHITE", width = 30, textvariable = ip).grid (rows = 2, columnspan = 2, pady = 20) spPhone = Spinbox (connFrame, state = "readonly", textvariable = pType, bg = "WHITE", wrap = True, width = 30, values = (devName, "HUAWEI Y7 Prime 2019", "Infinix Note 5 Stylus", "Samsung Galaxy S7 Edge", "Samsung Galaxy S8 Edge", "Nokia ")).grid(row = 3, columnspan = 2, padx = 10, pady = 1) btn = Button(connFrame, relief = GROOVE, command = connIP, text = "Connect & Start", bg = "#2896e0", width = 6, fg = "WHITE", font = ("times new roman", 15, "bold")).grid(row = 4, column = 0, pady = 10) btn2 = Button(connFrame, relief = GROOVE, text = "Skip and Start", command = skipConn, bg = "RED", width = 6, fg = "WHITE", font = ("times new roman", 15, "bold")).grid(row = 4, column = 1) except sp.CalledProcessError: clearTerm(0) mb.showerror("Device Not Attached", "Hey, put it inside me (^~^)") conn.update_idletasks() conn.mainloop()
def press_error_btn(): messagebox.showerror(title='Hi', # 显示错误 message='ERROR')
def PollModule(self,event=None): """ polls the module every 0.5s. The time is adjusted to maintain accuracy """ if self.Module != None: self.PollCount += 0.5 err = False try: self.pd = self.Module.Poll() except: err = True if err or self.pd == None: tkmb.showerror("comms error","lost connection ") self.window.quit() else: # calculate some useful values out of the measured data phi_rad = math.acos(self.pd.Pf) phi_deg = math.degrees(phi_rad) spwr = self.pd.Volt * self.pd.Current qpwr =spwr * math.sin(phi_rad) for i,fd in enumerate(self.FD): if i < 6: # values directly measured if self.x10: val = getattr(self.pd,fd.Attr) / fd.Scale s = fd.Fmtx10.format(val) else: val = getattr(self.pd,fd.Attr) s = fd.Fmtx1.format(val) else: # calculated values if fd.Attr == 'Phi': val =phi_deg s=fd.Fmtx1.format(val) elif fd.Attr == 'Q-pwr': val = qpwr if self.x10: val = val/fd.Scale s = fd.Fmtx10.format(val) else: s=fd.Fmtx1.format(val) elif fd.Attr == 'S-pwr': val = spwr if self.x10: val = val/fd.Scale s = fd.Fmtx10.format(val) else: s=fd.Fmtx1.format(val) else: s='???' # should never happen if self.RecName != '': self.RecData[fd.Idx][self.REC_VALUE] = val self.RecData[fd.Idx][self.REC_N] += 1 self.RecData[fd.Idx][self.REC_SUM] += val self.datavalue[i].configure(text=s) if self.RecName != '': # for debug only # rs = '' # for RD in self.RecData: # rs += '{:9.5f}'.format(RD[self.REC_VALUE]) + ',' # s = '{:5n},{:s}{:1n}'.format(0,rs,0) # self.f.write(s+'\n') if self.PollCount % self.RecSpd == 0: rs = '' # for building a recording string for RD in self.RecData: if self.RecAve: rs += '{:9.5f}'.format(RD[self.REC_SUM] / RD[self.REC_N]) + ',' RD[self.REC_SUM] = 0.0 RD[self.REC_N] = 0 else: rs += '{:9.5f}'.format(RD[self.REC_VALUE]) + ',' s = '{:5n},{:s}{:1n}'.format(self.PollCount,rs,10 if self.x10 else 1) try: self.f.write(s+'\n') self.RecNums = self.RecNums +1 self.labelRNums.config(text= '#{:7n}'.format(self.RecNums)) except: tkmb.showerror("rec error","can't write to "+self.RecName) self.RecName = '' self.labelRNums.config(text= '') self.labelRecFn.config(text= '{:24s}'.format(self.RecName)) self.buttRec.config(relief='raised') elapsed = (perf_counter_ns() - self.ProgStart)//1000000 # time in ms since start time2sleep= 500 - (elapsed % 500) self.window.after(time2sleep, self.PollModule)
def start_read(self): """请求服务器发送书签页""" self.sc.send_message(MessageType.start_read, self.user + '*' + self.bkname) # 接收书签所处页数 message = self.sc.recv_message() if message['type'] == MessageType.page_num: self.page_num = message['parameters'] print('《{}》书签位于第{}页'.format(self.bkname, message['parameters'])) elif message['type'] == MessageType.no_book: messagebox.showerror('请求失败', '查无此书,请返回刷新书籍列表!') return else: print('未能成功接收到书签页数!错误:{}'.format(message['type'])) messagebox.showerror('请求失败', '未能成功接收到书签页数!错误:{}'.format(message['type'])) return # 接收总页数 message = self.sc.recv_message() if message['type'] == MessageType.total_page: self.total_page = message['parameters'] print('《{}》共{}页'.format(self.bkname, message['parameters'])) elif message['type'] == MessageType.no_book: messagebox.showerror('请求失败', '查无此书,请返回刷新书籍列表!') return else: print('未能成功接收到总页数!错误:{}'.format(message['type'])) return # 接收章节列表 message = self.sc.recv_message() if message['type'] == MessageType.send_chapter: self.chapter = message['parameters'] self.total_chapter = len(self.chapter) self.chap_num = self.get_chapter() self.chapbtn['text'] = self.chapter[self.chap_num][0] # 更新要显示的章节名 print('《{}》共{}章'.format(self.bkname, self.total_chapter)) elif message['type'] == MessageType.no_book: messagebox.showerror('请求失败', '查无此书,请返回刷新书籍列表!') return else: print('未能成功接收到章节列表!错误:{}'.format(message['type'])) return #接收书签页 message = self.sc.recv_message() if not message: messagebox.showerror('连接失败', 'QAQ 网络出现了问题,请稍后再试~') elif message['type'] == MessageType.no_book: messagebox.showerror('请求失败', '查无此书,请返回刷新书籍列表!') return elif message['type'] == MessageType.send_page: print('成功接收书签页') if message['parameters'][0] == '#': message['parameters'] = message['parameters'][1:] self.text.insert(1.0, message['parameters']) else: messagebox.showerror('请求失败', '请求失败,服务器未返回书签页!') return
def startProgram(): if ChoosedCom == None: messagebox.showerror('Brak danych!', 'Kombinacje nie zostały wybrane') return Path = PathEntry.get() PDMS = PDMSEntry.get() AutoPipe = AutoPipeEntry.get() #Załadowanie kombinacji z drugiego okna Com = ChoosedCom #Nazwa raportu wyjściowego Out = 'Raport_policzony.xlsx' #Wczytanie pliku pdms i podział na kolumny PdmsFile = pd.read_csv(f'{PDMS}', sep='|', decimal='.') #Czyszczenie danych PdmsFile = PdmsFile.replace("=", "'=", regex=True) PdmsFile = PdmsFile.replace('degree', '', regex=True) PdmsFile['ORIANGLE'] = [ clean_angles(oriangle) for oriangle in PdmsFile['ORIANGLE'] ] PdmsFile['NAME'] = [clean_name(name) for name in PdmsFile['NAME']] #Obliczanie sinusów i cosinusów PdmsFile['SIN'] = [sin(oriangle) for oriangle in PdmsFile['ORIANGLE']] PdmsFile['COS'] = [cos(oriangle) for oriangle in PdmsFile['ORIANGLE']] #Zmiana nazwy kolumny PdmsFile.rename(columns={ 'DTXR': 'Description', 'Position WRT Owner': 'WRT', 'NAME': 'Name' }, inplace=True) #Obrabianie Koordynatów PdmsFile[['PDMS - CoodX', 'PDMS - CoordY', 'PDMS - CoordZ']] = [[ x[:x.find('mm')], x[x.find('mm') + 3:x.find('mm', x.find('mm') + 3)], x[x.find('mm', x.find('mm') + 3) + 3:len(x) - 2] ] for x in PdmsFile['WRT']] PdmsFile['PDMS - CoodX'] = [ x[x.find(' '):] for x in PdmsFile['PDMS - CoodX'] ] PdmsFile['PDMS - CoordY'] = [ x[x.find(' '):] for x in PdmsFile['PDMS - CoordY'] ] PdmsFile['PDMS - CoordZ'] = [ x[x.find(' '):] for x in PdmsFile['PDMS - CoordZ'] ] PdmsFile[['PDMS - CoodX', 'PDMS - CoordY', 'PDMS - CoordZ']] = PdmsFile[[ 'PDMS - CoodX', 'PDMS - CoordY', 'PDMS - CoordZ' ]].astype(float).astype(int) #Wczytanie pliku autopipe AutoPipeFile = pd.read_excel(f'{AutoPipe}') #Selekcja kolumn AutoPipeFile = AutoPipeFile[[ 'Tag No.', 'Combination', 'GlobalFX', 'GlobalFY', 'GlobalFZ', 'CoordX', 'CoordY', 'CoordZ' ]] #Usuwanie pierwszego wiersza AutoPipeFile = AutoPipeFile.drop(0) #Filtrowanie po wybranych kombinacjach obliczeniowych AutoPipeFile = AutoPipeFile[AutoPipeFile['Combination'].isin(Com)] #Zmiana danych na liczbowe AutoPipeFile[['GlobalFX', 'GlobalFY', 'GlobalFZ' ]] = AutoPipeFile[['GlobalFX', 'GlobalFY', 'GlobalFZ']].astype(float) #Zmiana nazw kolummn AutoPipeFile.rename(columns={ 'Tag No.': 'Name', 'GlobalFZ': 'FZ', 'GlobalFX': 'FX', 'GlobalFY': 'FY', 'CoordX': 'AutoPipe - CoordX', 'CoordY': 'AutoPipe - CoordY', 'CoordZ': 'AutoPipe - CoordZ' }, inplace=True) #Czyszczenie nazw z "\" AutoPipeFile['Name'] = [ clean_name(name) for name in AutoPipeFile['Name'] ] AutoPipeFileCoord = AutoPipeFile[[ 'Name', 'AutoPipe - CoordX', 'AutoPipe - CoordY', 'AutoPipe - CoordZ' ]] #Sumowanie wartości dla kombinacji obliczeniowej dla każdego zamocowania AutoPipeFile = AutoPipeFile.groupby(['Name', 'Combination' ]).sum().reset_index() #Obrabianie Koordynatów AutoPipeFileCoord['AutoPipe - CoordX'] = [ np.absolute(int(x[:str(x).find('.')])) for x in AutoPipeFileCoord['AutoPipe - CoordX'] ] AutoPipeFileCoord['AutoPipe - CoordY'] = [ np.absolute(int(x[:str(x).find('.')])) for x in AutoPipeFileCoord['AutoPipe - CoordY'] ] AutoPipeFileCoord['AutoPipe - CoordZ'] = [ np.absolute(int(x[:str(x).find('.')])) for x in AutoPipeFileCoord['AutoPipe - CoordZ'] ] AutoPipeFileCoord[[ 'AutoPipe - CoordX', 'AutoPipe - CoordY', 'AutoPipe - CoordZ' ]].astype(int) #MAX,MIN,EXTREMUM Colums Conditions = [Extremum.get(), Maximum.get(), Minimum.get()] allDf = [] if Extremum.get() != '': #Wybór ekstremalnej wartości dla każdej osi #Zwracanie wartości bezwzględej AutoPipeFileEXT = AutoPipeFile.copy() AutoPipeFileEXT['ABS(FX)'] = [ np.absolute(x) for x in AutoPipeFile['FX'] ] AutoPipeFileEXT['ABS(FY)'] = [ np.absolute(x) for x in AutoPipeFile['FY'] ] AutoPipeFileEXT['ABS(FZ)'] = [ np.absolute(x) for x in AutoPipeFile['FZ'] ] AutoPipeFileFxEXT = AutoPipeFileEXT[[ 'Name', 'ABS(FX)' ]].groupby('Name').max().reset_index() AutoPipeFileFxEXT = pd.merge( AutoPipeFileFxEXT, AutoPipeFileEXT[['FX', 'Combination', 'ABS(FX)']], on='ABS(FX)', how='left').rename(columns={ 'Combination': 'Extremum - CombinationFx', 'FX': 'Extremum - FX' }).drop_duplicates('Name') AutoPipeFileFyEXT = AutoPipeFileEXT[[ 'Name', 'ABS(FY)' ]].groupby('Name').max().reset_index() AutoPipeFileFyEXT = pd.merge( AutoPipeFileFyEXT, AutoPipeFileEXT[['FY', 'Combination', 'ABS(FY)']], on='ABS(FY)', how='left').rename(columns={ 'Combination': 'Extremum - CombinationFy', 'FY': 'Extremum - FY' }).drop_duplicates('Name') AutoPipeFileFzEXT = AutoPipeFileEXT[[ 'Name', 'ABS(FZ)' ]].groupby('Name').max().reset_index() AutoPipeFileFzEXT = pd.merge( AutoPipeFileFzEXT, AutoPipeFileEXT[['FZ', 'Combination', 'ABS(FZ)']], on='ABS(FZ)', how='left').rename(columns={ 'Combination': 'Extremum - CombinationFz', 'FZ': 'Extremum - FZ' }).drop_duplicates('Name') allDf.extend( [AutoPipeFileFxEXT, AutoPipeFileFyEXT, AutoPipeFileFzEXT]) if Minimum.get() != '': AutoPipeFileFxMIN = AutoPipeFile[[ 'Name', 'FX' ]].groupby('Name').min().reset_index() AutoPipeFileFxMIN = pd.merge( AutoPipeFileFxMIN, AutoPipeFile[['FX', 'Combination']], on='FX', how='left').rename(columns={ 'Combination': 'Minimum - CombinationFx', 'FX': 'Minimum - FX' }).drop_duplicates('Name') AutoPipeFileFyMIN = AutoPipeFile[[ 'Name', 'FY' ]].groupby('Name').min().reset_index() AutoPipeFileFyMIN = pd.merge( AutoPipeFileFyMIN, AutoPipeFile[['FY', 'Combination']], on='FY', how='left').rename(columns={ 'Combination': 'Minimum - CombinationFy', 'FY': 'Minimum - FY' }).drop_duplicates('Name') AutoPipeFileFzMIN = AutoPipeFile[[ 'Name', 'FZ' ]].groupby('Name').min().reset_index() AutoPipeFileFzMIN = pd.merge( AutoPipeFileFzMIN, AutoPipeFile[['FZ', 'Combination']], on='FZ', how='left').rename(columns={ 'Combination': 'Minimum - CombinationFz', 'FZ': 'Minimum - FZ' }).drop_duplicates('Name') allDf.extend( [AutoPipeFileFxMIN, AutoPipeFileFyMIN, AutoPipeFileFzMIN]) if Maximum.get() != '': AutoPipeFileFxMAX = AutoPipeFile[[ 'Name', 'FX' ]].groupby('Name').max().reset_index() AutoPipeFileFxMAX = pd.merge( AutoPipeFileFxMAX, AutoPipeFile[['FX', 'Combination']], on='FX', how='left').rename(columns={ 'Combination': 'Maximum - CombinationFx', 'FX': 'Maximum - FX' }).drop_duplicates('Name') AutoPipeFileFyMAX = AutoPipeFile[[ 'Name', 'FY' ]].groupby('Name').max().reset_index() AutoPipeFileFyMAX = pd.merge( AutoPipeFileFyMAX, AutoPipeFile[['FY', 'Combination']], on='FY', how='left').rename(columns={ 'Combination': 'Maximum - CombinationFy', 'FY': 'Maximum - FY' }).drop_duplicates('Name') AutoPipeFileFzMAX = AutoPipeFile[[ 'Name', 'FZ' ]].groupby('Name').max().reset_index() AutoPipeFileFzMAX = pd.merge( AutoPipeFileFzMAX, AutoPipeFile[['FZ', 'Combination']], on='FZ', how='left').rename(columns={ 'Combination': 'Maximum - CombinationFz', 'FZ': 'Maximum - FZ' }).drop_duplicates('Name') allDf.extend( [AutoPipeFileFxMAX, AutoPipeFileFyMAX, AutoPipeFileFzMAX]) #Łączenie wszystkich osi razem do jednego pliku MergedData = reduce( lambda x, y: pd.merge(x, y, on=['Name'], how='outer'), allDf) #Usuwanie duplikatów MergedData.drop_duplicates('Name') MergedData.to_excel(f'{Path}{Out}') #Łączenie danych z PDMS'a i AutoPipe'a FinalList = ['Name', 'Description'] for x in Conditions: if x != '': FinalList.extend([ f'{x} - CombinationFx', f'{x} - FX', f'{x} - CombinationFy', f'{x} - FY', f'{x} - CombinationFz', f'{x} - FZ' ]) FinalReport = pd.merge(MergedData, PdmsFile[[ 'Name', 'ORIANGLE', 'SIN', 'COS', 'Description', 'PDMS - CoodX', 'PDMS - CoordY', 'PDMS - CoordZ' ]], on='Name', how='left') #Przeliczanie wartości lokalnych dla danych globalnych i kąta nachylenia w płaszczyźnie X Y #MAX,MIN,EXTREMUM Colums allDf = [] if Extremum.get() != '': FinalReportEXT = FinalReport.copy() FinalReportEXT[['Extremum - FA', 'Extremum - FL']] = FinalReport[[ 'Extremum - FX', 'Extremum - FY', 'ORIANGLE', 'COS', 'SIN', ]].apply(force, axis=1) FinalReportEXT['Extremum - FV'] = FinalReport['Extremum - FZ'] allDf.append(FinalReportEXT) if Minimum.get() != '': FinalReportMIN = FinalReport.copy() FinalReportMIN[['Minimum - FA', 'Minimum - FL']] = FinalReport[[ 'Minimum - FX', 'Minimum - FY', 'ORIANGLE', 'COS', 'SIN', ]].apply(force, axis=1) FinalReportMIN['Minimum - FV'] = FinalReport['Minimum - FZ'] allDf.append(FinalReportMIN) if Maximum.get() != '': FinalReportMAX = FinalReport.copy() FinalReportMAX[['Maximum - FA', 'Maximum - FL']] = FinalReport[[ 'Maximum - FX', 'Maximum - FY', 'ORIANGLE', 'COS', 'SIN', ]].apply(force, axis=1) FinalReportMAX['Maximum - FV'] = FinalReport['Maximum - FZ'] allDf.append(FinalReportMAX) allDf.append(AutoPipeFileCoord) #Łączenie raportów z siłami FinalReport = reduce( lambda x, y: pd.merge(x, y, on=['Name'], how='outer'), allDf) for x in Conditions: if x != '': FinalList.extend([f'{x} - FL', f'{x} - FA', f'{x} - FV']) #Sprawdzanie poprawności koordynatów FinalReport['Difference - CoordX'] = np.absolute( FinalReport['AutoPipe - CoordX'] - FinalReport['PDMS - CoodX']) FinalReport['Difference - CoordY'] = np.absolute( FinalReport['AutoPipe - CoordY'] - FinalReport['PDMS - CoordY']) FinalReport['Difference - CoordZ'] = np.absolute( FinalReport['AutoPipe - CoordZ'] - FinalReport['PDMS - CoordZ']) FinalList.extend([ 'PDMS - CoodX', 'PDMS - CoordY', 'PDMS - CoordZ', 'AutoPipe - CoordX', 'AutoPipe - CoordY', 'AutoPipe - CoordZ', 'Difference - CoordX', 'Difference - CoordY', 'Difference - CoordZ' ]) FinalReport = FinalReport[FinalList] # Wygenerowanie raportu końcowego FinalReport.to_excel(f'{Path}{Out}') #Wiadomość na koniec generowania raportu messagebox.showinfo('Raport Gotowy!', f'Plik został zapisany pod scieżką: {Path}{Out}')
def error_message(self, message): tkMessageBox.showerror("Error", message)
def runTest(self, name, initial_speed, ramp, finished): try: # Initialize the robot commanded speed to 0 self.autospeed = 0 self.discard_data = True # print() # print(name) # print() # print('Please enable the robot in autonomous mode.') # print() # print( # 'WARNING: It will not automatically stop moving, so disable the robot' # ) # print('before it hits something!') # print('') self.STATE.postTask(lambda: messagebox.showinfo( "Running " + name, "Please enable the robot in autonomous mode, and then " + "disable it before it runs out of space.\n" + "Note: The robot will continue to move until you disable it - " + "It is your responsibility to ensure it does not hit anything!", parent=self.STATE.mainGUI, )) # Wait for robot to signal that it entered autonomous mode with self.lock: self.lock.wait_for(lambda: self.mode == "auto") data = self.wait_for_stationary() if data is not None: if data in ("connected", "disconnected"): self.STATE.postTask(lambda: messagebox.showerror( "Error!", "NT disconnected", parent=self.STATE.mainGUI) ) return else: self.STATE.postTask(lambda: messagebox.showerror( "Error!", "Robot exited autonomous mode before data could be sent?", parent=self.STATE.mainGUI, )) return # Ramp the voltage at the specified rate data = self.ramp_voltage_in_auto(initial_speed, ramp) if data in ("connected", "disconnected"): self.STATE.postTask(lambda: messagebox.showerror( "Error!", "NT disconnected", parent=self.STATE.mainGUI)) return # output sanity check if len(data) < 3: self.STATE.postTask(lambda: messagebox.showwarning( "Warning!", "Last run produced an unusually small amount of data", parent=self.STATE.mainGUI, )) else: distance = data[-1][ENCODER_P_COL] - data[0][ENCODER_P_COL] self.STATE.postTask(lambda: messagebox.showinfo( name + " Complete", "The robot reported traveling the following distance:\n" + "%.3f units" % distance + "\n" + "If seems wrong, you should change the encoder calibration" + "in the robot program or fix your encoders!", parent=self.STATE.mainGUI, )) self.stored_data[name] = data finally: self.autospeed = 0 self.STATE.postTask(finished)
#!/usr/bin/env python3 # -*- coding=utf8 -*- """ # Author: Carinda # Created Time : 2020/8/20 10:18:49 # File Name: dialogTable.py # Description: """ import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s: %(message)s') from tkinter.filedialog import askopenfilename from tkinter.colorchooser import askcolor from tkinter.messagebox import askquestion, showerror from tkinter.simpledialog import askfloat demos = { 'Open': askopenfilename, 'Color': askcolor, 'Query': lambda: askquestion('Warning', 'You typed "rm *"\nConfirm?'), 'Error': lambda: showerror('Error!', "What do you want!"), 'Input': lambda: askfloat('Entry', 'Enter you phone number'), }
"""Error message box. Stand-alone example from Tk Assistant. stevepython.wordpress.com""" from tkinter import messagebox, Tk root = Tk() root.withdraw() messagebox.showerror('Error', 'This is a error message box.')
def checkError(): if(year.get()>givenyear.get() or (year.get()==givenyear.get() and month.get()>givenmonth.get())or (year.get()==givenyear.get() and month.get()==givenmonth.get() and day.get()>givenday.get())): messagebox.showerror("Wrong Input") clearAll() return -1