You need to enable JavaScript to run this app. Python Tkinter乱序单词游戏messagebox异常弹窗修复及规则首页实现
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter乱序单词游戏messagebox异常弹窗修复及规则首页实现

Tkinter乱序单词游戏问题修复方案

问题1:启动自动弹出messagebox修复

  • 根因:按钮command参数绑定函数时错误添加了括号,代码加载到按钮组件时会立即执行对应函数,而非等待用户点击触发。原代码中command = vérif_rep()、command = mélanger()两处写法均存在该问题,启动时直接执行验证逻辑触发弹窗。
  • 修复方式:去掉函数名后的括号,仅传递函数引用,即修改为command = vérif_rep、command = mélanger。
    补充:原代码还存在随机单词索引不同步的逻辑bug:mélanger函数生成的新随机索引存为lettres变量,未同步更新全局的lettre索引,会导致答案校验永远匹配不上,修复时需同步修正该问题。

问题2:前置规则页跳转逻辑实现

  • 实现逻辑:将所有游戏相关组件统一收纳到独立的游戏容器Frame中,程序启动时默认隐藏游戏容器,优先渲染规则说明Frame;用户点击规则页的确认开始按钮后,隐藏/销毁规则页,再渲染游戏容器并初始化游戏内容即可。

修复后完整代码

from tkinter import *
import random
from tkinter import messagebox

#Creation de la fenetre
fenetre = Tk()
fenetre.geometry("800x500")
fenetre.title("Jeu de mots-melés")
fenetre.configure(background="light pink")

rep =["python",'virus','while','for','if','label','import','tkinter','random','fenetre','uct','clavier','hertz','print','global']
mots=["ohtnpy",'visur','lehiw','rfo','fi','eblal','ripotm','kntiert','draomn','nefetre','tcu','vrilcea','heztr','tnrip','oabgll']

lettre =random.randrange(0,len(mots),1)
#La variable du score
a=0
#Le nombre de fois joué
j=0
#Variable qui calcule le score
s = ""

def start_game():
    # 销毁规则页,显示游戏界面
    rule_frame.destroy()
    game_frame.pack(fill=BOTH, expand=True)
    default()

def mélanger():
    global mots, rep, lettre
    lettre = random.randrange(0,len(mots),1)
    label.config(text = mots[lettre])
    E1.delete(0, END)

def default():
    global mots,rep,lettre
    label.config(text = mots[lettre])

def vérif_rep():
    global mots, rep,lettre, a, j, s, lbl_score
    j=int(j)+1
    trouve = E1.get() #obtenir la reponse
    if trouve == rep[lettre]: #Trouve si la réponse est juste ou non
        messagebox.showinfo("Bravo", "C'est la bonne reponse!!")
        a = int(a)+1
    else:
        messagebox.showerror("Oops", "C'est pas la bonne réponse.")
    s = 'Score :' + str(a) + '/' + str(j)
    lbl_score.forget()
    lbl_score = Label(game_frame, font=("Verdana", 20), text=s, bg="#800080", fg="#fff", )
    lbl_score.pack(side=LEFT)
    mélanger()

# 前置规则页Frame
rule_frame = Frame(fenetre, bg="light pink")
rule_frame.pack(fill=BOTH, expand=True)
Label(rule_frame,text="Règles du jeu",font = ("Verdana",28),bg = "#000000", fg = "#fff").pack(pady=20)
rule_text = """
1. L'écran affiche un mot dont les lettres sont mélangées
2. Saisis le mot correct dans la zone de saisie
3. Clique sur "Vérifier" pour valider ta réponse :
   - Bonne réponse : tu gagnes 1 point
   - Mauvaise réponse : aucun point ne t'est retiré
4. Tu peux cliquer sur "Mélanger" à tout moment pour passer au mot suivant
"""
Label(rule_frame, text=rule_text, font=("Verdana",14), bg="light pink", justify=LEFT).pack(pady=30)
Button(rule_frame,text = "Commencer le jeu",font = ("Comic sans ms",20),width = 15,bg="#333945",fg="#45CE30",relief = GROOVE,command = start_game).pack(pady=20)

# 游戏界面容器Frame,启动时默认不显示
game_frame = Frame(fenetre, bg="light pink")

#Création du titre
Label(game_frame,text="Jeu de mots-melés",font = ("Verdana",28),bg = "#000000", fg = "#fff").pack(pady = 5)
label = Label(game_frame,font = ("Verdana",22),bg = "#000000", fg = "#fff")
label.pack(pady = 30,ipady=10,ipadx=10)

obt_rep = StringVar()
#L'affichage du score
lbl_score= Label(game_frame)

#Boite d'entrée
E1 = Entry(game_frame,font = ("Verdana",20),textvariable = obt_rep,)
E1.pack(ipady=5,ipadx=5)

#Les boutons du code
Button(game_frame,text = "Vérifier",font = ("Comic sans ms",20),width = 10,bg="#333945",fg="#45CE30",relief = GROOVE,command = vérif_rep,).pack(pady = 40)
Button(game_frame,text = "Mélanger",font = ("Comic sans ms",20),width = 10,bg="#777E8B",fg="#E1DA00",relief = GROOVE,command = mélanger).pack()

fenetre.mainloop()

代码说明:

  • 规则页默认在程序启动时加载,所有游戏组件收纳在game_frame中初始隐藏
  • 修复了原代码按钮command绑定错误、随机索引不同步的两个bug
  • 规则文本可根据需要自行修改调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 02:42:11