- Tkinter GUI Application Development Cookbook
- Alejandro Rodas de Paz
- 127字
- 2021-08-27 19:44:02
How to do it...
The following application shows how to validate an entry using regular expressions:
import re import tkinter as tk class App(tk.Tk): def __init__(self): super().__init__() self.pattern = re.compile("^\w{0,10}$") self.label = tk.Label(self, text="Enter your username") vcmd = (self.register(self.validate_username), "%i", "%P") self.entry = tk.Entry(self, validate="key", validatecommand=vcmd, invalidcommand=self.print_error) self.label.pack() self.entry.pack(anchor=tk.W, padx=10, pady=10) def validate_username(self, index, username): print("Modification at index " + index) return self.pattern.match(username) is not None def print_error(self): print("Invalid username character") if __name__ == "__main__": app = App() app.mainloop()
If you run this script and type a non-alphanumeric character in the Entry widget, it will keep the same content and print the error message. This will also happen when you try to type more than 10 valid characters since the regular expression also limits the content's length.
推薦閱讀
- The Complete Rust Programming Reference Guide
- C語(yǔ)言程序設(shè)計(jì)教程
- 計(jì)算思維與算法入門(mén)
- Linux C/C++服務(wù)器開(kāi)發(fā)實(shí)踐
- 垃圾回收的算法與實(shí)現(xiàn)
- ASP.NET Core 2 Fundamentals
- Spring Boot+Vue全棧開(kāi)發(fā)實(shí)戰(zhàn)
- Instant PHP Web Scraping
- Hands-On Full Stack Development with Spring Boot 2.0 and React
- JQuery風(fēng)暴:完美用戶體驗(yàn)
- Visual C++從入門(mén)到精通(第2版)
- Microsoft HoloLens By Example
- Git Version Control Cookbook
- ACE技術(shù)內(nèi)幕:深入解析ACE架構(gòu)設(shè)計(jì)與實(shí)現(xiàn)原理
- GitHub Essentials