为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

长风秋雁 2021-11-16 15:09:59
我正在尝试检查用户对我创建的 Tk GUI 的输入是否属于我希望的正确数据类型(整数),但我只能检查他们的输入是否为布尔值,我需要检查他们的输入是字符串还是整数:from tkinter import*# creates a GUITester = 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)
查看完整描述

3 回答

?
开心每一天1111

TA贡献1836条经验 获得超13个赞

一种方法是尝试转换您的输入并查看它是否可以管理。


编辑:这基本上是@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非空就会评估为 True (这也出现在最新版本的FlyingCircus as 中flyingcircus.util.to_bool())。


查看完整回答
反对 回复 2021-11-16
?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

好吧,您可以对输入运行正则表达式并检查哪个组不是None:


(?:^(?P<boolean>TRUE|FALSE)$)

|

(?:^(?P<integer>\d+)$)

|

(?:^(?P<float>\d+\.\d+)$)

|

(?:^(?P<string>.+)$)

在 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。


查看完整回答
反对 回复 2021-11-16
?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

例如,您可以使用以下代码围绕有效整数构建 if 语句: if isinstance(<var>, int): 否则获取类型type(<var>)并围绕它构建函数。


查看完整回答
反对 回复 2021-11-16
  • 3 回答
  • 0 关注
  • 182 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信