tkin中的打字机效应

2024-10-06 07:55:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用tkinter在python中创建一个文本冒险,因为它很容易使用图形(按钮等)

我想添加一个效果,使文本看起来像是被打印出来的。在

def displayNextPart():
    for i in buttons:
        i.destroy()
    global curPart
    for char in story[curPart]["Text"]:
        slp(.05)
        w.config(text=char)
        sys.stdout.flush()

但窗口在完成前都会冻结,留给我的只有字符串的最后一个字符。在

有人能帮我吗?在


Tags: in文本图形fortkinterdef按钮global
2条回答

你需要更新循环屏幕。最简单的方法是使用tkinter的after方法编写一个自重复函数。在

这是一个有效的例子。这使用一个文本小部件,但是您可以很容易地更新标签小部件或画布文本项。在

import Tkinter as tk

def typeit(widget, index, string):
   if len(string) > 0:
      widget.insert(index, string[0])
      if len(string) > 1:
         # compute index of next char
         index = widget.index("%s + 1 char" % index)

         # type the next character in half a second
         widget.after(250, typeit, widget, index, string[1:])

root = tk.Tk()
text = tk.Text(root, width=40, height=4)
text.pack(fill="both", expand=True)
typeit(text, "1.0", "Hello, this is an \nexample of some text!")

root.mainloop()

time.sleep()无法与Tkinter应用程序一起正常工作。使用after()方法,如下例所示:

import tkinter as tk

root = tk.Tk()

word = 'hello'

def go(counter=1):
    l.config(text=word[:counter])
    root.after(150, lambda: go(counter+1))

b = tk.Button(root, text='go', command=go)
l = tk.Label(root)
b.pack()
l.pack()

root.mainloop()

相关问题 更多 >