官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 阳江市| 宾阳县| 竹溪县| 右玉县| 郴州市| 马鞍山市| 郁南县| 和顺县| 高邑县| 东乡族自治县| 额尔古纳市| 句容市| 梨树县| 朝阳市| 阿坝| 玉溪市| 广元市| 尚志市| 博乐市| 平昌县| 中牟县| 眉山市| 左贡县| 崇仁县| 鄯善县| 栾城县| 边坝县| 环江| 南投市| 桃江县| 图木舒克市| 都匀市| 稷山县| 长汀县| 九江县| 乐陵市| 宁强县| 潍坊市| 宁陵县| 宁远县| 邵东县|