【问题标题】:Printing characters(with delay) on the same widget multiple times in Tkinter在 Tkinter 中多次在同一个小部件上打印字符(有延迟)
【发布时间】:2019-11-10 06:07:00
【问题描述】:

我正在尝试在同一个小部件上一个接一个地多次延迟打印(一个字符出现,几毫秒过去,然后下一个字符出现),类似于 >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()

【问题讨论】:

    标签: user-interface tkinter textbox output python-3.7


    【解决方案1】:

    您的代码的问题是 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 秒发生.

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

    【讨论】:

      【解决方案2】:

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

      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):
          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()
      

      【讨论】:

      • 哦,非常感谢您的帮助,它工作得很好:333
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 2014-03-06
      • 2020-07-16
      相关资源
      最近更新 更多