Python Tkinter 如何更新 for 循环中的文本小部件?

Dav*_*ews 0 tkinter python-3.x

我正在尝试更新 for 循环内的滚动文本小部件中的文本。print 语句每次通过循环都会显示更新的文本,但在循环完成之前我在 Tk 窗口中看不到任何内容。然后我看到'('这是循环中的', 4, '次。')'。我从未见过显示 0 到 3。

from   tkinter import *
from   tkinter import scrolledtext
import time

main = Tk()
main.title("test_loop")
main.geometry('750x625')
main.configure(background='ivory3')


def show_msg():
    global texw
    textw = scrolledtext.ScrolledText(main,width=40,height=25)
    textw.grid(column=0, row=1,sticky=N+S+E+W)
    textw.config(background="light grey", foreground="black",
             font='arial 20 bold', wrap='word', relief="sunken", bd=5)
    for i in range(5):
        txt = "This is ", i, " times though the loop."
        txt = str(txt)
        print(txt)
        textw.delete('1.0', END)  # Delete any old text on the screen
        textw.update()            # Clear the screen.
        textw.insert(END, txt)    # Write the new data to the screen
        time.sleep(5)

btn = Button(main, text = 'display_log', bg='light grey', width = 15, 
         font='arial 12', relief="raised",bd=5,command = show_msg)
btn = btn.grid(row = 0, column = 0)

main.mainloop()
Run Code Online (Sandbox Code Playgroud)

Бог*_*пир 5

问题是在循环运行之前您的窗口不会更新。为了避免它“冻结”,您应该定期更新它。做这样的事情:

from tkinter import *
do_your_init()
tk = Tk()
do_your_preparation()
for x in range(n):
    do_your_update()
    tk.update()
Run Code Online (Sandbox Code Playgroud)

希望这有帮助!祝你好运!