You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter猜数字游戏:int与str拼接报错,需实现尝试次数统计

问题解决:猜数字游戏的TypeError与尝试次数统计

1. 修复TypeError错误

你遇到的can only concatenate str (not 'int') to str错误,根源是str(tries)仅做了类型转换但未赋值给变量,原tries仍为整数类型,直接和字符串拼接必然报错。

有两种简洁的修复方式:

  • 方式一:将转换后的字符串赋值给变量再参与拼接:
    tries_str = str(tries)
    e = b + d + " " + tries_str + " " + c
    
  • 方式二:用Python的f-string自动处理类型转换(更推荐,代码更简洁):
    e = f"You guessed the number! It took you {tries} tries. Do you want to play again?"
    

2. 正确实现尝试次数计数

你的代码未对tries做递增操作,递归调用时也没维护尝试次数状态,还缺少随机数生成逻辑(变量a未定义),需从以下几点修改:

  • 用户输入有效数字(无论猜中与否),尝试次数加1
  • 重新开始游戏时,重置尝试次数并生成新的随机数
  • 将尝试次数作为参数传入递归函数,避免全局变量的副作用

修改后的完整代码

import turtle
import messagebox
import random
import sys

def Guesser(tries=0, target_num=None):
    # 首次启动或重新开局时生成随机目标数
    if target_num is None:
        target_num = random.randint(1, 100)
    try:
        guess = int(turtle.textinput('Guess the Number!', 'Guess a number between 1 and 100!'))
        # 有效输入才计入尝试次数
        tries += 1
        if guess == target_num:
            win_msg = f"You guessed the number! It took you {tries} tries. Do you want to play again?"
            winner = messagebox.askquestion('Guess the Number!', win_msg)
            if winner == 'yes':
                # 重新开局,重置尝试次数与目标数
                Guesser()
            else:
                sys.exit()
        elif guess < target_num:
            messagebox.showinfo('Guess the Number!', 'You need to guess higher!')
            # 继续当前游戏,传递当前尝试次数与目标数
            Guesser(tries, target_num)
        elif guess > target_num:
            messagebox.showinfo('Guess the Number!', 'You need to guess lower!')
            Guesser(tries, target_num)
    except Exception:
        messagebox.showwarning('Guess the Number!', 'You have not entered a number. Please enter a number between 1 and 100!')
        quitter = messagebox.askquestion('Guess the Number!', 'Do you want to quit?')
        if quitter == 'yes':
            sys.exit()
        else:
            # 错误输入不计入尝试次数,继续当前游戏
            Guesser(tries, target_num)

# 启动游戏
Guesser()

关键修改说明

  • 导入random模块生成1-100的随机目标数,sys模块用于正确退出程序
  • 将tries和target_num作为函数参数,递归调用时传递当前状态,避免全局变量干扰
  • 仅当用户输入有效数字时,尝试次数才递增,错误输入不算尝试次数
  • 用f-string简化文本拼接,彻底解决类型转换问题
  • 重新开局时自动重置尝试次数并生成新的随机数

内容的提问来源于stack exchange,提问作者BeardedWeazel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 15:53:46