一小段延迟后如何依次打印字符

时间:2019-10-15 07:40:16

标签: python tkinter

该程序在延迟0.5后打印整个字符串。我想在延迟0.5后打印每个字符。如何操作。请帮助我。该程序在延迟之后打印整个单词

import tkinter as tk
import time
class tab:
    i=0
    def __init__(self,master):
        self.input=tk.Entry(master,text="Input")
        self.input.grid(column=1,row=1)
        self.button=tk.Button(master,text="Click me!",command=self.printt)
        self.button.grid(column=1,row=2)
        self.label=tk.Label(master,text="")
        self.label.grid(column=1,row=3)
    def printt(self):
        try:
            t=str(self.input.get())
            tab.i=0
            while(tab.i< len(t)):
                  self.label['text']=self.label['text'] + t[tab.i]
                  time.sleep(0.5)
                  tab.i = tab.i + 1

        except ValueError:
            self.label['text']="Error"
            return



root=tk.Tk()
tab(root)
root.geometry('300x400')
root.mainloop()

1 个答案:

答案 0 :(得分:1)

我从python邮件列表中获得了这段代码。朋友们感谢您的支持和帮助

import tkinter as tk

class App(tk.Tk):
    def __init__(self,*args, **kwargs):
         tk.Tk.__init__(self, *args, **kwargs)
         self.label = tk.Label(self, text="", width=20, anchor="w")
         self.label.pack(side="top",fill="both",expand=True)
         self.print_label_slowly("Hello, world!")

    def print_label_slowly(self, message):
         '''Print a label one character at a time using the event loop'''
         t = self.label.cget("text")
         t += message[0]
         self.label.config(text=t)
         if len(message) > 1:
             self.after(500, self.print_label_slowly, message[1:])

app = App()
app.mainloop()