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

Tkinter循环窗口问题:定时显示词汇练习窗口失效

词汇练习程序:定时弹窗问题解决

需求

开发一个词汇练习程序,实现每30分钟弹出一个包含当前学习词汇的窗口。

初始代码

import time
from tkinter import *

window = Tk()
date = time.ctime()
text = Text(window, width=40, height=10)
window.title("Active Recall Trainer")
text.insert("1.0", "here is my text to insert")
canvas = Canvas(window, width=750, height=500, bg="SpringGreen2")
window.configure(width=300, height=150)
canvas.create_text(30, 10, text="""VOCABULARY""", fill="red")

while True:
    time.sleep(60*30)
    window.mainloop()
    print("Loop Complete")

遇到的问题

  • while True循环仅能显示一次窗口,窗口运行时循环被阻塞,无法执行后续的print("Loop Complete")语句
  • 关闭窗口后循环继续,但窗口不再弹出
  • 尝试用quit()和destroy()函数关闭窗口时:
    • 使用destroy()会触发_tkinter.TclError报错
    • 使用quit()时循环持续,但窗口无法再次弹出
  • 问题根源:mainloop()会创建嵌套循环,打乱了外部while循环的执行逻辑

解决方法及最终代码

通过重新创建窗口实例并结合after()方法解决问题,最终代码如下:

import time
from tkinter import *
window = Tk()

while True:
    window = Tk()

    # 窗口设置
    text = Text(window, width=40, height=10)
    window.title("Active Recall Trainer")
    text.insert("1.0", "here is my text to insert")
    canvas = Canvas(window, width=750, height=500, bg="SpringGreen2")
    window.configure(width=300, height=150)

    # 文本绘制
    canvas.create_text(30, 10, text="""VOCABULARY""", fill="red")

    window.configure(bg="lightgray")
    canvas.pack()

    # 窗口控制
    window.after(3000, window.mainloop())
    window.after(1000, window.quit())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:50:37