代码之家  ›  专栏  ›  技术社区  ›  grozan programer

打字机效果tkinter python

  •  0
  • grozan programer  · 技术社区  · 2 年前

    所以我想做一个游戏,我想让标题变成打字机效果,我知道打字机效果的代码,只是不知道如何实现它。 pitanje_菜单就是标签

    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)
    
    1 回复  |  直到 2 年前
        1
  •  2
  •   Tim Roberts    2 年前

    tkinter 与所有GUI框架一样,是事件驱动的。当你创建这些标签或采取任何行动时,都不会立即采取任何行动。所做的就是发送消息。这些消息将一直排在消息队列中,直到您到达 mainloop .主循环调度并处理所有这些消息,从而采取行动。

    所以,在运行循环时,屏幕上什么都没有。你所做的只是将时间延迟到主窗口设置完毕。

    所以,你需要做的是使用 win.after 每0.2秒请求一次回调。在该回调中,您将添加下一个字符,并请求另一个回调。你一次做一个。我会创建一个包含要显示的字母的全局列表。每次通话消耗一个字母,直到列表为空。

    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!" )