Python TK如何检查输入是字符串还是数字?

Python TK如何检查输入是字符串还是数字?,python,tkinter,Python,Tkinter,因此,我基本上是在检查用户是否输入了正确的变量类型。它应该是int或float。如果没有,那么应该有一个消息框,说明输入不正确或类似的内容 这是代码。此函数当前用于测试目的。我还有一个,但它有很多嵌套条件,因此我想看看这是否有效: def test(gameNames, gamePrices): gamePriceInput = priceText.get("1.0", END) if type(int(gamePriceInput)) == int

因此,我基本上是在检查用户是否输入了正确的变量类型。它应该是int或float。如果没有,那么应该有一个消息框,说明输入不正确或类似的内容

这是代码。此函数当前用于测试目的。我还有一个,但它有很多嵌套条件,因此我想看看这是否有效:

def test(gameNames, gamePrices):
    gamePriceInput = priceText.get("1.0", END)
    
    if type(int(gamePriceInput)) == int or type(float(gamePriceInput)) == float:
        print("its a number")
    elif type(str(gamePriceInput))==str :
        print("not a number")
gameNames和gamePrices是一个列表,它们在这个测试函数中没有任何用途,只是保留它们,这样当我在测试函数和正确的函数之间来回移动时,我就不需要删除列表了


使用Python 3.7

< P>你可以使用Type语句来做这个,你可以尝试把这个值转换成一个浮点数,即使它是一个整数,它会被转换成一个浮点,从你的问题中,你似乎认为数字既包含浮点又包含整数。 如果将值转换为浮点值时引发异常,则表示该值不是数字,然后可以在except语句中执行类似的测试,以进行字符串检查

像这样-:

def check_type(val) :
    try :
        float(val) # Tries to convert the value to a float.
        print('Value is a number!') # If an exception is not thrown the value is a number and the same is printed.
    except ValueError :
        print('Value is not a number!') # If an exception is thrown the same is caught and the value is not a number and the same is printed.
    return
正如您所指出的,如果您只想将输入限制为数值,那么您应该签出-

您可以使用它来执行此操作

如果re.fullmatch(^(?:\。?\d+)|(?:\。\d+)|(?:\d+)$),str(gamePriceInput))为None:#None表示不匹配
打印(“不是数字”)
其他:
打印(“它是一个数字”)

请参阅我为测试正则表达式而制作的应用程序。

我编写了这个Tkinter模拟Tkinter应用程序,它检查“Price”是否是一个数字(int,float),并相应地显示一条消息,我已经在一些重要部分和变量上发表了评论,希望这能有所帮助

from tkinter import *
global root, canvas, ef, is_int, is_float, error, box, price_type_is_number


# Setting Our variables that we will use later to None for the time being
is_int = None
is_float = None
error = None
box = None
price_type_is_number = None  # This is the final result, if it's a number, Float, int, or not.

# Setting up the Tk Window and Canvas
root = Tk()
canvas = Canvas(width=500, height=500)
canvas.pack()


# Functions

def submit():
    global root, canvas, ef, is_int, is_float, error, box, price_type_is_number
    price_type_is_number = None
    if not is_int and not is_float: # If it's not a float and not an int it displays an error
        try: # Just Tries to remove any previous instances of the box element, or error element to avoid lag and overlapping
            box.destroy()
            error.destroy()
        except:
            pass
        box = Label(bg="gray75", width=20, height=5)
        price_type_is_number = False  # You can use this value to get the definite status if the price is a number, float, int. But here it sets it to False
        error = Label(text="Price must be a number", fg="red", bg="gray75")
        canvas.create_window(165, 200, anchor="nw", window=box)
        canvas.create_window(165, 210, anchor="nw", window=error)
    elif is_int or is_float: # If it's a float, or int it displays the correct message
        try: # Just Tries to remove any previous instances of the box element, or error element to avoid lag and overlapping
            box.destroy()
            error.destroy()
        except:
            pass
        price_type_is_number = False  # You can use this value to get the definite status if the price is a number, float, int. But here it sets it to True
        box = Label(bg="gray75", width=20, height=5)
        error = Label(text="Price is a number", fg="green", bg="gray75")
        canvas.create_window(165, 200, anchor="nw", window=box)
        canvas.create_window(165, 210, anchor="nw", window=error)


def process():
    global root, canvas, ef, is_int, is_float
    try: # checks to see if it can convert the str into a float
        f_test = float(ef.get())
        is_float = True # If it can it sets it's float status to true
    except ValueError: # If it can't sets it's float status to false
        is_float = False
    try: # Checks to see if it can convert the str into an int
        int_test = int(ef.get())
        is_int = True # If it can sets the int status to true
    except ValueError: # if it can't sets it to false
        is_int = False
    submit() # Runs the submit command


# Widgets

efl = Label(text="Price") # Label For Entry Field
ef = Entry() # Entry Field
efb = Button(text="Enter", command=process)# Button to submit


# Adding Widgets to Canvas
canvas.create_window(165, 150, anchor="nw", window=ef)
canvas.create_window(165, 110, anchor="nw", window=efl)
canvas.create_window(315, 145, anchor="nw", window=efb)
mainloop()

最好的方法是:

def check_type(val) :
  try :
    float(val) 
    print('The value entered was a number.') 
  except ValueError :
    print('The value entered was a string.') 
  return

程序尝试转换为一个数字,但如果转换失败,它会检测到它是一个字符串。

如果输入始终是字符串,请尝试使用另一种方法,而不是使用类型,或者尝试使用
gamePriceInput.isdigit()
。此外,发生了什么问题?有错误吗?非预期输出?如果用户输入
aaa
,您的程序将崩溃,因为它试图调用
int(“aaa”)
,这将引发错误。您可以使用
try
/
except
捕捉错误并从那里开始工作。是的,非常感谢,try-except非常有效。下面是代码,也许它会帮助其他人:def checkIfNumber():gamePriceInput=priceText.get(“1.0”,END)try:parsed=float(gamePriceInput)if type(parsed)==float:return True除了ValueError:return false这认为“.”和“”是一个数字。我不确定这是否是OP想要的。啊,噢,谢谢。我用
+
替换了
*
,现在它可以工作了。现在你的解决方案不接受像“.1”或“1”这样的东西,python允许它们都作为浮点数。@BryanOakley正如你可能知道的,我在正则表达式方面不是最好的。但是我很确定所有可能的测试用例现在都能正常工作是的!这非常有效,稍微调整了一下,可能是最好的解决方案,谢谢!如果这个答案对你有用,请接受它。