Fundamentals 7 min read

Chinese Idiom Chain Game Implemented with Python Tkinter

This article presents a Python Tkinter implementation of a Chinese idiom chain game, explaining its educational purpose, core modules, idiom data handling, validation functions, GUI layout, game logic, hint system, and provides the complete source code for learners to run and explore.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Chinese Idiom Chain Game Implemented with Python Tkinter

Idiom Chain is an educational game that helps learn Chinese idioms while having fun.

The following Python code implements a Tkinter GUI for the game, including functions to load idioms from a JSON file, validate idioms, provide hints, and manage game flow.

import tkinter as tk
from tkinter import messagebox
import random
import json
import re
# 成语库
idiom_url = 'idiom.json'

def idioms_continue(guess):
    matching_idioms = []
    with open(idiom_url, 'r', encoding='utf-8') as file:
        s = json.load(file)
    for i in s:
        if i['word'][0] == guess[-1]:
            matching_idioms.append(i['word'])
    return matching_idioms[0] if matching_idioms else False

def idioms_start(user_input=None):
    # 如果没有用户输入,就随机选择一个成语开始
    if user_input:
        return user_input
    with open(idiom_url, 'r', encoding='utf-8') as file:
        s = json.load(file)
    return random.choice(s)['word']

def is_idiom(s):
    pattern = re.compile(r'^[\u4e00-\u9fa5]+$')
    return bool(pattern.match(s)) and 4 <= len(s) <= 8

class IdiomGameGUI:
    def __init__(self, master):
        self.master = master
        master.title("成语接龙游戏")
        self.win_count = 0
        self.start_idiom = ""
        self.create_start_widgets()
    def create_start_widgets(self):
        self.label_instruction = tk.Label(self.master, text="请输入首个成语开始游戏:", font=("Arial", 12))
        self.label_instruction.pack(pady=10)
        self.entry_first_idiom = tk.Entry(self.master, font=("Arial", 14))
        self.entry_first_idiom.pack(pady=10)
        self.button_start = tk.Button(self.master, text="开始游戏", command=self.validate_first_idiom, font=("Arial", 12))
        self.button_start.pack(pady=10)
    def validate_first_idiom(self):
        first_idiom = self.entry_first_idiom.get().strip()
        if is_idiom(first_idiom):
            self.start_idiom = first_idiom
            self.create_game_widgets()
        else:
            messagebox.showwarning("警告", "输入的不是有效的成语,请重新输入!")
    def create_game_widgets(self):
        self.label_instruction.config(text="请根据以下成语接龙:")
        self.label_idiom = tk.Label(self.master, text=self.start_idiom, font=("Arial", 16, "bold"))
        self.label_idiom.pack(pady=20)
        self.entry_guess = tk.Entry(self.master, font=("Arial", 14))
        self.entry_guess.pack(pady=10)
        self.button_submit = tk.Button(self.master, text="提交", command=self.on_submit, font=("Arial", 12))
        self.button_submit.pack(pady=10)
        self.button_hint = tk.Button(self.master, text="提示", command=self.show_hint, font=("Arial", 12))
        self.button_hint.pack(pady=5)
        self.button_quit = tk.Button(self.master, text="退出", command=self.quit_game, font=("Arial", 12))
        self.button_quit.pack(pady=10)
    def on_submit(self):
        guess = self.entry_guess.get().strip()
        if guess == '0':
            self.quit_game()
        elif is_idiom(guess):
            if guess[0] == self.start_idiom[-1]:
                self.win_count += 1
                messagebox.showinfo("恭喜", f"你赢了!接龙次数:{self.win_count}")
                self.start_idiom = idioms_continue(guess)
                self.label_idiom.config(text=self.start_idiom)
                self.entry_guess.delete(0, tk.END)
            else:
                messagebox.showerror("错误", "你输了,游戏结束(首字与尾字不相同!)")
                self.quit_game()
        else:
            messagebox.showwarning("警告", "你输入的好像不是成语,请再试一次!")
            self.entry_guess.delete(0, tk.END)
    def show_hint(self):
        hint = idioms_continue(self.start_idiom)
        if hint:
            messagebox.showinfo("提示", f"试试这个成语:{hint}")
        else:
            messagebox.showinfo("提示", "没有找到合适的成语,再试试别的吧!")
    def quit_game(self):
        answer = messagebox.askyesno("确认退出", "确定要退出游戏吗?")
        if answer:
            self.master.destroy()

def main():
    root = tk.Tk()
    app = IdiomGameGUI(root)
    root.mainloop()

if __name__ == '__main__':
    main()

The code imports tkinter for GUI creation, messagebox for dialogs, random for selecting idioms, json for reading the idiom database, and re for validating idiom format. It defines the idiom data path, helper functions for finding continuation idioms, starting the game, and checking idiom validity. The IdiomGameGUI class builds the interface, handles user input, enforces game rules, provides hints, and allows quitting. The main function launches the application.

GUIpythonprogrammingTkinterEducationalIdiom Game
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.