如何修复 Python Turtle textinput() 中的这个 int() 错误

How do I fix this int() error in Python Turtle textinput()

当我 运行 这段代码时,当在 textinput() 中输入一个字母时,我得到一个 invalid literal 错误,因为它只是为了注册 int 值而不是 str 值。 我尝试了一些不同的东西,但 none 似乎有效。

import turtle

eg = 100

def betcurrency():
    bettedc = turtle.textinput('Bet money.',
    f'You have {eg}')

    if int(bettedc) <= eg:
        print(f'User betted {bettedc}$')
    elif int(bettedc) >= eg:
        betcurrency()
        print("Users can't bet what they don't have!")
    elif int(bettedc) <= 0:
        betcurrency()
        print('User tried to bet a negative amount.')
    else:
        betcurrency()
        print('User betted invalid money.')

这是我得到的错误;

Traceback (most recent call last):
  File "e:\Visual Studio Code\Python\Finished\Turtle Race\main.py", line 145, in <module>
    setup()
  File "e:\Visual Studio Code\Python\Finished\Turtle Race\main.py", line 112, in setup
    betcurrency()
  File "e:\Visual Studio Code\Python\Finished\Turtle Race\main.py", line 41, in betcurrency
    if int(bettedc) <= eg:
ValueError: invalid literal for int() with base 10: 'TEXT' #This is the text I put in.
import turtle

eg = 100

def betcurrency():
 try:
    bettedc = turtle.textinput('Bet money.',
    f'You have {eg}')

    if int(bettedc) <= eg:
        print(f'User betted {bettedc}$')
    elif int(bettedc) >= eg:
        betcurrency()
        print("Users can't bet what they don't have!")
    elif int(bettedc) <= 0:
        betcurrency()
        print('User tried to bet a negative amount.')
    else:
        betcurrency()
        print('User betted invalid money.')
 except ValueError :
  print("user wrote word not number as amount") 

您的错误是由于未能捕获当 int() 无法从用户输入中提取 int 时引发的错误。

如果您正在与用户输入交互并且需要某种验证,我通常建议将该逻辑移出到一个函数中。您可以从 here 修改 collect_int 以使用您正在使用的 turtle 提示符。

import turtle

def collect_int(
    heading, 
    message, 
    err_msg="Invalid number entered. Please try again."
):
    while True:
        try:
            return int(turtle.textinput(heading, message))
        except ValueError:
            message = err_msg

def bet_currency(user_currency):
    while True:
        bet = collect_int('Bet money.', f'You have {user_currency}')


        if bet <= 0:
            print('User tried to bet a negative amount.')
        elif bet <= user_currency:
            print(f'User betted {bet}$')
            break
        else:
            print("Users can't bet what they don't have!")

user_currency = 100
bet_currency(user_currency)

如果您尝试通过 turtle GUI 与用户交互,使用 print 有点奇怪。用户可能不想查看控制台。也许这些是您正在处理的正在进行的程序中的非用户可见日志,但似乎值得一提。

请注意,我还将 eg(为清楚起见重命名为 user_currency)传递给了 bet_currency 函数。函数到达自身外部以获取数据不是一个好主意——函数访问的所有变量都应该进入参数。如果参数过多或函数改变对象的属性,请使用 class 将多个相关数据分组在一个狭窄的范围内。从长远来看,这可以避免错误并使程序更易于编写。

我还删除了递归:如果提示失败的时间足够长(~1000 次),程序就会崩溃。这不太可能对您的程序很重要,安全性和可靠性可能不是您现在的首要任务,但使用 while True: 循环并从一开始就正确执行它同样容易。

elif bet <= 0:else 永远不会发生,因为前两个分支涵盖了所有可能的情况。

这个条件似乎不正确:

bet >= user_currency: 
    print("Users can't bet what they don't have!")

我希望你能赌上所有的钱,所以我会赢 bet > user_currency。这可能只是 else 因为第一个分支涵盖了另一种可能的情况 <=.

elif bet <= 0: 永远不会发生,除非 eg 可以为负数。我只是将其作为第一个选项,或者查看 this answer,它提供了更通用的提示,让您可以传入可以阻止负数并更优雅地处理这些不同场景的验证函数。

如果您的 Python 乌龟库有 textinput(),它可能还有它的伙伴 numinput(),这可能会解决您的问题:

import turtle

stack = 100

def betcurrency():
    bet = turtle.numinput("Bet money.", f"You have {stack}", minval=1, maxval=stack)

    if bet:
        print(f"User bet ${bet:.2f}")
    else:
        print("User cancelled bet.")

这可能比尝试自己处理潜在错误更简单。