验证 Tkinter 输入框 [英] Validating Tkinter Entry Box
问题描述
我正在尝试验证我的输入框,它只接受浮点数、数字和运算符(+×÷-,%).但是我的程序只接受数字而不接受符号.
I am trying to validate my entry box, that only accepts floats, digits, and operators (+×÷-, %). But my program only accepts numbers not symbols.
我认为是我的条件或 Python 正则表达式有问题.
I think it is a problem with my conditions or Python Regex.
代码如下:
from tkinter import *
import re
root = Tk()
def correct(inp):
pattern = re.compile(r'^(\d*\.?\d*)$')
if pattern.match(inp) is not None:
return True
elif inp is "":
return True
else:
return False
a = Entry(root)
e = root.register(correct)
a.config(validate='key', validatecommand=(e, '%P'))
a.pack()
root.mainloop()
推荐答案
您的正则表达式仅匹配浮点数:\d*.?\d* 匹配数字后跟可选的点和更多数字.如果你想匹配的是像[float][operator][float]这样的模式,那么你可以使用(只需在方括号中添加你想要的运算符):
Your regexp only matches floats: \d*.?\d* matches digits followed optionally by a dot and more digits. If what you want to match is a pattern like [float][operator][float], then you can use (just add the operators you want in the square brackets):
pattern = re.compile(r'^\d*\.?\d*[+*/\-%]?\d*\.?\d*$')
如果您不关心顺序而只想允许任何数字和运算符序列:
If you don't care about the order and just want to allow any sequence of numbers and operators:
pattern = re.compile(r'^[\d.+*/\-%]*$')
这篇关于验证 Tkinter 输入框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!