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

Python美国州猜测游戏文件找不到错误求助

解决Tkinter无法读取图片路径的问题及代码优化

一、路径错误的核心原因与解决方法

错误信息里的路径变成了guess the states gamlank_states_img.png,这是因为Windows路径中的单反斜杠\在Python字符串中是转义字符:你路径里的\b(来自game\blank)被解析为退格符,直接删掉了game的最后一个字母e,导致路径被篡改,系统找不到正确的文件。

解决方法三选一:

  • 使用原始字符串:在路径前加r,让Python不解析转义字符:
    image_path = r"D:\python course\day 25 - introduction to pandas\guess the states game\blank_states_img.png"
    data_file_path = r"D:\python course\day 25 - introduction to pandas\guess the states game\50_states.csv"
    
  • 用双反斜杠代替单反斜杠:
    image_path = "D:\\python course\\day 25 - introduction to pandas\\guess the states game\\blank_states_img.png"
    data_file_path = "D:\\python course\\day 25 - introduction to pandas\\guess the states game\\50_states.csv"
    
  • 用正斜杠作为路径分隔符(Python在Windows下兼容这种写法):
    image_path = "D:/python course/day 25 - introduction to pandas/guess the states game/blank_states_img.png"
    data_file_path = "D:/python course/day 25 - introduction to pandas/guess the states game/50_states.csv"
    

二、代码中的其他bug修复

除了路径问题,你的代码还有两处需要调整:

  1. 坐标获取错误:text.goto(state_details[1], state_details[2])写法错误,state_details是筛选后的DataFrame行,需通过列名+iloc[0]获取具体坐标值:
    text.goto(int(state_details.x.iloc[0]), int(state_details.y.iloc[0]))
    
  2. 缺少游戏退出逻辑:当前循环无法终止,可添加输入Exit退出的逻辑,并记录未猜对的州:
    guessed_states = []
    game_is_on = True
    
    while game_is_on:
        answer = screen.textinput(title=f"{len(guessed_states)}/50 States Correct",
                                  prompt="Write name of a state (type 'Exit' to quit)").capitalize()
        
        if answer == "Exit":
            # 保存未猜对的州到文件
            missing_states = [state for state in states_data if state not in guessed_states]
            pd.DataFrame(missing_states, columns=["state"]).to_csv("missing_states.csv")
            game_is_on = False
        elif answer in states_data.values and answer not in guessed_states:
            guessed_states.append(answer)
            state_details = data[data.state == answer]
            text = turtle.Turtle()
            text.hideturtle()
            text.penup()
            text.goto(int(state_details.x.iloc[0]), int(state_details.y.iloc[0]))
            text.write(answer)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:43:13