简体   繁体   English

验证 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.但是我的程序只接受数字而不是符号。

I think it is a problem with my conditions or Python Regex.我认为这是我的条件或 Python Regex 的问题。

Here's the code:这是代码:

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()

Your regexp only matches floats: \\d*.?\\d* matches digits followed optionally by a dot and more digits.您的正则表达式仅匹配浮点数: \\d*.?\\d* 匹配数字后跟可选的点和更多数字。 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):如果您要匹配的是像 [float][operator][float] 这样的模式,那么您可以使用(只需在方括号中添加您想要的运算符):

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.+*/\-%]*$')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM