Search code examples
pythonloopstkintersleep

(Python 3.7) How can i print messages characters with a delay between them using tkinter?


First of all i'm new to python and coding

I want to do something pretty simple with tkinter, when you hit a button it show you a text, like in old games, letter by letter with a little delay between each characters

I can't find a way to make the delay between characters, i've tried time.sleep with a loop but the text is shown at the end of the loop

I've seen the after function but i don't know how to use it neither i understand how it works

Should i use sleep or after ? And how should i use them to make it work ?

Btw if you have any tips or advices about the code tell me

    #MainFrame
root.title("Project")
root.geometry('400x400')
root.configure(bg="plum1")
    #Frame
BlackBorder=Frame(root,width=400,height=300,bg='Black')
BlackBorder.place(x=0,y=80)
TxtFrame=Frame(BlackBorder,width=370,height=270,bg='lavender')
TxtFrame.place(x=15,y=15)
    #Display
Cunter=Text(root,width=24,height=1,bg='lavender',font='Fixedsys')
Cunter.place(x=100,y=22)
Cunter.insert(END, str(len(LoList))+" Résultats Différents")


#defTxt
def LoMsg(self):
    self=Text(TxtFrame,wrap='word',borderwidth=0,width=35,height=10,bg='lavender',font='Fixedsys')
    self.place(x=50,y=100)
    LoTxt=str(LovList[randrange(len(LovList))])
    LoNum=0
    while LoNum!=len(LoTxt):
        self.insert(END,LoTxt[LoNum])
        sleep(0.1)
        LoNum+=1

    #Button
buttonMain=Button(root,width=9,height=3,bg='thistle2',text="Try me",font='Fixedsys')
buttonMain.place(x=5,y=5)
#ButtonEvent
buttonMain.bind('<1>', LoMsg)

Solution

  • The following is an example to highlight the usage of the after(ms, callback) method to get your desired result (adjust the ms in the after method accordingly):

    import tkinter as Tk
    
    def insert():
        global LoNum
        text.insert(Tk.END, word[LoNum])
        LoNum += 1
        if LoNum != len(word):
            root.after(300, insert)
        else:
            return
    
    root = Tk.Tk()
    root.geometry('600x200')
    
    LoNum = 0
    word = [x for x in 'abcdefg'] # get the word to a list format
    text = Tk.Text(root, wrap='word', borderwidth=0, width=35, height=10, bg='lavender')
    text.pack()
    
    Tk.Button(root, text='Try Me', width=9, height=3, bg='thistle2', command=insert).pack()
    
    root.mainloop()