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

Tkinter调用.get()预期获字符串却得到空值问题

问题原因及修复方案

核心问题

你在next_color()函数里先清空了输入框,再调用user_input.get(),这必然会得到空值:

entry_box.delete(0, "end")  # 先清空输入框
# ... 后续调用get()时输入框已为空

其他问题

  1. 更新分数时,score_l.config(f"Score: {score}")写法错误,缺少text=参数,正确写法是score_l.config(text=f"Score: {score}")
  2. 游戏逻辑顺序颠倒:应该先读取用户输入判断得分,再清空输入框并生成下一组颜色

修正后的完整代码

# Modules
from tkinter import *
import random

# Variables
colors = ["red", "blue", "green", "pink", "black", "yellow", "orange", "white", "purple", "brown"]
score = 0
max_time = 30
time_left = max_time
second_color = ""  # 全局存储当前目标颜色

# Functions
def start_game(event):
    global score_label
    # 第一次启动时更新提示文本
    if time_left == max_time:
        score_label.config(text="")
        countdown()
    # 先处理当前输入,再生成下一组颜色
    check_input()
    next_color()

def countdown():
    global time_left
    if time_left > 0:
        time_left -= 1
        time_label.config(text=f"Time Left: {time_left}")
        time_label.after(1000, countdown)
    else:
        print("\n**************")
        print("* Game over! *")
        print("**************")
        root.quit()

def check_input():
    global score
    # 获取用户输入并做格式处理
    input_val = user_input.get().strip().lower()
    if input_val == second_color:
        score += 1
        score_l.config(text=f"Score: {score}")

def next_color():
    global second_color
    # 清空输入框
    entry_box.delete(0, "end")
    first_color = random.choice(colors)
    second_color = random.choice(colors)
    label.config(text=first_color.title(), fg=second_color)

# Main Window
root = Tk()
root.title("Color Reaction")
root.geometry("375x220")
instructions = Label(root, text="Type in the color of the word, not the text.", font=("Helvetica", 12))
instructions.pack()
score_label = Label(root, text="Press [ENTER] to start.", font=("Helvetica", 12))
score_label.pack()
time_label = Label(root, text=f"Time Left: {time_left}", font=("Helvetica", 12))
time_label.pack()
score_l = Label(root, text=f"Score: {score}", font=("Helvetica", 12), fg="black")
score_l.pack()
label = Label(root, font=("Helvetica", 60))
label.pack()
user_input = StringVar()
entry_box = Entry(root, textvariable=user_input)
root.bind("<Return>", start_game)
entry_box.pack()
entry_box.focus_set()

# 初始化第一组颜色
next_color()

root.mainloop()

关键改动说明

  • 拆分逻辑:新增check_input()专门处理输入判断,确保先读取用户输入再清空输入框
  • 修复分数更新的参数错误
  • 优化启动提示文本,提升用户体验
  • 全局存储目标颜色second_color,避免跨函数调用的逻辑混乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:05:21