您的代码正在并行执行两个文本,因此您将获得以下输出:
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