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

Tkinter实现点击按钮后每2秒随机插入单个字符串至Listbox

解决Tkinter中定时更新Listbox且仅显示单个条目的问题

你的代码问题出在time.sleep()会阻塞Tkinter的主事件循环,导致所有更新要等循环结束后才一次性显示,而且没有清空Listbox导致条目累加。下面是修正后的代码,改用Tkinter原生的after()方法实现非阻塞定时更新,同时保证每次只显示一个条目:

import random
from tkinter import *

def update_note():
    # 清空Listbox,确保仅显示当前条目
    list1.delete(0, END)
    # 随机选取和弦
    output = random.choice(c)
    list1.insert(END, output)
    # 2秒后再次调用自身,实现循环更新
    global after_id
    after_id = window.after(2000, update_note)

def practice_key_of_c():
    # 启动定时更新逻辑
    update_note()

def stop_update():
    # 停止定时任务
    if after_id:
        window.after_cancel(after_id)

# 和弦列表
c = ["C","Dm","Em","F","G","Am"]
after_id = None  # 用于存储定时任务ID,方便停止

window = Tk()
window.geometry("350x200")
window.wm_title("guitar quiz")

list1 = Listbox(window, height = 8, width = 35)
list1.grid(row = 2, column = 0, rowspan = 6, columnspan = 2)

b1 = Button(window, text="启动和弦随机显示", width = 14, command=practice_key_of_c)
b1.grid(row = 2, column = 3)

# 新增停止按钮,方便手动终止更新
b2 = Button(window, text="停止显示", width = 14, command=stop_update)
b2.grid(row = 3, column = 3)

window.mainloop()

核心修改说明:

  • 替换time.sleep()为after()方法:after(2000, update_note)会在2000毫秒后异步执行update_note函数,不会阻塞GUI主循环,界面能实时响应更新。
  • 每次更新前清空Listbox:通过list1.delete(0, END)删除所有现有条目,确保Listbox中始终只有当前选中的和弦。
  • 递归调用实现循环更新:在update_note末尾再次调用after(),实现每隔2秒自动刷新内容。
  • 添加停止功能:通过after_cancel()可以终止定时任务,避免无限循环更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:50:40