本期给大家分享一套简易 Tkinter正则表达式工具 ,希望对你有所帮助,如有疑问或者需要改进的地方可以私信小编。 整体布局: 功能代码介绍: ?️? 1. 导入tkinter和re模块 from tkinte
?️? 1. 导入tkinter和re模块
from tkinter import * from tkinter import messagebox, ttk import re
# 窗口居屏幕中央 screenwidth = root.winfo_screenwidth() screenheight = root.winfo_screenheight() alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth-width)/2, (screenheight-height)/2) root.geometry(alignstr)
font_size = 10 label1 = Label(root, text="常用正则表达式:",font=(StringVar(), font_size),pady=10) label1.grid(row=1, column=0, sticky=W,padx=5, pady=5) # 功能按钮 button2 = Button(root, width=15, text="测试", command=check_regex) button3 = Button(root, width=15, text="清空所有", command=clear_all) button2.grid(row=5, column=1, padx=5, pady=5) button3.grid(row=5, column=2, padx=5, pady=5) label2 = Label(root, text="正则表达式:", font=(StringVar(), font_size), pady=10) label3 = Label(root, text="目标字符串:", font=(StringVar(), font_size), pady=10) label4 = Label(root, text="匹配结果:", font=(StringVar(), font_size), pady=10) label2.grid(row=2, column=0, sticky=W, padx=5) label3.grid(row=3, column=0, sticky=W, padx=5) label4.grid(row=4, column=0, sticky=W, padx=5) # 设置默认项 text1 = Text(root, width=47, height=5, font=(StringVar(), font_size)) text1.insert('1.0', dic_tmp[comboxlist.get()]) text2 = Text(root, width=47, height=10, font=(StringVar(), font_size)) text3 = Text(root, width=47, height=10, font=(StringVar(), font_size)) text1.grid(row=2, column=1,columnspan=3, pady=10) text2.grid(row=3, column=1,columnspan=3, pady=10) text3.grid(row=4, column=1,columnspan=3, pady=10)
# 下拉选择框 def set_combox(): comboxlist["values"] = list(dic_tmp.keys()) comboxlist.current(0) comboxlist.bind("<<ComboboxSelected>>", get_combox) comboxlist.grid(row=1, column=1, pady=10)
?️? 5. 清空文本框
# 清空三个文本框 def clear_all(): text1.delete('1.0', 'end') text2.delete('1.0', 'end') text3.delete('1.0', 'end')
?️? 6. 正则匹配结果
# 正则匹配 def check_regex(): text3.delete('1.0', 'end') re_text = text1.get('1.0', '1.end') source_text = text2.get('1.0', END) try: pattern = re.compile(f'{re_text}') result = re.findall(pattern, source_text) if result: # 循环输出 for res in result: if res != '': text3.insert(END, res+'\n') else: text3.delete('1.0', 'end') text3.insert('insert', '匹配结果为空') except: text3.delete('1.0', 'end') text3.insert('insert', '匹配失败')
?️? 7. 设置滚动条
# 创建滚动条 scroll2 = Scrollbar(orient=VERTICAL,command=text2.yview) text2.config(yscrollcommand = scroll2.set) scroll2.grid(row=3,column=4, pady=10, sticky=S+W+E+N) # 创建滚动条 scroll3 = Scrollbar(orient=VERTICAL,command=text3.yview) text3.config(yscrollcommand = scroll3.set) scroll3.grid(row=4,column=4, pady=10, sticky=S+W+E+N)
?️? 8. 几个示例
数字:
字母:
中文:
大写字母:
以上正则字典大家可以根据自己的需求进行修改。