在 Tkinter 中多次在同一个小部件上打印字符(有延迟)

Printing characters(with delay) on the same widget multiple times in Tkinter

我正在尝试在同一个小部件上多次延迟打印(一个字符出现,几毫秒过去,然后下一个字符出现),就像 > 文本延迟显示 > a第二遍>更多文本出现延迟......等等。 time.sleep() 似乎不起作用,我不知道如何正确使用 .after()

这是我正在使用的代码

from tkinter import *

def insert_slow(widget, string):
    if len(string) > 0:
        widget.insert(END, string[0])

    if len(string) > 1:
        widget.after(50, insert_slow, widget, string[1:])

root=Tk()

tx=Text(root)

tx.pack()
insert_slow(tx, "this is a testing piece of text\n")
tx.after(3000)
loop=insert_slow(tx, "this is another testing piece of text")

root.mainloop()

您的代码并行执行这两个文本,因此您得到以下输出:

text1 = 'Hi to you'
text2 = 'Hi to me'

OUTPUT:
HHii  tt  oo  ymoeu

您的 insert_slow 表现良好,但如果您尝试 运行 文本分两行。

如果是这样,这应该在不同的新文本小部件上。

如果您想在同一个小部件上输出文本 ,此代码有效:

from tkinter import *

def insert_slow(widget, string):
    if len(string) > 0:
        widget.insert(END, string[0])

    if len(string) > 1:
        widget.after(50, insert_slow, widget, string[1:])

root=Tk()

tx=Text(root)
tx.pack()

text_body = "this is a testing piece of text\n" \
            "this is another testing piece of text"



insert_slow(tx, text_body)

root.mainloop()

如果你想让文本行一起插入慢一点,你也可以用这个:

from tkinter import *

def insert_slow(widget, string):
    if len(string) > 0:
        widget.insert(END, string[0])

    if len(string) > 1:
        widget.after(50, insert_slow, widget, string[1:])

root=Tk()

tx1=Text(root)
tx2=Text(root)
tx1.pack()
tx2.pack()

text_body1 = "this is a testing piece of text\n"
text_body2 = "this is another testing piece of text"



insert_slow(tx1, text_body1)
insert_slow(tx2, text_body2)

root.mainloop()

您的代码的问题在于 after(3000)time.sleep 几乎完全相同——它冻结了整个 UI.

解决方案非常简单:使用 after 调用第二个 insert_slow

insert_slow(tx, "this is a testing piece of text\n")
tx.after(3000, insert_slow, tx, "this is another testing piece of text")

但是,您需要注意 after 是相对于您调用 after 的时间而言的。由于上面示例中的第二行代码仅在第一行之后运行一毫秒,因此第二次调用不会在第一个字符串出现后 3 秒发生,而是在 开始后 3 秒发生 出现。

如果你想等第一个完成然后然后等三秒钟,你要么必须自己做数学(添加 50ms 乘以字符数到起始值),或添加一些其他机制。您可以将多个字符串传递给 insert_slow,它可以在每个字符串之间自动等待三秒钟。