Home > front end >  typewriter effect tkinter python
typewriter effect tkinter python

Time:04-01

so i want to make a game and i want to have the title be in a typewriter effect i know the code of the typewriter effect just dont know how to implement it. pitanje_menu is the label

ab=StringVar()
a=Label(textvariable=ab)
a.pack()
l=[]
for i in words:
    l.append(i)
    sleep(0.2)
    b=str(l)
    b=b.replace("[","")
    b=b.replace("]","")
    b=b.replace(", ","")
    b=b.replace(",","")
    b=b.replace("'","")
    b=b.replace("  ","")
    c=len(b)
    ab.set(f"{b[0:c-1]}{i}")
    a.update()


pitanje_menu = Label(win, text="the game", bg="black", fg="white", font= ('Open Sans', 100))
pitanje_menu.place(x= "770", y= "240", anchor=CENTER)
da_play = Button(win, text="play", bg="black", fg="white", font= ('Open Sans', 60), borderwidth=0, command=play)
da_play.place(x= "770", y= "490", anchor=CENTER)

CodePudding user response:

tkinter, like all GUI frameworks, is event-driven. When you create those labels or take any action, NOTHING gets done immediately. All that does is send messages. The messages will sit in the message queue until you get to mainloop. The main loop dispatches and processes all of those messages, which causes action to be taken.

So, at the time you're running your loop, there is nothing on the screen. All you are doing is delayed the time until the main window is set up.

So, what you need to do is use win.after to request a callback every 0.2 seconds. In that callback, you will add the next character, and request another callback. You do one at a time. I would create a global list that contained the letters to be displayed. Each call consumes one letter until the list is empty.

to_be_drawn = []

def callback():
    if not to_be_drawn:
        return
    nxt = to_be_drawn.pop(0)
    ab.set( ab.get()   nxt )
    win.after( 200, callback )

def start_typing(text):
    was_empty = not to_be_drawn
    text = text.replace('[','').replace(']','').replace(',','')
    to_be_drawn.extend( list(text) )
    if was_empty:
        win.after( 200, callback )

start_typing( "Hello, kitty!" )
  • Related