如何检查使用 tkinter 输入的文本是否为 int? (python 和 tkinter)

How to check if text entered using tkinter is an int? (python and tkinter)

我正在尝试将交易记录保存到 excel 文件中。用户可以通过我使用 tkinter 创建的文本框输入文本。

这是我的代码的简化版本。

quantity = '0'
newWindow = Tk()
buyLabel = Label(newWindow, text = 'How many apples do you want to buy?')
global textentry2
textentry2 = Entry(newWindow, width=10)
global quantity
if quantity=="":
   quantity=0
quantity = textentry2.get()
quantity = int(float(quantity))

我想让我的程序检查用户输入的值是否可以接受。对于他们购买的苹果数量,他们应该 return 一个大于 0 的整数。因此,如果在 'textentry2' 中输入的文本是一个大于 0 的整数,则 return 为真,如果它是不是 int 或小于零。但是,我不知道如何检查输入的文本是否为 int,所以我尝试先将其转换为 int,然后检查它是否 > 0。 这是我的代码:

if (quantity > 0):
     print('your value is stored')
else:
     print('please enter an acceptable quantity')

我收到一条错误消息,指出以 10 为底的 int() 的无效文字:' ' 并且来自 Whosebug 中的另一个 post,他们说要将变量转换为浮点数,然后是 int,这就是为什么我的代码如下所示:

quantity = int(float(quantity))

但是,我仍然收到错误消息 'ValueError: could not convert string to float:' 我很困惑。谁能帮忙?如果您知道如何检查输入的文本是否为整数,那也很棒。

您可以像这样使用 python 内置字符串的方法 .isnumeric():

>>> "".isnumeric()
False
>>> "a".isnumeric()
False
>>> "5".isnumeric()
True
>>> "55".isnumeric()
True
>>> "55a".isnumeric()
False

但如果您还想检查数字是否为负数,则可能会出现问题,因为:

>>> "-5".isnumeric()
False
>>> a = "-4"
>>> a.lstrip("-").isnumeric() and (len(a)-len(a.lstrip("-")) <= 1)
True
>>> a = "--4"
>>> a.lstrip("-").isnumeric() and (len(a)-len(a.lstrip("-")) <= 1)
False

发送部分(len(a)-len(a.lstrip("-")) <= 1)检查号码前是否超过1"-"

据我所知,您可以使用 int(quantity) 将其转换为 int。在此之前,您应该使用 quantity.isnumeric().

检查字符串是否为数字

所以你的代码应该是这样的:

quantity = '0'
newWindow = Tk()
buyLabel = Label(newWindow, text = 'How many apples do you want to buy?')
global textentry2
textentry2 = Entry(newWindow, width=10)
global quantity

quantity = textentry2.get()
if quantity.isnumeric():                               # Check if the quantity is a number, as TheLizzard said, negative numbers in a string will be marked as not numeric so no need to check if it is greater than 0
   quantity = int(quantity)                            # Then set the quantity to the converted int
else                                                   # If it's not
   # whatever you want to do if it is not