def loginCheck(self): self.username=self.E1.get() #gets the username from the entry widget self.password=self.E2.get() #gets the password from the entry widget cursor=self.database.cursor() #forms a cursor #forms the sql query that will check for the username in the existing database sql = "SELECT 'patient' AS Usertype FROM PATIENT WHERE Username=%s and Password=%s " \ "UNION " \ "SELECT 'doctor' AS Usertype FROM DOCTOR WHERE Username=%s and Password=%s " \ "UNION " \ "SELECT 'admin' AS Usertype FROM ADMINISTRATION_PERSONNEL WHERE Username=%s and Password=%s" loginSuccess = cursor.execute(sql,(self.username, self.password, self.username, self.password, self.username, self.password)) #executes the query if loginSuccess: self.currentUser = cursor.fetchone()[0] messagebox.showinfo("Login Successful","Login Successful") #if the login is successful, it'll return a message saying the same. if self.currentUser == "patient": self.patientHomepageWin = self.patientHomepage() elif self.currentUser == "doctor": self.doctorHomepageWin = self.doctorHomepage() else: self.adminHomepageWin = self.adminHomepage() else: messagebox.showwarning("Login Unsuccessful","Wrong Username/password combination, please try again") #if the login is unsuccessful, it'll return a message saying the user to check his/her username/password combo cursor.close() self.database.commit() self.mainWin.withdraw()
def _do_open_file (self, fpath): """ effective procedure for opening file to import; """ # is a genuine CSV file? if self.is_csv(fpath): # update options dir self.options["dirs"]["namedb_import_dir"] = OP.dirname(fpath) # update current path self.current_path = fpath # update file infos self.container.get_stringvar("lbl_file_path")\ .set(P.shorten_path(fpath, limit=50)) # show contents preview self._fill_preview(fpath) # update field assignment order self._fill_fields(fpath) # prepare to import self.BTN_IMPORT.configure( text=_("Import"), command=self.slot_file_import ) self.stop_import = False # not a CSV file else: # notify user MB.showwarning( title=_("Attention"), message=_("Invalid CSV file format. Not supported."), parent=self, )
def create_schedule(self): self.create_schedule_form = Toplevel() self.create_schedule_form.title("создание расписания") self.variable = StringVar(self.create_schedule_form) self.variable_objects = StringVar(self.create_schedule_form) self.get_group = adapter.get_group() self.get_objects = adapter.get_objects() if self.get_group == False or self.get_objects == False: messagebox.showwarning( "Error", "Ошибка, групп не найдено или нет предметов" ) self.create_schedule_form.destroy() w = OptionMenu(self.create_schedule_form, self.variable, *self.get_group) object_for_group = OptionMenu(self.create_schedule_form, self.variable_objects, *self.get_objects) w.pack() object_for_group.pack() self.send_engine = Button(self.create_schedule_form,text = "создать",command = self.send_engine_controller) self.send_engine.pack()
def ok(self): urlname = self.name.get().strip() url = self.url.get().strip() if urlname == '' or url == '': messagebox.showwarning('警告', '输入不能为空!') return # if self.parent.urllist.has_key(self.parent.name): # has_key() 方法 if urlname in self.parent.urllist: if messagebox.askyesno('提示', '名称 ‘%s’ 已存在,将会覆盖,是否继续?' % urlname): pass else: return # 顯式地更改父窗口參數 # self.parent.name = urlname # self.parent.url = url self.parent.urllist[urlname] = url # 重新加载列表 self.parent.listbox.delete(0, END) for item in self.parent.urllist: self.parent.listbox.insert(END, item) self.destroy() # 銷燬窗口
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 showwarning(*args): root = Tk() root.withdraw() messagebox.showwarning(*args, parent=root) root.destroy()
def delete_files(self): if self.default_algorithm.get() == 'Zero fill': method = 0 if self.default_algorithm.get() == 'Secure Erase': method = 1 if self.default_algorithm.get() == 'Schneier': method = 2 if self.default_algorithm.get() == 'Random Data': method = 3 path = '\\\\.\\' + self.default_drive.get() + ':' if 'File System Type: NTFS' in get_file_system(path): selection = self.files_list.curselection() value = list(map(lambda x: self.files_list.get(x),selection)) delete_files = [] for filename in value: for directory in self.files_in_drive: if directory['dir_path'] == filename: delete_files.append(directory) break for files in directory['list_child']: if files['dir_path'] == filename: delete_files.append(files) break for files in delete_files: deletion(files,method) self.files_list.delete(0,tk.END) rootPath = self.default_drive.get() self.files_in_drive = getfiles(path,rootPath) for directory in self.files_in_drive: self.files_list.insert(tk.END,directory['dir_path']) for files in directory['list_child']: self.files_list.insert(tk.END,files['dir_path']) messagebox.showinfo('Delete Files','Done!') else: messagebox.showwarning('Error','NTFS only!')
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 mem_new(self, c=[0]): from my_class import Member new = self.name.get(), self.abbr.get(), self.level.get(), self.rank.get() if not new[0]: return flag = not new[1] kw = {} kw['name'], kw['abbr'], kw['level'], kw['rank'] = new kw['abbr'] = ( kw['abbr'] or '%d'%c[0] ).rjust(3,'_') kw['level'] = int (kw['level'] or 1) kw['rank'] = kw['rank'] or kw['level'] * 100 title = "添加成员" message = "新成员信息:\n Name: %s\n Abbr: %s\n Town Hall Lv: %s\n Rank: %s"\ ""%(kw['name'], kw['abbr'], kw['level'], kw['rank']) if kw['abbr'] in self.clan.member: messagebox.showwarning("错误!","该缩写已存在,如需帮助请联系Ceilopty") return if not messagebox.askyesno(title, message): return try: new = Member(self.clan, **kw) self.clan[kw['abbr']] = new except BaseException as e: messagebox.showwarning("成员创建失败","错误:%s\n如有疑问请咨询Ceilopty"%e) else: self.unsaved = True if flag: c[0] += 1 messagebox.showinfo("成员创建成功","即日起成员%s可以参战!"%kw['name']) self.flash()
def print_all(): """Print all the things.""" for number, entry in enumerate(entries, start = 1): if (len(entry.get()) > 0): messagebox.showwarning('DO IT! JUST DO IT!', '{0}){1}\n\n\t{2}'.format(number, entry.get(), (random.choice(LaBeouf))))
def addProduct(*args): """ This adds the currently selected product using information from a database that is fetched by the ShoppingCart class and then stored in Product and Material objects. """ if (selectedProductVar.get() != "<Product>"): indx = self.possibleProductNames.index(selectedProductVar.get()) product, messages = ShoppingCart.AddProduct(self.possibleProductIds[indx], productNumber.get()) #There are several possible messages we might get back after trying to add a product. Let's display those to the user first. for msg in messages: messagebox.showwarning("Possible Problem", msg) if (product != None): newProd = (product.columnInfo["ProductDescription"], product.columnInfo["ProductFinish"], product.quantity) #First check to see if the product and its materials exist already! #There should only be 1 instance of each product and material in the tables. if (self.productTable.exists(product.PK)): self.productTable.item(product.PK, values=newProd) else: self.productTable.insert("", "end", iid=product.PK, values=newProd) AdjustColumnWidths(self.productTable, self.productHeader, self.productColWidth, newProd) sortby(self.productTable, self.productHeader[0], False)
def already_exist(self, warn=True, bcode=None): if warn: mbox.showwarning("Warning", "Barcode is already in table!"); return False else: if not self.isunique(bcode): self.updatecomment(self.existcomment)
def checkName(name): if name == '': messagebox.showwarning("Whoops", "Name should not be blank.") return 0 if name in names: messagebox.showwarning("Name exists", "Sheet name already exists!") return 0
def loadfunc() : if not exists(filename) : print( filename, 'does not exists!' ) return for i, l in enumerate(open( filename )) : v1, v2, v3 = l.split('\t') if v1 : try : assert v1 in selections except : showwarning('WARNING', 'ChIP name is not in the selection list!' ) print( 'v1:',v1 ) print( 'selection:', selection ) continue if v2 : try: assert v2 in selections except : showwarning('WARNING', 'Input name is not in the selection list!' ) print( 'v2:',v2 ) print( 'selection:', selection ) return chip_vars[i].set(v1.strip()) input_vars[i].set(v2.strip()) group_vars[i].set(v3.strip())
def open(self, *args): """ open a file on your computer return data """ self.fname.set(askopenfilename(filetypes=[("text file", ".txt")], parent=self.window, title="Open a file")) try: self.data, self.time_sample = load_file(self.fname.get())[1:] self.time_sample = 1 / self.time_sample except FileNotFoundError: pass except FileError: showwarning(title="Error", message="Can't read file {}!".format(self.fname.get()), parent=self.window) else: self.fshortname.set(self.fname.get().split("/")[-1]) self.flenght.set(len(self.data) / self.time_sample) self.time["start"].set(0) self.time["end"].set(self.flenght.get()) self.amplitude["start"].set(min(self.data) - 10) self.amplitude["end"].set(max(self.data) + 10) self.refresh() return
def salvar(self, event): """ Evento para salvar e modificar registros. """ id = self.lbl_numero_id['text'] descricao = self.edt_descricao.get() conta_pai = self.cbx_conta_pai.get().split(':')[0] conta_pai = 0 if conta_pai == self.default_conta_pai else conta_pai lancamento_padrao = self.cbx_tipo.get() lancamento_padrao = "c" if lancamento_padrao == self.default_tipo else lancamento_padrao if not descricao: showwarning("Atenção", "Descrição vazia") else: if conta_pai == 0: parametros = {'descricao': descricao, 'lancamento_padrao': lancamento_padrao} else: parametros = {'descricao': descricao, 'conta_pai': conta_pai, 'lancamento_padrao': lancamento_padrao} if id == self.default_id: self.contas.inserir(**parametros) showinfo("Informação", "Cadastro realizado com sucesso") self.limpar_campos() else: self.contas.atualizar(**parametros, filtro='id = %d' % id) showinfo("Informação", "Atualização realizada com sucesso") self.limpar_campos()
def loadfunc() : #self.readpaste( filename, info_text ) for i, l in enumerate(open( contrast_fn )) : v1, v2 = l.split('\t') v1 = v1.strip() v2 = v2.strip() if v1 : try : assert v1 in groups except : showwarning('WARNING', 'Group name is not in the selection list!' ) print( 'v1:',v1 ) print( 'group:', groups ) continue if v2 : try: assert v2 in groups except : showwarning('WARNING', 'Group name is not in the selection list!' ) print( 'v2:',v2 ) print( 'group:', groups ) continue contrast_vars[i][0].set(v1) contrast_vars[i][1].set(v2)
def next(self): self.setOptions() # refresh options nextIsDown = self.options["direction"] == "down" # check that asme instance applies if not self.options["messagesLog"]: if self.modelXbrl is None: return if self.modelManager.modelXbrl != self.modelXbrl: messagebox.showerror(_("Next cannot be completed"), _("A different DTS is active, than find was initiated with. Please press 'find' to re-search with the current DTS"), parent=self) return lenObjsList = len(self.objsList) if lenObjsList == 0: messagebox.showwarning(_("Next cannot be completed"), _("No matches were found. Please try a different search."), parent=self) return if self.foundIndex < 0 and nextIsDown: self.foundIndex += 1 elif self.foundIndex >= lenObjsList and not nextIsDown: self.foundIndex -= 1 if 0 <= self.foundIndex < lenObjsList: objectFound = self.objsList[self.foundIndex][2] if self.options["messagesLog"]: self.modelManager.cntlr.logView.selectLine(objectFound) else: self.modelManager.modelXbrl.viewModelObject(objectFound) self.resultText.setValue("{0}, selection {1} of {2}".format(self.result, self.foundIndex + 1, len(self.objsList) ) ) self.foundIndex += 1 if nextIsDown else -1 elif nextIsDown: self.resultText.setValue("{0}, selection at end".format(self.result) ) else: self.resultText.setValue("{0}, selection at start".format(self.result) )
def validate_entry(self, filename): if os.path.getsize(filename) == 1024: self.filetype = "entry" else: self.filetype = "partition" if self.filetype == "partition": p = entry.Partition(filename) while True: try: w = p.walk() self.add_entry(w.__next__()) except StopIteration: break else: with open(filename, "rb") as data: d = data.read(1024) e = entry.Entry(d) try: e.validate() except ValidationError: showwarning( "Invalid Mft entry", "This file is not a valid MFT entry. Its signature value is %s" % e.signature.raw, ) else: self.add_entry(e)
def generate_by_date_2(): try: cur=dbconn.cursor() cur.execute("select distinct mc.ministry_county_name,c.course_name, r.first_name, r.middle_name, r.sur_name, r.personal_id, r.national_id, r.mobile_no, r.email_id,r.scheduled_from,r.scheduled_to,r.attended_from,r.attended_to from register r join ministry_county mc on mc.ministry_county_id = r.ministry_county_id join courses c on c.course_id = r.course_id where scheduled_from between '%s' and '%s' order by scheduled_from;"%(fromentry.get(),toentry.get())) get_sch_report=cur.fetchall() if get_sch_report ==[]: messagebox.showwarning('Warning', "No data found from period '%s' to '%s'" %(fromentry.get(),toentry.get())) else: file_format = [("CSV files","*.csv"),("Text files","*.txt"),("All files","*.*")] all_trained_mdac_report = asksaveasfilename( title ="Save As='.csv'", initialdir="C:\\Users\\usrname", initialfile ='Generate by date All Trained MDAC Report', defaultextension=".csv", filetypes= file_format) outfile = open(all_trained_mdac_report, "w") writer = csv.writer(outfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) writer.writerow( ['ministry_county_name','course_name','first_name','middle_name','sur_name','personal_id','national_id','mobile_no','email_id','scheduled_from','scheduled_to','attended_from','attended_to']) for i in get_sch_report: writer.writerows([i]) outfile.close() gui.destroy() except psycopg2.InternalError: messagebox.showerror('Error', 'You need to input dates') messagebox.showerror('Error', 'Fatal Error occured') sys.exit(0) except: pass
def searchCodebarre(self): """Méthode de recherche de code barres. Suppression du contenu de la Listbox à chaque appel de cette méthode Vérifie que la zone de texte n'est pas vide. """ self.clear() # variable stockant le retour de la recherche réinitialisée. self.rslt = "" try: self.cnx = search.Connexion() if (len(self.strCodebarre.get()) != 0): self.rslt = self.cnx.checkCodebarre(self.strCodebarre.get()) if len(self.rslt) == 0: self.rslt = "Aucune\ donnée." self.lstResultQuery.set(self.rslt) else: msgbox.showwarning("Attention", "Zone de recherche vide.") self.cnx.arret() except: msgbox.showwarning("Connexion", "Impossible de se connecter avec \ la base : base activée ? paramètres corrects ?") # suppression du texte dans l'Entry self.strCodebarre.set("") # le focus redirigé sur l'Entry self.txtSearch.focus_set()
def update_excel(self): if '__kopia__pliku__.xlsx' not in self.file_path and self.count == True: messagebox.showwarning(title=None, message="Dla kolejnych odznaczen ustaw sciezke dla nowo stworzonego pliku kopii!") else: try: if self.E2.get().isdigit(): find_value = int(self.E2.get()) else: find_value = self.E2.get() book = load_workbook(self.file_path) # color_fill = PatternFill(patternType='solid', fgColor=Color('56FFE9')) orange = PatternFill(patternType='solid', fgColor=Color('FFFFC000')) sheets = book.get_sheet_names() check_amount = 0 for count, sheet in enumerate(sheets): sheet = book.get_sheet_by_name(sheets[count]) for row in sheet.rows: for cell in row: if cell.value == find_value: check_amount += 1 cell.fill = orange if check_amount == 0: messagebox.showinfo(title=None, message="Odznaczenie nie powiodło sie") else: book.save('__kopia__pliku__.xlsx') self.count = True messagebox.showinfo(title=None, message="Pomyslnie zaktualizowano dokument") except: messagebox.showwarning(title="Uwaga", message="Sprobuj ponownie wybrac plik!")
def deleteRecord(): """this function only shows warning, no record editing possible""" logging.info('deleteRecord: ') popup = Toplevel(c, takefocus=True) # child window popup.wm_title("Usuwanie wpisu z tabeli %s" % gTable) popLabel = ttk.Label(popup, text="Czy na pewno chcesz usunąć ten wpis?") yesButton = ttk.Button(popup, text="Tak", command=lambda: writeDeleteRecord(ID, popup)) noButton = ttk.Button(popup, text="Nie", command=lambda: closePopup(popup), default='active') popLabel.grid(column=0, row=0, padx=5, pady=5, columnspan=2) yesButton.grid(column=0, row=1) noButton.grid(column=1, row=1) if not lbox.curselection(): logging.warning('pop-up : nie zaznaczono rekordu do modyfikacji') messagebox.showwarning( "Usuwanie rekordu", "Nie zaznaczono rekordu do usunięcia" ) return # get the selected record id selection = lbox.curselection() recordString = lbox.get(selection[0]) logging.debug('%r' % recordString) ID = recordString.split(' ; ')[-1] # ID is after ; in listbox logging.debug('%r' % ID) deleteID.set(updateString + ' ; ' + ID) logging.debug("updateString: %r" % updateString)
def validate(self): """Verify that a name was defined and only one between data and image path was set.""" img_name = self.img_name.get() img_path = self.img_path.get() img_data = self.img_data.get('1.0', 'end').strip() if not img_name or (img_path and img_data) or \ (not img_path and not img_data): showwarning("Invalid image specification", "You need to specify an image name and then either specify " "a image path or the image data, at least.", parent=self) return False try: img_format = self.img_format.get() if self._editing: # try to create an image with current settings, if it succeeds # then it is ok to change the image being edited. self._create_image(None, img_path, img_data, img_format) self._change_image(img_path, img_data, img_format) else: self._create_image(img_name, img_path, img_data, img_format) except Tkinter.TclError as err: showerror("Error creating image", err, parent=self) return False else: return True
def updateRecord(): logging.info('updateRecord: ') child = Toplevel(c, takefocus=True) # child window child.wm_title("Modyfikacja wpisu w tabeli %s" % gTable) e = Entry(child, textvariable = updateEntry, width=70) ok = ttk.Button(child, text = 'OK', command=lambda: writeUpdateRecord(child), default='active') # refactor to class with self.updateWindow e.grid(column=1, row=1, sticky=W) ok.grid(column=2, row=1, sticky=W) e.focus_set() if not lbox.curselection(): logging.warning('pop-up : nie zaznaczono rekordu do modyfikacji') messagebox.showwarning( "Modyfikacja rekordu", "Nie zaznaczono rekordu do modyfikacji" ) child.destroy() return # get the selected record id selection = lbox.curselection() recordString = lbox.get(selection[0]) logging.debug('%r' % recordString) ID = recordString.split(' ; ')[-1] # ID is after ; in listbox logging.debug('%r' % ID) cursor.execute('SELECT * FROM %s WHERE ID = %s' % (gTable, ID)) tupleString = cursor.fetchone() updateString = ' ; '.join(str(x) for x in tupleString[1:]) # take subset without ID # save to state variable and add ID information updateEntry.set(updateString + ' ; ' + ID) logging.debug("updateString: %r" % updateString)
def show_test_vad_open(self, path=path_to_test): askopenfile = filedialog.askopenfile(filetypes=[("Wave audio files", "*.wav *.wave")], defaultextension=".wav", initialdir=path) if not askopenfile is None: test(WavFile(askopenfile.name), self.nbc) else: messagebox.showwarning("Warning", "You should select one file. Please, try again")
def submitComplaintButtonClicked(self): #submit the complaint to database restaurant = self.complaintInfoList[0].get().split(',')[0] self.cursor.execute("SELECT rid FROM restaurant WHERE name = %s", restaurant) restaurantID = self.cursor.fetchone()[0] phone = self.complaintInfoList[4].get() cdate = self.complaintInfoList[1].get() customerFirstName = self.complaintInfoList[2].get() customerLastName = self.complaintInfoList[3].get() ''' address = self.complaintInfoList[0].get().split(', ', 1)[1] print("address: " + address) self.cursor.execute("SELECT email FROM restaurant WHERE name = %s", restaurant) operatorEmail = self.cursor.fetchone()[0] print("email: " + operatorEmail) self.cursor.execute("SELECT firstname, lastname FROM operatorowner WHERE email = %s", operatorEmail) nameTuple = self.cursor.fetchall() operatorName = nameTuple[0][0] + ' ' + nameTuple[0][1] print(operatorName) self.cursor.execute("SELECT totalscore FROM inspection WHERE rid = %s ORDER BY idate DESC", restaurantID) score = self.cursor.fetchone()[0] print("score: " + str(score)) ''' complaint = self.complaintInfoList[-1].get() result = self.cursor.execute("SELECT * FROM customer WHERE phone = %s", phone) if not result: self.cursor.execute("INSERT INTO customer (phone, firstname, lastname) VALUES (%s, %s, %s)", (phone, customerFirstName, customerLastName)) self.db.commit() self.cursor.execute("INSERT INTO complaint (rid, phone, cdate, description) VALUES (%s, %s, %s, %s)", (restaurantID, phone, cdate, complaint)) self.db.commit() messagebox.showwarning("Submission Successful!", "Your complaint has been submitted.") self.fileComplaintWindow.withdraw() self.guestMenuWindow.deiconify()
def ev_displayOPD(self): self._updateFromGUI() if self.inst.pupilopd is None: tkMessageBox.showwarning( message="You currently have selected no OPD file (i.e. perfect telescope) so there's nothing to display.", title="Can't Display") else: if self._enable_opdserver and 'ITM' in self.opd_name: opd = self.inst.pupilopd # will contain the actual OPD loaded in _updateFromGUI just above else: opd = fits.getdata(self.inst.pupilopd[0]) # in this case self.inst.pupilopd is a tuple with a string so we have to load it here. if len(opd.shape) >2: opd = opd[self.opd_i,:,:] # grab correct slice masked_opd = np.ma.masked_equal(opd, 0) # mask out all pixels which are exactly 0, outside the aperture cmap = matplotlib.cm.jet cmap.set_bad('k', 0.8) plt.clf() plt.imshow(masked_opd, cmap=cmap, interpolation='nearest', vmin=-0.5, vmax=0.5) plt.title("OPD from %s, #%d" %( os.path.basename(self.opd_name), self.opd_i)) cb = plt.colorbar(orientation='vertical') cb.set_label('microns') f = plt.gcf() plt.text(0.4, 0.02, "OPD WFE = %6.2f nm RMS" % (masked_opd.std()*1000.), transform=f.transFigure) self._refresh_window()
def start(self): # Validate self.entry and begin path = self.entry.get() if os.path.exists(path): if os.path.isfile(path): try: bank = testbank.parse(path) engine = teach_me.FAQ(bank) except xml.sax._exceptions.SAXParseException as error: title = error.getMessage().title() LN = error.getLineNumber() CN = error.getColumnNumber() message = 'Line {}, Column {}'.format(LN, CN) showerror(title, message, master=self) except AssertionError as error: title = 'Validation Error' message = error.args[0] showerror(title, message, master=self) except: title = 'Error' message = 'Unknown exception was thrown!' showerror(title, message, master=self) else: self.done = False self.next_event = iter(engine).__next__ self.after_idle(self.execute_quiz) else: title = 'Warning' message = 'File does not exist.' showwarning(title, message, master=self) else: title = 'Information' message = 'Path does not exist.' showinfo(title, message, master=self)
def openInExcel(self): # 1. Check a valid schedule exists if (len(self._guiMngr.getPages()) <= 2): messagebox.showwarning("Export Error", "You need to create the schedule first!") return # 2. Get and write temporary file tempFilename = None with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as tFile: for i in range(2, len(self._guiMngr.getPages())): pageName = self._guiMngr.getPageName(i) pageBegin = (0, 0) page = self._guiMngr.getPage(pageName) tFile.write('{}\n'.format(pageName)) self._writePageData(page, tFile, pageBegin, '\t') tFile.write('\n') tempFilename = tFile.name # 3. Open the tempfile in Excel from sys import platform as _platform if(_platform == "linux" or _platform == "linux2"): subprocess.Popen(['subl', tempFilename]) subprocess.Popen(['libreoffice', '--calc', tempFilename]) else: subprocess.Popen(["start", "excel.exe", tempFilename], shell=True)
def trainModel(): messagebox.showwarning( "TRAINING", "Only use if location of CCTV is changed. It will take a lot of time to be completed" ) os.system('python cnn_model.py')
def warn(): msgbox.showwarning("Warning", "Warning Message")
def leerInfoInputCliente(self): try: data = int(self.cuadroCliente.get()) return data except: messagebox.showwarning("Clientes", "Error en los datos")
def warning(title, msg): dialog(lambda t=title, m=msg: messagebox.showwarning(t, m))
def message(): counter = 0 for i in range(0, 500): counter += 1 messagebox.showwarning("Windows", "Your data is getting repaired DON\'T SHUT DOWN!") if counter == 100: messagebox.showwarning("Windows", "Don´t DO THAT!") if counter == 200: messagebox.showwarning("Windows", "Don´t DO THAT!") if counter == 300: messagebox.showwarning("Windows", "Don´t DO THAT!") if counter == 400: messagebox.showwarning("Windows", "Don´t DO THAT!") if counter == 500: messagebox.showwarning("Windows", "Don´t DO THAT!")
def store_data(store=False): if data_stored_yes: yes_no_5 = messagebox.askyesno( "Warning", "This entry may have already been logged. Save a new entry anyways?" ) if yes_no_5: data_stored(False) store_data() else: if direct_called_yes: try: # appends excel file and saves as new entry check.lists_append() wb = openpyxl.load_workbook("Directory.xlsx") ws = wb.active bold_12_font = Font(size=12, bold=True) ws.append(sw.all_vars) wb.save("Directory.xlsx") # appends csv file and saves as new entry with open("Directory.csv", "a+", newline="") as append_csv: append = csv.writer(append_csv) append.writerow(sw.all_vars) data_stored(True) if store == True: # This is for new entry button storing text before clearing text messagebox.showwarning("Data Stored", "Data saved successfully.") clear_text() elif store == "exit": # this is for saving before exiting the program messagebox.showwarning("Data Stored", "Data saved successfully.") window.destroy() else: # this is for save button storing text yes_no_3 = messagebox.askyesno( "Data Stored", "Data saved successfully. Do you want to clear the text?" ) if yes_no_3: combo_client.configure(values=check.client_names) combo_task.configure(values=check.tasks_types) clear_text() else: data_stored(True) pass except PermissionError: messagebox.showerror( "Error", "Please close the Directory Excel or CSV file before continuing." ) store_data() except FileNotFoundError: checker() store_data() except NameError: pass else: checker() store_data()
conn = pymysql.connect(host='127.0.0.1', user='******', password='', db='basedatos', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) cur = conn.cursor() #cur.execute("DROP TABLE IF EXISTS profesor") #sql="CREATE TABLE profesor ( nombre VARCHAR(30) NOT NULL , cedula VARCHAR(30) NOT NULL )" sql = "SELECT * FROM estudiantes " #sql="SELECT * FROM profesores " #mostrar en un label de tkinter concatenando con un + #ingresar las notas #con insert cur.execute(sql) result = cur.fetchall() print(result) cur.close() conn.close #print ("conectada") except: messagebox.showwarning("¡ATENCION!", "NO EXISTE EL USUARIO") finally: conn.close
def bags_decode_QR(bag_count): y = 0 cipher = [] final = [] plain = [] new = [] key = 3 transposition = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] start_bag_decode = time.time() x = int(bag_count) while (x > 0): print(x) messagebox.showwarning("Verification process","You have " + str(x) + " more bag(s) to be scanned.\n" + str(j) + " bag(s) verified successfully.") #call decode QR #write decoded value to a text file #os.system("QR.exe") os.system(r'Next_decode.exe') f = open("Bag_check.txt","r") bag_check = f.read() f.close() #Decrypting transposition cipher final = bag_check for a in final: new.append(a) j = 0 for m in range(0,4): for n in range(0,4): #j = j+1 transposition[m][n] = new[j] j = j+1 print(transposition) cipher = [] for m in range(0,4): for n in range(0,4): #j = j+1 cipher.append(transposition[n][m]) cipher = cipher[0:11] print(cipher) for a in cipher: print(a) diff = int(a) - key if (diff < 0): diff = abs(diff) diff = 10 - diff plain.append(diff) else: plain.append(diff) plain = ''.join(str(e) for e in plain) print(plain) bag_check = str(plain) ID = "" for i in range(4,11): ID += bag_check[i] print(RowID) print(ID) if (str(RowID) != str(ID)): print(x) messagebox.showwarning("Verification process","Security breach.\nThe bag does not belong to this user !!") else: x = x - 1 if (x == 0): messagebox.showinfo("Successful verification","Have a nice day !!\nThank you for the co operation.") return None end_bag_decode = time.time() bag_decode_time = end_bad_decode - start_bag_decode end_session = time.time() f = open("start_session.txt","r") start_session = float(f.read()) f.close() session_time = end_session - start_session #Accessing Excel loadingExcel = openpyxl.load_workbook('PassengerDataStore.xlsx') #Accessing Sheet in that Excel airlinesSheet=loadingExcel.get_sheet_by_name('Form Responses 1') format_end_time = time.gmtime(end_session) format_end_time = time.asctime(format_end_time) airlinesSheet.cell(row=access, column=19).value = format_end_time airlinesSheet.cell(row=access, column=20).value = session_time loadingExcel.save('PassengerDataStore.xlsx')
def restore(self, _): try: self.rm.restore_pop() except NotRestorableError as e: messagebox.showwarning("警告", "無法還原至上一步!", parent=self.view)
def opozorilo1(sez): if len(sez) > 2 or self.kaj.get() == 0: messagebox.showwarning('Opozorilo', 'Preveč izbranih možnosti') return False return True
def callback_web(ch, method, properties, body): data = body.decode("utf-8") web = json.loads(data) if web['bool'] == "false": tm.showwarning("Website", "Wrong domain opened:- " + web['domain'])
def measure_loop(): global scan_field_output, measured_values, sens_lbl measured_values = [] pos_values = [] neg_values = [] sens_lbl = [0] # create the lists of field values, scan loop is modified to include full loop if control_dict['Field Step'].get() == 'Step': # builds list from step and max value scan_field_output = make_list(mag_dict['Hx Field (Oe)'].get(), mag_dict['Hx Step (Oe)'].get()) # take inverse list and add it on, creating the full list values to measure at inverse = reversed(scan_field_output[0:-1]) scan_field_output += inverse else: # takes string and converts to list scan_field_output = convert_to_list(mag_dict['Hx Field (Oe)'].get()) # take inverse list and add it on, creating the full list values to measure at inverse = reversed(scan_field_output[0:-1]) scan_field_output += inverse # create the list of current values if control_dict['I_app Step'].get() == 'Step': # sensing current list sense_output = make_list(keith_dict['Sensing Current (mA)'].get(), keith_dict['Sensing Current Step (mA)'].get()) else: # sensing current list sense_output = convert_to_list(keith_dict['Sensing Current (mA)'].get()) # ensures output voltages will not exceed amp thresholds if max(scan_field_output) / float(control_dict['Hx/DAC (Oe/V)']) < float(control_dict['Hx DAC Limit']): # initialize machines amp = lockinAmp(lockin_dict['Mode'], lockin_dict['Sensitivity'], lockin_dict['Signal Voltage'], lockin_dict['Frequency']) keith_2400=Keithley2400('f') #Initiate K2400 keith_2000=Keithley('f') #Initiate K2000 # fixed sensing current value for sense_val in sense_output: sens_lbl[0] = round(sense_val, 3) # setup K2400 here keith_2400.fourWireOff() keith_2400.setCurrent(round(sense_val,4)) keith_2400.outputOn() # take initial resistance measurement? index=1 data=[] while index<=5: #Average of five measurements data=data+keith_2400.measureOnce() index+=1 resistance = round(data[1]/data[2], 4) display.insert('end',"Measured current: %f mA" %(1000*data[2])) display.insert('end',"Measured voltage: %f V" %data[1]) display.insert('end',"Measured resistance: %f Ohm" %(resistance)) display.see(END) # intializes the measurement data list measured_values = [] display.insert('end', 'Measurement using %s (mA) sensing current' % str(sense_val)) display.see(END) # measurement loops - measure pos and neg current at give scan value and take avg abs val (ohms) for counter, scan_val in enumerate(scan_field_output): if counter == 0: diff = abs(scan_val) else: diff = abs(scan_val - scan_field_output[counter-1]) # function to be built to model the time necessary for the magnets to get to value amp.dacOutput((scan_val / float(control_dict['Hx/DAC (Oe/V)'])), control_dict['Hx DAC Channel']) time.sleep(charging(diff)) keith_2400.outputOn() keith_2400.setCurrent(round(sense_val,4)) time.sleep(float(keith_dict['Delay (s)'].get())) # delay before measuring pos_data = keith_2000.measureMulti(int(keith_dict['Averages'].get())) keith_2400.setCurrent(round(-sense_val,4)) time.sleep(float(keith_dict['Delay (s)'].get())) # delay before measuring neg_data = keith_2000.measureMulti(int(keith_dict['Averages'].get())) tmp = round(float((abs(pos_data) - abs(neg_data))*1000/sense_val), 4) # voltage from K2000 / sense current pos_values.append(abs(pos_data)*1000/sense_val) neg_values.append(abs(neg_data)*1000/sense_val) measured_values.append(tmp) display.insert('end', 'Applied Hx Field Value: %s (Oe) Measured Avg Resistance: %s (Ohm)' %(scan_val, tmp)) display.see(END) # save data save_method(sense_val, scan_field_output, measured_values, display, control_dict['Directory'], control_dict['File Name'].get(), resistance, pos_values, neg_values) # turn everything off at end of loop amp.dacOutput(0, control_dict['Hx DAC Channel']) keith_2400.minimize() display.insert('end',"Measurement finished") display.see(END) else: messagebox.showwarning('Output Too Large', 'Output value beyond amp voltage threshold') display.insert('end', 'Output value too large!') display.see(END)
def clicked(r, c, m): w = 0 Button(root, text="X", padx=40, pady=40, bg='#fdff79', state=DISABLED).grid(row=r, column=c) if (len(user_cord) != 5): rr = random.randint(0, 2) rc = random.randint(0, 2) rm = 3 * rr + rc + 1 #formula to conver m into rows and columns if (rm != m and (str(rm) not in comp_cord) and (str(rm) not in user_cord)): comp_cord.append(str(rm)) user_cord.append(str(m)) print("USER Input: ") print(user_cord) print("COMPUTER Input: ") print(comp_cord) Button(root, text="O", padx=40, pady=40, bg='#99faff', state=DISABLED).grid(row=rr, column=rc) #for player if ('1' in user_cord and '2' in user_cord and '3' in user_cord): messagebox.showwarning("X Won!", "Player Won!") w = 1 disable() elif ('4' in user_cord and '5' in user_cord and '6' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() w = 1 elif ('7' in user_cord and '8' in user_cord and '9' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() w = 1 elif ('1' in user_cord and '4' in user_cord and '7' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() w = 1 elif ('2' in user_cord and '5' in user_cord and '8' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() w = 1 elif ('3' in user_cord and '6' in user_cord and '9' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() w = 1 elif ('1' in user_cord and '5' in user_cord and '9' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() w = 1 elif ('3' in user_cord and '5' in user_cord and '7' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() w = 1 #for computer if (w != 1): if ('1' in comp_cord and '2' in comp_cord and '3' in comp_cord): messagebox.showwarning("O Won!", "Computer Won!") disable() elif ('4' in comp_cord and '5' in comp_cord and '6' in comp_cord): messagebox.showwarning("O Won!", "Computer Won!") disable() elif ('7' in comp_cord and '8' in comp_cord and '9' in comp_cord): messagebox.showwarning("O Won!", "Computer Won!") disable() elif ('1' in comp_cord and '4' in comp_cord and '7' in comp_cord): messagebox.showwarning("O Won!", "Computer Won!") disable() elif ('2' in comp_cord and '5' in comp_cord and '8' in comp_cord): messagebox.showwarning("O Won!", "Computer Won!") disable() elif ('3' in comp_cord and '6' in comp_cord and '9' in comp_cord): messagebox.showwarning("O Won!", "Computer Won!") disable() elif ('1' in comp_cord and '5' in comp_cord and '9' in comp_cord): messagebox.showwarning("O Won!", "Computer Won!") disable() elif ('3' in comp_cord and '5' in comp_cord and '7' in comp_cord): messagebox.showwarning("O Won!", "Computer Won!") disable() elif (len(user_cord) > 3): user_cord.append(str(m)) print(user_cord) print(comp_cord) #for player if ('1' in user_cord and '2' in user_cord and '3' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() elif ('4' in user_cord and '5' in user_cord and '6' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() elif ('7' in user_cord and '8' in user_cord and '9' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() elif ('1' in user_cord and '4' in user_cord and '7' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() elif ('2' in user_cord and '5' in user_cord and '8' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() elif ('3' in user_cord and '6' in user_cord and '9' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() elif ('1' in user_cord and '5' in user_cord and '9' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() elif ('3' in user_cord and '5' in user_cord and '7' in user_cord): messagebox.showwarning("X Won!", "Player Won!") disable() else: clicked(r, c, m)
def process(): global filename, df, normal_mzs, indicator_process if filename == '': messagebox.showwarning( "No File", "Sorry, no file loaded! Please choose Excel file first.") else: #Ignoring Warnings warnings.filterwarnings("ignore") indicator_process = 0 #Default Peaks peak01 = int(text_peak01.get('1.0', tk.END)) peak02 = int(text_peak02.get('1.0', tk.END)) peak03 = int(text_peak03.get('1.0', tk.END)) peak04 = int(text_peak04.get('1.0', tk.END)) peaks = [peak01, peak02, peak03, peak04] normal_mzs = [] for peak in peaks: if peak != 0: normal_mzs.append(peak) normal_rows = len(normal_mzs) #Import File book = xlrd.open_workbook(filename) #print('Source file: '+sys.path[0]+filename+' loaded!') #Extraction nsheets = book.nsheets sheet_names = book.sheet_names() sheets = {} for sheet_name in sheet_names: nrows = book.sheet_by_name(sheet_name).nrows current_header = book.sheet_by_name(sheet_name).row_values(2) current_data = [ book.sheet_by_name(sheet_name).row_values(i) for i in range(3, nrows) ] sheets[sheet_name] = pd.DataFrame( current_data, columns=current_header) #DataFrame Construction #Feedback #print('Data Extracted!') #Dealing with the Missing Peak(s) #///////////////////Main Loop/////////// peak_missing_amount = 0 peak_redundant_amount = 0 peak_redundant_item = [] peak_missing_item = [] peak_repeated_amount = 0 peak_repeated_item = [] gain = 1000 / len(sheet_names) for sheet_name in sheet_names: df = sheets[sheet_name] actual_rows = len(df.index) mzs = list(df['m/z']) #////////////////////Unique!!!!/////////////////////////////////////////////// for mz in mzs: if len(df[df['m/z'] == mz].index) > 1: del_index = list(df[df['m/z'] == mz].index) del_index.pop(0) df = df.drop(del_index) mzs = list(df['m/z']) peak_repeated_amount += 1 peak_repeated_item.append( sheet_name.replace('_0_', ' @ ').replace('_1', '')) #//////////////////////////////////////////////////////////////////////////// df = df.sort_index(by='m/z') df = df.reset_index().drop('index', axis=1) actual_rows = len(df.index) #///////Larger than normal: Redundant/////////// if actual_rows > normal_rows: mzs = list(df['m/z']) mzs_adjacents = detect_redundant(mzs) #Call Function df = pd.concat([ df.ix[df[df['m/z'] == mzs_adjacent].index] for mzs_adjacent in mzs_adjacents ]) #////Memorize the Redundant One////////////////// peak_redundant_amount += 1 peak_redundant_item.append( sheet_name.replace('_0_', ' @ ').replace('_1', '')) #/////Sort & Reindex//////////// df = df.sort_index(by='m/z') df = df.reset_index().drop('index', axis=1) actual_rows = len(df.index) ##///////Less than normal: Missing/////// if actual_rows < normal_rows: mzs = list(df['m/z']) mzs_missing = detect_missed(mzs) #Call Function i = actual_rows for mz_missing in mzs_missing: df.ix[i] = 0 df['m/z'].ix[i] = mz_missing i += 1 #////Memorize the Missing One/////// peak_missing_amount += 1 peak_missing_item.append( sheet_name.replace('_0_', ' @ ').replace('_1', '')) df = df.sort_index(by='m/z') df = df.reset_index().drop('index', axis=1) actual_rows = len(df.index) #///////Again! Larger than normal: Redundant//////// if actual_rows > normal_rows: mzs = list(df['m/z']) mzs_adjacents = detect_redundant(mzs) #Call Function df = pd.concat([ df.ix[df[df['m/z'] == mzs_adjacent].index] for mzs_adjacent in mzs_adjacents ]) #/Memorize the Redundant One peak_redundant_amount += 1 peak_redundant_item.append( sheet_name.replace('_0_', ' @ ').replace('_1', '')) #Sort & Reindex///////////// df = df.sort_index(by='m/z') df = df.reset_index().drop('index', axis=1) sheets[sheet_name] = df indicator_process += gain df = pd.concat([sheets[sheet_name] for sheet_name in sheet_names], keys=sheet_names) #///Change the sheetnames from indeces into column names df = df.reset_index() #Sorting df = df.sort_index(by=['level_0', 'level_1']) df = df.set_index(['level_0', 'level_1']) df = df.unstack()
def show_warningmessage(operation, description, questions='ok'): tk_init() messagebox.showwarning(operation, description, type=questions) return
def avisoDocumentacion(): messagebox.showwarning("Documentación", "Toda la Documentación está disponible")
def detalle(self): try: self.tree2.item(self.tree2.selection())['values'][0] except IndexError as e: mb.showwarning('Atencion', 'SELECCIONE REGISTRO') return #obtencion de los datos en la fila seleccionada dato_fila = self.tree2.item(self.tree2.selection())['values'] #verficando si el nombre existe en la base de datos name = self.logica.verificar_existencia((dato_fila[0], )) if name == None: mb.showerror('ERROR', 'ACTUALICE REGISTROS') else: self.id_inquilino = '' self.id_inquilino = self.logica.id_inquilino(name) pagos_inquilino = self.logica.obtener_pagos(self.id_inquilino) #la longitud de la lista indica si hay cobros realizados if len(pagos_inquilino) == 0: mb.showinfo('Informacion', 'El inquilino aun no realiza pagos') else: #insercion de una nueva ventana para mostrar textos self.dialogo2 = tk.Toplevel(self.pagina3) self.dialogo2.title('Detalle de pagos') self.dialogo2.resizable(False, False) self.dialogo2.protocol("WM_DELETE_WINDOW") self.dialogo2.grab_set() #implementacion de labels y scroll ttk.Label(self.dialogo2, text='Nombre: ').grid(column=0, row=0, padx=4, pady=4) nombre_inquilino = tk.StringVar() nombre_inquilino.set(dato_fila[0]) tk.Entry(self.dialogo2, textvariable=nombre_inquilino, state='readonly').grid(column=1, row=0, padx=4, pady=4) ttk.Label(self.dialogo2, text='Cedula: ').grid(column=0, row=1, padx=4, pady=4) cedula_inquilino = tk.StringVar() cedula_inquilino.set(dato_fila[1]) tk.Entry(self.dialogo2, textvariable=cedula_inquilino, state='readonly').grid(column=1, row=1, padx=4, pady=4) ttk.Label(self.dialogo2, text='Celular: ').grid(column=0, row=2, padx=4, pady=4) celular_inquilino = tk.StringVar() celular_inquilino.set(dato_fila[2]) tk.Entry(self.dialogo2, textvariable=celular_inquilino, state='readonly').grid(column=1, row=2, padx=4, pady=4) #boton para mostrar el detalle en el scroll text ttk.Button(self.dialogo2, text='Mostrar Detalle', command=self.llenar_scroll).grid(column=0, row=3, columnspan=2, sticky='we', padx=4, pady=10) self.scrolledtext1 = st.ScrolledText(self.dialogo2, width=30, height=10) self.scrolledtext1.grid(column=0, row=4, padx=10, pady=10, columnspan=2, sticky='we')
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)
def showwarning(window, title='Warning', message='Please check your input'): if messagebox.showwarning(title, message): window.deiconify()
def SubmitType(): global Ret_math_range global Ret_math_type global Ret_opera_num global Ret_math_num ## 得到数学题的运算范围 if en0.get() != "": try: Ret_math_range = int(en0.get()) except: txt = "计算大小: 自定义\"" + en0.get() + "\"不是有效的数字!" #tk.Message(master, text=txt).pack() tm.showwarning("注意", txt) return 0 else: if num_range.get() == 0: txt = "请设置计算大小" tm.showwarning("注意", txt) return 0 Ret_math_range = num_range.get() #print(Ret_math_range) ## 得到数学提的运算类型 Ret_math_type = strs.get() if Ret_math_type == 0: txt = "请设置运算类型" tm.showwarning("注意:", txt) return 0 #print(Ret_math_type) ## 一道题有几个数参与运算 Ret_opera_num = yun_num.get() if Ret_opera_num == 0: txt = "请设置多项运算" tm.showwarning("注意:", txt) return 0 #print(Ret_opera_num) ## 得到需要计算的题目的数量 if en1.get() != "": try: Ret_math_num = int(en1.get()) except: txt = "题目数量: 自定义\"" + en1.get() + "\"不是有效的数字!" #tk.Message(master, text=txt).pack() tm.showwarning("注意", txt) return 0 else: Ret_math_num = math_num.get() if math_num.get() == 0: txt = "请设置题目数量" tm.showwarning("注意", txt) return 0 master.destroy()
def Auto_Post(): root = Tk() #root.title("Upload post on Linkedin") root.geometry("0x0") root.iconbitmap("Auto_Post_icon.ico") Result = None #print(Result) Key_Pressed = True pyautogui.rightClick(138, 744) while (Key_Pressed): if keyboard.is_pressed('ctrl'): print("Exit1") Key_Pressed = False break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\2.png"))): x,y = pyautogui.locateCenterOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\2.png") pyautogui.click(x,y) print(x,y) print("Enter1") break else: print("Not_Enter1") if((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\2_1.png"))): x,y = pyautogui.locateCenterOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\2_1.png") pyautogui.click(x,y) print(x,y) print("Enter1_1") break else: print("Not_Enter1") while (Key_Pressed): if keyboard.is_pressed('ctrl'): print("Exit2") Key_Pressed = False break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\3.png"))): x,y,w,h = pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\3.png") pyautogui.click(x+4,y+4) print("Enter2") break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\3_4.png"))): x,y = pyautogui.locateCenterOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\3_4.png") pyautogui.click(x,y) print("Enter2_4") break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\3_5.png"))): x,y,w,h = pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\3_5.png") pyautogui.click(x,y) print("Enter2_5") break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\3_1.png"))): print("Enter2_1") break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\3_2.png"))): print("Enter2_2") break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\3_3.png"))): print("Enter2_3") break else: print("Not_Enter2") while (Key_Pressed): if keyboard.is_pressed('ctrl'): print("Exit3") Key_Pressed = False break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\4_1.png"))): x,y = pyautogui.locateCenterOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\4_1.png") pyautogui.click(x+100,y);pyautogui.typewrite("https://www.linkedin.com/feed/",interval = 0.1) pyautogui.press("enter") print("Enter3") break else: print("Not_Enter3") while (Key_Pressed): if keyboard.is_pressed('ctrl'): print("Exit4") Key_Pressed = False break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\5.png"))): x,y = pyautogui.locateCenterOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\5.png") pyautogui.click(x,y) print("Enter4") break else: print("Not_Enter4") while (Key_Pressed): if keyboard.is_pressed('ctrl'): print("Exit5") Key_Pressed = False break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\6.png"))): x,y = pyautogui.locateCenterOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\6.png") pyautogui.click(x,y);pyautogui.typewrite("""Comment your answer below \n#C #codingisfun #coders #coderlife #programminglife #cdac #programming #codingchallenge #hackerrank """,interval = 0.1) print("Enter5") break else: print("Not_Enter5") while (Key_Pressed): if keyboard.is_pressed('ctrl'): print("Exit6") Key_Pressed = False break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\7.png"))): x,y,w,h = pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\7.png") pyautogui.click(x,y) date = [] dt = datetime.datetime.today() date.append(dt.day) date.append(dt.month) date.append(dt.year) date = str(date[0])+"-"+str(date[1])+"-"+str(date[2]) print("Enter6") break else: print("Not_Enter6") if ((Key_Pressed == True) and (os.path.exists("C:\\Users\\ankitaPC\\Desktop\\Post\\"+ str(date) + ".png"))): time.sleep(2) #pyautogui.typewrite([r"C:\Users\ankitaPC\Desktop\Post\\","backsapce" , str(date)],interval = 0.1) #pyautogui.typewrite( str(date),interval = 0.1) while (Key_Pressed): if keyboard.is_pressed('ctrl'): print("Exit7") Key_Pressed = False break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\8.png"))): x,y = pyautogui.locateCenterOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\8.png") print(x,y) pyautogui.click(x+100,y+3);pyautogui.typewrite( r"C:\Users\ankitaPC\Desktop\Post",interval = 0.1) pyautogui.typewrite("\\",interval = 0.1) #pyautogui.press('backspace') pyautogui.typewrite( str(date),interval = 0.1) print("Enter7") break else: print("Not_Enter7") while (Key_Pressed): if keyboard.is_pressed('ctrl'): print("Exit8") Key_Pressed = False break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\9.png"))): x,y = pyautogui.locateCenterOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\9.png") pyautogui.click(x,y) print("Enter8") break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\9_1.png"))): x,y = pyautogui.locateCenterOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\9_1.png") pyautogui.click(x,y) print("Enter8_1") break else: print("Not_Enter8") while (Key_Pressed): if keyboard.is_pressed('ctrl'): print("Exit9") Key_Pressed = False break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\10.png"))): x,y = pyautogui.locateCenterOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\10.png") pyautogui.click(x,y) print("Enter9") break else: print("Not_Enter9") while (Key_Pressed): if keyboard.is_pressed('ctrl'): print("Exit10") Key_Pressed = False break elif((Result is not pyautogui.locateOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\11.png"))): x,y = pyautogui.locateCenterOnScreen(r"C:\Users\ankitaPC\Desktop\Post\Auto_post\11.png") pyautogui.click(x,y) print("Enter10") break else: print("Not_Enter10") elif(Key_Pressed == False): print("Exit7777") messagebox.showwarning("Linkedin Post","Canceled") else: print("File Not Found") #time.sleep(1) pyautogui.hotkey('win',"d") messagebox.showerror("Error",str(date) + ".png" + "\nFile Not Found") os.system("taskkill /f /im Auto_post_1.exe") root.mainloop()
def avisoLicencia(): messagebox.showwarning("Licencia", "Producto bajo licencia GNU")
tix.Button( f2, text="error", bg="lightblue", command=lambda t="error", m="This is bad!": mb.showerror(t, m)).pack( fill='x', expand=True) tix.Button(f2, text="info", bg='pink', command=lambda t="info", m="Information": mb.showinfo(t, m)).pack( fill='x', expand=True) tix.Button( f2, text="warning", bg='yellow', command=lambda t="warning", m="Don't do it!": mb.showwarning(t, m)).pack( fill='x', expand=True) tix.Button( f2, text="question", bg='green', command=lambda t="question", m="Will I?": mb.askquestion(t, m)).pack( fill='x', expand=True) tix.Button( f2, text="yes-no", bg='lightgrey', command=lambda t="yes-no", m="Are you sure?": mb.askyesno(t, m)).pack( fill='x', expand=True) tix.Button(f2, text="yes-no-cancel",
def avisoLicencia(): messagebox.showwarning("Tacaño", "No compraste la licencia, la pirateaste")
def calculate_result(self): # Objem a obsah kvádra if self.current == "Objem a obsah kvadra": if self.entry_one != "" or self.entry_two != "" or self.entry_three != "": try: a = float(self.entry_one.get()) b = float(self.entry_two.get()) c = float(self.entry_three.get()) V = round((a * b * c), 2) S = round((2 * (a * b + b * c + a * c)), 2) messagebox.showinfo( "Výsledok", f"Kváder pri rozmeroch: a={a}cm; b={b}cm; c={c}cm\n-->V = {V}cm kubických\n-->S = {S}cm štvorcových" ) except ValueError: messagebox.showwarning( "Chyba", "Zadané hodnoty nie su akceptovateľné.\nProsím, skontrolujte vaše zadané hodnoty." ) else: messagebox.showwarning( "Chyba", "Skontrolujte, či sú všetky polia zaplnené.") # Obvod a obsah kruhu elif self.current == "Obvod a obsah kruhu": if self.entry_one != "": try: r = float(self.entry_one.get()) S = round(3.14 * (r * r), 2) o = round(3.14 * (2 * r), 2) messagebox.showinfo( "Výsledok", f"Kruh pri polomere {r}cm\n-->S = {S}cm štvorcových\n-->o = {o}cm" ) except ValueError: messagebox.showwarning( "Chyba", "Zadané hodnoty nie su akceptovateľné.\nProsím, skontrolujte vaše zadané hodnoty." ) else: messagebox.showwarning( "Chyba", "Skontrolujte, či sú všetky polia zaplnené.") # Pytagorova veta elif self.current == "Pytagorova veta": try: a = float(self.entry_one.get()) b = float(self.entry_two.get()) c = ((a**2 + b**2)**(1 / 2)) messagebox.showinfo( "Výsledok", f"Pri odvesnách a={a}cm a b={b}cm\n-->c = {c}cm") except ValueError: messagebox.showwarning( "Chyba", "Zadané hodnoty nie su akceptovateľné.\nProsím, skontrolujte vaše zadané hodnoty." ) # Kvadraticka rovnica elif self.current == "Kvadraticka rovnica": try: a = int(self.entry_one.get()) b = int(self.entry_two.get()) c = int(self.entry_three.get()) D = ((b**2) - 4 * a * c) if D == 0: x = (-b / (2 * a)) messagebox.showinfo( "Výsledok", f"Pre hodnoty: a={a}; b={b}; c={c}\n-->x = {x}") elif D < 0: messagebox.showinfo( "Výsledok", f"Pre hodnoty: a={a}; b={b}; c={c}\n-->Rovnica nemá riešenie" ) elif D > 0: x1 = (-b + (isqrt(D)) / 2 * a) x2 = (-b - (isqrt(D)) / 2 * a) messagebox.showinfo( "Výsledok", f"Pre hodnoty: a={a}; b={b}; c={c}\n-->x1 = {x1}\n-->x2 = {x2}" ) except ValueError: messagebox.showwarning( "Chyba", "Zadané hodnoty nie su akceptovateľné.\nProsím, skontrolujte vaše zadané hodnoty." )
def crearMatriz(self): label = [] for i in range(4 + len(self.result)): label.append([]) for j in range(len(self.matriz[0])): if self.matriz[i][j] == "": label[i].append( Label(self.inicio, width="6", height="2", bg="#7f8c8d", font=("Comic Sans MS", 14), borderwidth=2, relief="solid")) label[i][j].grid(row=i + 1, column=j + 1) else: label[i].append( Label(self.inicio, text=self.matriz[i][j], fg="#d63031", width="6", height="2", bg="#95a5a6", font=("Comic Sans MS", 14), borderwidth=2, relief="solid")) label[i][j].grid(row=i + 1, column=j + 1) pivote = CEspeciales(self.matriz, self.funcion) pivote.pivoteE() pivote.pivoteS() self.pivote = pivote.pivotefc if (pivote.nacotada): self.boton.config(state='disabled') if pivote.degenerado: self.bandera = True if pivote.solucion: self.bandera = False self.boton.config(state='disabled') a = str(self.matriz[len(self.matriz) - 2][2]) mult = False if (a.find("M") == -1): Label(self.inicio, text="Solucion = " + str(self.matriz[len(self.matriz) - 2][2]), font=("Comic Sans MS", 19), bg="#34495e", fg="#fff200").grid(columnspan=3, row=0, column=1) else: messagebox.showwarning( "Advertencia", "Problema no acotado hay variables artificiales en la solucion" ) for i in range(len(self.variables)): for j in range(2, len(self.matriz) - 2): if self.matriz[j][1].count("X" + str(i + 1)) > 0: mult = True if mult == False: break if (mult == False): messagebox.showwarning("Advertencia", "Es una solucion optima multiple") if (pivote.abierto): self.boton.config(state='disabled') else: for i in range(len(self.matriz[0])): label[pivote.pivotefc[1]][i].config(bg="#1abc9c") for i in range(len(self.matriz)): label[i][pivote.pivotefc[0]].config(bg="#1abc9c") label[pivote.pivotefc[1]][pivote.pivotefc[0]].config(bg="#8e44ad") if self.bandera: degenerado = [] for i in range(len(self.matriz)): degenerado.append(str(self.matriz[i][2])) if (degenerado == self.degenerado): self.count += 1 if (self.count == 3): self.boton.config(state='disabled') messagebox.showwarning("Advertencia", "Es un problema con ciclajes") Label(self.inicio, text="Solucion = " + str(self.matriz[len(self.matriz) - 2][2]), font=("Comic Sans MS", 19), bg="#34495e").grid(columnspan=3, row=0, column=1) self.degenerado = degenerado
command=lambda: os.startfile("C:" + dirVar)) open_folder.place(relx=0.5, rely=0.75, anchor=N) about = Button(window, text="About", width=10, height=2, bd=2, font=helv12, bg="#959DA5", command=create_about) about.place(relx=0.8, rely=0.75, anchor=N) dirVar = "/Users/" + str(os.getlogin()) + "/Desktop/GUHProject/" sortedDir = "" selectedfile = "" globalflag = True create_button() try: os.mkdir(dirVar) messagebox.showwarning( "Folder Created", "Folder GUHProject has been created on the Desktop.\nPlease copy photos into the folder before scan." ) except: pass status_bar("Ready.", "#00FF00") window.mainloop()
def warn(): msgbox.showwarning("경고", "해당 좌석은 매진되었습니다.")
def submit(): global sheet src = src_dir.get() dst = dst_dir.get() src_dir.set("") dst_dir.set("") files = len([f for f in glob.glob(src + "**/*.jpg", recursive=True)]) name = askopenfilename(filetypes=[('Excel', ('*.xls', '*.xlsx'))]) book = xlrd.open_workbook(name) sheet = book.sheet_by_index(0) num_rows = sheet.nrows book.release_resources() with open('html.html', 'r') as f: html = f.read() for jpgfile in glob.iglob(os.path.join(src, "*.jpg")): filename = os.path.basename(jpgfile) file, ext = os.path.splitext(filename) if ext == '.jpg' and file.endswith('-AR'): src = os.path.join(src, jpgfile) img = cv2.imread(src) h, w, c = img.shape abc(num_rows) output_file = os.path.join(dst + '/ar') os.mkdir(dst + '/ar/') path = Path(output_file) shutil.copy(jpgfile, path) doc = os.path.join(output_file + '/' + file + '.html') find_list = ["<title></title>", "<tag1>", "<tag2>"] replace_list = ["<title>" + file + "</title>", '<a href="' + AR + '"' + ' target="_blank">', '<img src="' + file + '.jpg"' + ' width="' + str(w) + '" height="' + str(h) + '" alt=""></a>'] update_html(output_file, html, find_list, replace_list, file) elif ext == '.jpg' and file.endswith('-DE'): src = os.path.join(src, jpgfile) img = cv2.imread(src) h, w, c = img.shape abc(num_rows) output_file = os.path.join(dst + '/de') os.mkdir(dst + '/de/') path = Path(output_file) shutil.copy(jpgfile, path) doc = os.path.join(output_file + '/' + file + '.html') find_list = ["<title></title>", "<tag1>", "<tag2>"] replace_list = ["<title>" + file + "</title>", '<a href="' + DE + '"' + ' target="_blank">', '<img src="' + file + '.jpg"' + ' width="' + str(w) + '" height="' + str(h) + '" alt=""></a>'] update_html(output_file, html, find_list, replace_list, file) elif ext == '.jpg' and file.endswith('-EN'): src = os.path.join(src, jpgfile) img = cv2.imread(src) h, w, c = img.shape abc(num_rows) output_file = os.path.join(dst + '/en') os.mkdir(dst + '/en/') path = Path(output_file) shutil.copy(jpgfile, path) doc = os.path.join(output_file + '/' + file + '.html') find_list = ["<title></title>", "<tag1>", "<tag2>"] replace_list = ["<title>" + file + "</title>", '<a href="' + EN + '"' + ' target="_blank">', '<img src="' + file + '.jpg"' + ' width="' + str(w) + '" height="' + str(h) + '" alt=""></a>'] update_html(output_file, html, find_list, replace_list, file) elif ext == '.jpg' and file.endswith('-ES'): src = os.path.join(src, jpgfile) img = cv2.imread(src) h, w, c = img.shape abc(num_rows) output_file = os.path.join(dst + '/es') os.mkdir(dst + '/es/') path = Path(output_file) shutil.copy(jpgfile, path) doc = os.path.join(output_file + '/' + file + '.html') find_list = ["<title></title>", "<tag1>", "<tag2>"] replace_list = ["<title>" + file + "</title>", '<a href="' + ES + '"' + ' target="_blank">', '<img src="' + file + '.jpg"' + ' width="' + str(w) + '" height="' + str(h) + '" alt=""></a>'] update_html(output_file, html, find_list, replace_list, file) elif ext == '.jpg' and file.endswith('-FR'): src = os.path.join(src, jpgfile) img = cv2.imread(src) h, w, c = img.shape abc(num_rows) output_file = os.path.join(dst + '/fr') os.mkdir(dst + '/fr/') path = Path(output_file) shutil.copy(jpgfile, path) doc = os.path.join(output_file + '/' + file + '.html') find_list = ["<title></title>", "<tag1>", "<tag2>"] replace_list = ["<title>" + file + "</title>", '<a href="' + FR + '"' + ' target="_blank">', '<img src="' + file + '.jpg"' + ' width="' + str(w) + '" height="' + str(h) + '" alt=""></a>'] update_html(output_file, html, find_list, replace_list, file) elif ext == '.jpg' and file.endswith('-IT'): src = os.path.join(src, jpgfile) img = cv2.imread(src) h, w, c = img.shape abc(num_rows) output_file = os.path.join(dst + '/it') os.mkdir(dst + '/it/') path = Path(output_file) shutil.copy(jpgfile, path) doc = os.path.join(output_file + '/' + file + '.html') find_list = ["<title></title>", "<tag1>", "<tag2>"] replace_list = ["<title>" + file + "</title>", '<a href="' + IT + '"' + ' target="_blank">', '<img src="' + file + '.jpg"' + ' width="' + str(w) + '" height="' + str(h) + '" alt=""></a>'] update_html(output_file, html, find_list, replace_list, file) elif ext == '.jpg' and file.endswith('-NL'): src = os.path.join(src, jpgfile) img = cv2.imread(src) h, w, c = img.shape abc(num_rows) output_file = os.path.join(dst + '/nl') os.mkdir(dst + '/nl/') path = Path(output_file) shutil.copy(jpgfile, path) doc = os.path.join(output_file + '/' + file + '.html') find_list = ["<title></title>", "<tag1>", "<tag2>"] replace_list = ["<title>" + file + "</title>", '<a href="' + NL + '"' + ' target="_blank">', '<img src="' + file + '.jpg"' + ' width="' + str(w) + '" height="' + str(h) + '" alt=""></a>'] update_html(output_file, html, find_list, replace_list, file) elif ext == '.jpg' and file.endswith('-NO'): src = os.path.join(src, jpgfile) img = cv2.imread(src) h, w, c = img.shape abc(num_rows) output_file = os.path.join(dst + '/no') os.mkdir(dst + '/no/') path = Path(output_file) shutil.copy(jpgfile, path) doc = os.path.join(output_file + '/' + file + '.html') find_list = ["<title></title>", "<tag1>", "<tag2>"] replace_list = ["<title>" + file + "</title>", '<a href="' + NO + '"' + ' target="_blank">', '<img src="' + file + '.jpg"' + ' width="' + str(w) + '" height="' + str(h) + '" alt=""></a>'] update_html(output_file, html, find_list, replace_list, file) elif ext == '.jpg' and file.endswith('-Pl'): src = os.path.join(src, jpgfile) img = cv2.imread(src) h, w, c = img.shape abc(num_rows) output_file = os.path.join(dst + '/pl') os.mkdir(dst + '/pl/') path = Path(output_file) shutil.copy(jpgfile, path) doc = os.path.join(output_file + '/' + file + '.html') find_list = ["<title></title>", "<tag1>", "<tag2>"] replace_list = ["<title>" + file + "</title>", '<a href="' + PL + '"' + ' target="_blank">', '<img src="' + file + '.jpg"' + ' width="' + str(w) + '" height="' + str(h) + '" alt=""></a>'] update_html(output_file, html, find_list, replace_list, file) elif ext == '.jpg' and file.endswith('-PT'): src = os.path.join(src, jpgfile) img = cv2.imread(src) h, w, c = img.shape abc(num_rows) output_file = os.path.join(dst + '/pt') os.mkdir(dst + '/pt/') path = Path(output_file) shutil.copy(jpgfile, path) doc = os.path.join(output_file + '/' + file + '.html') find_list = ["<title></title>", "<tag1>", "<tag2>"] replace_list = ["<title>" + file + "</title>", '<a href="' + PT + '"' + ' target="_blank">', '<img src="' + file + '.jpg"' + ' width="' + str(w) + '" height="' + str(h) + '" alt=""></a>'] update_html(output_file, html, find_list, replace_list, file) elif ext == '.jpg' and file.endswith('-RU'): src = os.path.join(src, jpgfile) img = cv2.imread(src) h, w, c = img.shape abc(num_rows) output_file = os.path.join(dst + '/ru') os.mkdir(dst + '/ru/') path = Path(output_file) shutil.copy(jpgfile, path) doc = os.path.join(output_file + '/' + file + '.html') find_list = ["<title></title>", "<tag1>", "<tag2>"] replace_list = ["<title>" + file + "</title>", '<a href="' + RU + '"' + ' target="_blank">', '<img src="' + file + '.jpg"' + ' width="' + str(w) + '" height="' + str(h) + '" alt=""></a>'] update_html(output_file, html, find_list, replace_list, file) elif ext == '.jpg' and file.endswith('-SV'): src = os.path.join(src, jpgfile) img = cv2.imread(src) h, w, c = img.shape abc(num_rows) output_file = os.path.join(dst + '/se') os.mkdir(dst + '/se/') path = Path(output_file) shutil.copy(jpgfile, path) doc = os.path.join(output_file + '/' + file + '.html') find_list = ["<title></title>", "<tag1>", "<tag2>"] replace_list = ["<title>" + file + "</title>", '<a href="' + SE + '"' + ' target="_blank">', '<img src="' + file + '.jpg"' + ' width="' + str(w) + '" height="' + str(h) + '" alt=""></a>'] update_html(output_file, html, find_list, replace_list, file) elif ext == '.jpg' and file.endswith('-ZH'): src = os.path.join(src, jpgfile) img = cv2.imread(src) h, w, c = img.shape abc(num_rows) output_file = os.path.join(dst + '/cn') os.mkdir(dst + '/cn/') path = Path(output_file) shutil.copy(jpgfile, path) doc = os.path.join(output_file + '/' + file + '.html') find_list = ["<title></title>", "<tag1>", "<tag2>"] replace_list = ["<title>" + file + "</title>", '<a href="' + CN + '"' + ' target="_blank">', '<img src="' + file + '.jpg"' + ' width="' + str(w) + '" height="' + str(h) + '" alt=""></a>'] update_html(output_file, html, find_list, replace_list, file) else: continue # folder_counter = int(sum([len(folder) for _, _, folder in os.walk(dst)]) / 2) if files == num_rows: messagebox.showinfo("Successful", "All folders successfully created") else: messagebox.showwarning("Warning", "Folders Missing")
def selected_item(self): self.entry_one.delete(0, END) self.entry_two.delete(0, END) self.entry_three.delete(0, END) self.text_one.set(" ") self.text_two.set(" ") self.text_three.set(" ") try: selected = self.list_func.curselection() self.current = self.list_func.get(selected) print(self.current) if self.current == "Objem a obsah kvadra": self.selection_tag.set("Vybrane: V a S kvader") self.calculate["state"] = "normal" self.entry_one.configure(state="normal") self.entry_two.configure(state="normal") self.entry_three.configure(state="normal") self.text_one.set("a:") self.text_two.set("b:") self.text_three.set("c:") self.current = "Objem a obsah kvadra" elif self.current == "Obvod a obsah kruhu": self.selection_tag.set("Vybrane: S a o kruhu") self.calculate["state"] = "normal" self.entry_one["state"] = "normal" self.entry_two["state"] = "disabled" self.entry_three["state"] = "disabled" self.text_one.set("r:") self.current = "Obvod a obsah kruhu" elif self.current == "Kvadraticka rovnica": self.selection_tag.set("Vybrane: Kvadrar. r.") self.calculate["state"] = "normal" self.entry_one["state"] = "normal" self.entry_two["state"] = "normal" self.entry_three["state"] = "normal" self.text_one.set("a:") self.text_two.set("b:") self.text_three.set("c:") self.current = "Kvadraticka rovnica" elif self.current == "Pytagorova veta": self.selection_tag.set("Vybrane: Pytag. veta") self.calculate["state"] = "normal" self.entry_one["state"] = "normal" self.entry_two["state"] = "normal" self.entry_three["state"] = "disabled" self.text_one.set("a:") self.text_two.set("b:") self.current = "Pytagorova veta" except: messagebox.showwarning("Chyba", "Nebola vybraná žiadna možnosť.")