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

如何实现Tkinter滚动条的实时动态更新?

Fixing Your Auto-Updating Scrollable List in Tkinter

Let's break down what's going wrong with your current code first:

  • You're creating a new Scrollbar and Listbox every single second inside the while True loop. That means your window will get flooded with duplicate widgets instead of adding lines to one existing list.
  • Using time.sleep(1) blocks Tkinter's main event loop, which is why your GUI will freeze up and won't update properly—Tkinter can't handle rendering or user interactions while it's stuck sleeping.

Here's the corrected version that works as intended:

from tkinter import *

master = Tk()

# Create the scrollbar and listbox ONCE, outside the update function
scrollbar = Scrollbar(master)
scrollbar.pack(side=RIGHT, fill=Y)

listbox = Listbox(master, yscrollcommand=scrollbar.set)
listbox.pack(side=LEFT, fill=BOTH, expand=True)  # Add expand=True to fill available space
scrollbar.config(command=listbox.yview)

def add_line():
    # Insert new line into the existing listbox
    listbox.insert(END, "Another line")
    # Auto-scroll to the bottom to show the new line
    listbox.see(END)
    # Schedule the next update in 1 second (1000 milliseconds)
    master.after(1000, add_line)

# Start the auto-update cycle
add_line()

# Run Tkinter's main event loop
master.mainloop()

Key improvements:

  • We initialize the Scrollbar and Listbox once when the app starts, not every time we add a line.
  • Instead of a blocking while loop and time.sleep, we use Tkinter's after() method. This schedules the add_line function to run every 1000ms (1 second) without freezing the GUI.
  • Added listbox.see(END) to automatically scroll to the bottom whenever a new line is added, so users don't have to manually scroll down.
  • Added expand=True to the Listbox's pack arguments so it fills the window properly if you resize it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:02:36