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

Tkinter石头剪刀布游戏点击操作按钮重置倒计时功能实现求助

现有代码核心问题

  • 按钮绑定的回调里countdown没有加括号,点击按钮时不会执行该函数
  • 没有存储定时器ID,无法取消正在运行的计时任务,会出现多个计时任务同时运行的异常
  • 缺少重置计时参数、重启倒计时的逻辑
  • 原有胜负判断逻辑存在错误,直接将Label组件转为字符串对比,无法得到正确结果

修改后可用代码

1. 全局变量调整

t = 10
countdown_task_id = None  # 新增变量存储定时器ID

2. 倒计时与重置逻辑

def countdown():
    global t, computer_score, countdown_task_id
    if t > 0:
        print(t)
        timer.config(text=t)
        t = t - 1
        # 存储本次定时器ID用于后续取消
        countdown_task_id = timer.after(1000, countdown)
    elif t == 0:
        timer.config(text='00')
        winner.config(text="TIMES UP !! Computer Won !!")
        computer_score += 1
        comp_score.config(text='Computer Score : ' + str(computer_score))
        # 修正胜负判断逻辑,取分数数值对比
        your_score_val = int(your_score.cget("text").split(":")[-1].strip())
        if computer_score > your_score_val:
            champ = 'COMPUTER'
        elif computer_score == your_score_val:
            champ = 'TIE'
        else:
            champ = 'YOU'
        win.config(text='Winner : ' + champ, font=('calibri',15), fg='red')
        countdown_task_id = None

def reset_countdown():
    global t, countdown_task_id
    # 取消正在运行的旧定时器
    if countdown_task_id:
        timer.after_cancel(countdown_task_id)
    # 重置计时参数
    t = 10
    # 重新启动倒计时
    countdown()

3. 按钮绑定调整

rock = Button(
    input_frame, 
    pady = 5, 
    text = 'Rock', 
    width = 15, 
    bg = 'pink',
    command = lambda: [player_choice(options[0]), reset_countdown()]
)
rock.grid(row = 1, column = 1,padx = 8, pady = 5)

paper = Button(input_frame, 
    pady = 5,
    text = 'Paper',
    width = 15,
    bg = 'silver',
    command = lambda: [player_choice(options[1]), reset_countdown()]
)
paper.grid(row = 1, column = 2,padx = 8,pady=1)

scissors = Button(input_frame, 
    pady = 5, 
    text = 'Scissors', 
    width = 15,
    bg = 'light blue',
    command = lambda: [player_choice(options[2]), reset_countdown()]
)
scissors.grid(row = 1, column = 3,padx = 8, pady = 5)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:27:03