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

Tkinter闪卡程序Bug:无法先显示法语直接展示英语

问题排查与修复:Tkinter闪卡程序无法显示法语单词

问题原因

你的button_y_pressed函数存在逻辑错误:在设置法语文本后,立刻执行了设置英语文本的代码,而window.after(3000, flip_card)只是延迟触发卡片翻转动作,但不会暂停后续代码的执行。这就导致法语单词刚被设置就被英语覆盖,用户完全看不到法语内容。

修复方案

  1. 移除button_y_pressed中直接设置英语文本的代码;
  2. 将选中的单词保存为全局变量,让flip_card在3秒后负责设置英语文本并完成卡片翻转。

修复后的完整代码

from tkinter import *
import pandas
import random

current_word = {}  # 保存当前选中的单词

def button_y_pressed():
    global current_word
    current_word = random.choice(data)
    # 先显示法语卡片
    canvas.itemconfig(text1, text="French")
    canvas.itemconfig(text2, text=current_word["French"])
    canvas.itemconfig(canvas_image, image=front_image)  # 确保回到正面卡片
    window.after(3000, flip_card)

def flip_card():
    # 翻转到英语卡片
    canvas.itemconfig(text1, text="English")
    canvas.itemconfig(text2, text=current_word["English"])
    canvas.itemconfig(canvas_image, image=back_image)

BACKGROUND_COLOR = "#B1DDC6"
window = Tk()
window.configure(bg=BACKGROUND_COLOR)
window.geometry("900x780")
window.title("Flash Cards")

my_image_x = PhotoImage(file="images/wrong.png")
button_x = Button(image=my_image_x, highlightthickness=0)
button_x.grid(row=1, column=0, padx=10, pady=10)

my_image_y = PhotoImage(file="images/right.png")
button_y = Button(image=my_image_y, highlightthickness=0, command=button_y_pressed)
button_y.grid(row=1, column=1, padx=10, pady=10)

front_image = PhotoImage(file="images/card_front.png")
canvas = Canvas(window, width=800, height=526, highlightthickness=0, bg=BACKGROUND_COLOR)
canvas_image = canvas.create_image(400, 263, image=front_image)
canvas.grid(row=0, column=0, columnspan=2, padx=50, pady=50)
back_image = PhotoImage(file="images/card_back.png")
text1 = canvas.create_text(400, 150, text="text1", font=("Arial", 40, "italic"))
text2 = canvas.create_text(400, 263, text="text2", font=("Arial", 60, "bold"))

data = pandas.read_csv("data/french_words.csv")
data = data.to_dict(orient="records")

button_y_pressed()

window.mainloop()

额外优化说明

修复代码中添加了canvas.itemconfig(canvas_image, image=front_image)到button_y_pressed函数,确保每次点击按钮时卡片先回到正面,避免连续点击时卡片停留在背面的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 19:24:57