猿问

如何检查python/tk中条目小部件的内容是浮点数、字符串、布尔值还是整数?

我正在尝试检查用户对我创建的 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)


长风秋雁
浏览 183回答 3
3回答

开心每一天1111

一种方法是尝试转换您的输入并查看它是否可以管理。编辑:这基本上是@martineau 在评论中建议的方法以下代码改编自FlyingCircus(免责声明:我是主要作者):def auto_convert(&nbsp; &nbsp; text,&nbsp; &nbsp; casts=(int, float, complex)):"""Convert value to numeric if possible, or strip delimiters from string.Args:&nbsp; &nbsp; text (str|int|float|complex): The text input string.&nbsp; &nbsp; casts (Iterable[callable]): The cast conversion methods.Returns:&nbsp; &nbsp; val (int|float|complex): The numeric value of the string.Examples:&nbsp; &nbsp; >>> auto_convert('<100>', '<', '>')&nbsp; &nbsp; 100&nbsp; &nbsp; >>> auto_convert('<100.0>', '<', '>')&nbsp; &nbsp; 100.0&nbsp; &nbsp; >>> auto_convert('100.0+50j')&nbsp; &nbsp; (100+50j)&nbsp; &nbsp; >>> auto_convert('1e3')&nbsp; &nbsp; 1000.0&nbsp; &nbsp; >>> auto_convert(1000)&nbsp; &nbsp; 1000&nbsp; &nbsp; >>> auto_convert(1000.0)&nbsp; &nbsp; 1000.0"""if isinstance(text, str):&nbsp; &nbsp; val = None&nbsp; &nbsp; for cast in casts:&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; val = cast(text)&nbsp; &nbsp; &nbsp; &nbsp; except (TypeError, ValueError):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pass&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; if val is None:&nbsp; &nbsp; &nbsp; &nbsp; val = textelse:&nbsp; &nbsp; val = textreturn val请注意,对于布尔情况,您需要一个专门的函数,因为bool(text)一旦text非空就会评估为 True (这也出现在最新版本的FlyingCircus as 中flyingcircus.util.to_bool())。

沧海一幻觉

好吧,您可以对输入运行正则表达式并检查哪个组不是None:(?:^(?P<boolean>TRUE|FALSE)$)|(?:^(?P<integer>\d+)$)|(?:^(?P<float>\d+\.\d+)$)|(?:^(?P<string>.+)$)在 regex101.com 上查看演示。首先,每个输入都是一个字符串。在Python:import restrings = ["TRUE", "FALSE", "123", "1.234343", "some-string", "some string with numbers and FALSE and 1.23 in it"]rx = re.compile(r'''&nbsp; &nbsp; (?:^(?P<boolean>TRUE|FALSE)$)&nbsp; &nbsp; |&nbsp; &nbsp; (?:^(?P<integer>-?\d+)$)&nbsp; &nbsp; |&nbsp; &nbsp; (?:^(?P<float>-?\d+\.\d+)$)&nbsp; &nbsp; |&nbsp; &nbsp; (?:^(?P<string>.+)$)&nbsp; &nbsp; ''', re.VERBOSE)for string in strings:&nbsp; &nbsp; m = rx.search(string)&nbsp; &nbsp; instance = [k for k,v in m.groupdict().items() if v is not None]&nbsp; &nbsp; print(instance)&nbsp; &nbsp; if instance:&nbsp; &nbsp; &nbsp; &nbsp; print("{} is probably a(n) {}".format(string, instance[0]))正如您在原始问题上方的评论中所说,您可能会遵循另一种方式try/except。

拉风的咖菲猫

例如,您可以使用以下代码围绕有效整数构建 if 语句:&nbsp;if isinstance(<var>, int):&nbsp;否则获取类型type(<var>)并围绕它构建函数。
随时随地看视频慕课网APP

相关分类

Python
我要回答