我试图检查用户对我创建的Tk GUI的输入是否是我想要的正确数据类型(整数),但我只能检查他们的输入是否是布尔值,我需要检查他们的输入是字符串还是整数:
from tkinter import*
# creates a GUI
Tester = Tk()
NonEssentialFoodEntry = Entry(Tester, width="30")
NonEssentialFoodEntry.place(x=300,y=540)
def checker():
if NonEssentialFoodEntry.get() == 'TRUE' or 'FALSE':
tkinter.messagebox.showerror("","You have entered a boolean value in the Non-EssentialFood entry field, please enter an integer")
Checker=Button(Tester, height="7",width="30",font=300,command=checker)
Checker.place(x=700, y=580)
好吧,你可以在输入上运行一个正则表达式,并检查哪个组不是None
:
(?:^(?P<boolean>TRUE|FALSE)$)
|
(?:^(?P<integer>\d+)$)
|
(?:^(?P<float>\d+\.\d+)$)
|
(?:^(?P<string>.+)$)
见a demo on regex101.com。首先,每个输入都是一个字符串。
Python
:
import re
strings = ["TRUE", "FALSE", "123", "1.234343", "some-string", "some string with numbers and FALSE and 1.23 in it"]
rx = re.compile(r'''
(?:^(?P<boolean>TRUE|FALSE)$)
|
(?:^(?P<integer>-?\d+)$)
|
(?:^(?P<float>-?\d+\.\d+)$)
|
(?:^(?P<string>.+)$)
''', re.VERBOSE)
for string in strings:
m = rx.search(string)
instance = [k for k,v in m.groupdict().items() if v is not None]
print(instance)
if instance:
print("{} is probably a(n) {}".format(string, instance[0]))
正如上面的评论中所说的那样,你可能会跟try/except
采用另一种方式。
一种方法是尝试转换您的输入并查看它是否管理。
编辑:这基本上是@martineau在评论中提出的方法
以下代码改编自FlyingCircus(免责声明:我是主要作者):
def auto_convert(
text,
casts=(int, float, complex)):
"""
Convert value to numeric if possible, or strip delimiters from string.
Args:
text (str|int|float|complex): The text input string.
casts (Iterable[callable]): The cast conversion methods.
Returns:
val (int|float|complex): The numeric value of the string.
Examples:
>>> auto_convert('<100>', '<', '>')
100
>>> auto_convert('<100.0>', '<', '>')
100.0
>>> auto_convert('100.0+50j')
(100+50j)
>>> auto_convert('1e3')
1000.0
>>> auto_convert(1000)
1000
>>> auto_convert(1000.0)
1000.0
"""
if isinstance(text, str):
val = None
for cast in casts:
try:
val = cast(text)
except (TypeError, ValueError):
pass
else:
break
if val is None:
val = text
else:
val = text
return val
请注意,对于布尔情况,您需要一个专门的函数,因为bool(text)
一旦text
非空(在FlyingCircus的最新版本中也作为flyingcircus.util.to_bool()
出现),if isinstance(<var>, int):
将评估为True。
例如,您可以使用以下代码围绕有效整数构建if语句:type(<var>)
否则使用qazxswpoi获取类型并围绕它构建函数。