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

如何为Python Tkinter游戏实现空格键控制的暂停续玩功能

实现Tkinter颜色游戏的暂停功能

要满足你的三个需求(暂停后从当前位置继续、SPACE键切换暂停/恢复、bind实现),可以通过以下步骤修改代码:

核心修改点

  • 添加全局变量标记游戏暂停状态
  • 改造倒计时函数,使其在暂停时停止计时
  • 编写暂停切换函数并绑定SPACE键
  • 优化交互:暂停时禁用输入框,避免误操作

修改后的完整代码

from tkinter import *
from tkinter import messagebox
import random

win = Tk()
win.title('Color game')
win.geometry('500x500')
win.config(bg = "#C1AB8C")
win.resizable(0,0)

#================================全局变量=====================================
colors = ['Yellow' , 'Blue' , 'Green' , 'Black' , 'Red' , 'Orange' , 'White' , 'Purple' , 'Brown']
score = 0
timeleft = 45
is_paused = False  # 标记游戏是否处于暂停状态

#================================function=====================================
def startgame(event):
    global is_paused
    if timeleft == 45 :
        countdown()
    is_paused = False  # 启动游戏时重置暂停状态
    nextcolor()

def nextcolor():
    global score
    global timeleft
    if timeleft > 0 and not is_paused:  # 仅非暂停状态下处理输入
        ent.focus_set()
        if ent.get().strip():
            if ent.get().lower() == colors[1].lower():
                lbl_feedback.config(text = 'CORRECT!' , fg = '#075B21')
                score += 1
            else:
                lbl_feedback.config(text = 'WRONG!' , fg = '#AE1717')
        else:
            lbl_feedback.config(text= '')
        ent.delete(0 , END)
        random.shuffle(colors)
        lbl_color.config(fg = str(colors[1]) , text = str(colors[0]))
        lbl_score.config(text = 'Score :' + str(score) , font = ('comic sans ms' , 16 , 'bold') )

def countdown():
    global timeleft
    global is_paused
    if timeleft > 0:
        if not is_paused:  # 仅非暂停状态下更新时间
            timeleft -= 1
            lbl_time.config(text='Time :' + str(timeleft) , font = ('comic sans ms' , 16 , 'bold'))
            
            if timeleft <= 10 and timeleft > 0 :
                lbl_hurry_up.config(text ='Hurry up ,you are\n runing out of time!!!\U0001f630' )
            elif timeleft == 0 :
                messagebox.showinfo('End' , 'Times up!')
        # 无论是否暂停,持续调用自身,保证恢复后能继续计时
        lbl_time.after(1000 , countdown)

def toggle_pause(event):
    global is_paused
    is_paused = not is_paused
    if is_paused:
        lbl_feedback.config(text='PAUSED', fg='#FF8C00')
        ent.config(state=DISABLED)  # 暂停时禁用输入框
    else:
        lbl_feedback.config(text='')
        ent.config(state=NORMAL)   # 恢复时启用输入框
        ent.focus_set()

def escape(event):
    global timeleft
    result = messagebox.askquestion('Quit' , 'Are you sure to quit?')
    if result == 'yes':
        win.destroy()
        
#================================label========================================
lbl_question = Label(win , text = 'Enter the color of each word.' , font = ('comic sans ms' , 19 , 'bold'))
lbl_question.place(x = 60 , y = 20)

lbl_time = Label(win , text = 'Time :' , font = ('comic sans ms' , 16 , 'bold'))
lbl_time.place(x = 130, y = 70)

lbl_hurry_up = Label(win , text = '' , font = 'arial 13 bold' , bg = "#C1AB8C" , fg = "#B80000")
lbl_hurry_up.place(x = 290 , y = 70)

lbl_score = Label(win , text = 'Score :' , font = ('comic sans ms' , 16 , 'bold'))
lbl_score.place(x = 130 , y = 115)

lbl_color = Label(win , text = '' , font = 'arial 33 bold' , bg = "#C1AB8C" )
lbl_color.place(x =170 , y = 180 )

lbl_feedback = Label(win , text = '' , font = 'arial 12 bold' , bg = "#C1AB8C")
lbl_feedback.place(x = 190, y = 270)

#================================entry========================================
ent = Entry(win , font = 'arial 17' ,  width = 20)
ent.place(x = 105 , y = 240)

#================================frame========================================
frame_tip =LabelFrame(win , text='Tips' , font=('Arial',12 , 'bold') ,width=370 , height=180 , bg = "#C1AB8C" , fg = "#B80000")
frame_tip.place(x = 89 , y = 300)

lbl_welcome = Label (frame_tip , text = f'\u2b55Welcome to COLOR GAME.   ' '\n\u2b55The game starts with ENTER.\n\u2b55The game stops with SPACE.\n\u2b55The game closes with ESC.   '   '\n\u2b55Answer them all,you will win. ''\n\u2b55You only have 45 seconds.'"\U0001F605" , font = 'arial 15 bold' , bg = "#C1AB8C" ,fg = "#503B3B")
lbl_welcome.pack(padx = 4 , pady =3 )

#================================bind=========================================
win.bind('<Return>' , startgame)
win.bind('<Escape>' , escape)
win.bind('<space>' , toggle_pause)  # 绑定SPACE键实现暂停切换

win.mainloop()

关键逻辑说明

  1. 暂停状态控制:通过is_paused全局变量记录游戏状态,切换时直接反转布尔值。
  2. 倒计时续跑:倒计时函数每次执行都会通过after调度下一次调用,暂停时仅跳过时间更新,保证恢复后能无缝继续计时。
  3. 交互优化:暂停时禁用输入框,避免玩家误操作;恢复时自动聚焦输入框,提升游戏流畅度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 03:08:13