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.
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. 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.+*/\-%]*$')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.