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

我试图在同一控件上多次延迟打印(出现一个字符,经过几毫秒然后出现下一个字符),一次又一次,例如> text出现延迟>一秒钟>延迟显示更多文本...等等。 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()

cqw101 回答:在Tkinter中多次在同一小部件​​上打印字符(延迟)

您的代码正在并行执行两个文本,因此您将获得以下输出:

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

OUTPUT:
HHii  tt  oo  ymoeu

您的 insert_slow 表现良好,但如果尝试在两行中分别运行文本,则无需再次使用 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()

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[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,tx,"this is another testing piece of text")

但是,您需要知道after与您呼叫after的时间有关。由于上述示例中的第二行代码仅在第一行之后的毫秒内运行,因此第二次调用不会在第一个字符串出现后3秒发生,而是在开始出现后3秒发生。

如果要等待第一个完成,然后然后等待三秒钟,则必须自己进行数学运算(将50ms乘以起始字符数) ,或添加其他一些机制。您可以将多个字符串传递到insert_slow,并且每个字符串之间可以自动等待三秒钟。

本文链接:https://www.f2er.com/3130252.html

大家都在问