我想创建一个动画,使文本出现在旧的单色终端(如屏幕)上,就像有人在键入文本一样。但是,在GUI窗口打开后,我经常遇到尝试运行代码的问题。当窗口打开或根本不显示时,文本始终已经存在。任何帮助都非常感激:)
string = "Hello World this is a Test String"
import random
import time
import tkinter as tk
from tkinter import *
vid = tk.Tk()
vid.title('Terminal')
text = Text( vid, width = 100, height = 50, highlightthickness=1, bg='black', highlightbackground="black", font=('Courier', 14), fg='green')
text.pack()
def main():
for i in string:
text.insert(END, i)
time.sleep(0.2)
text.after(10, main)
vid.mainloop()
这是我到目前为止想出的:/
答案 0 :(得分:1)
您需要在睡后使用update_idletasks()
。以下内容对我有用,请问您还有其他问题吗?
string = "Hello World this is a Test String"
import random
import time
import tkinter as tk
from tkinter import *
vid = tk.Tk()
vid.title('Terminal')
text = Text( vid, width = 100, height = 50, highlightthickness=1, bg='black', highlightbackground="black", font=('Courier', 14), fg='green')
text.pack()
def main():
for i in string:
text.insert(END, i)
time.sleep(0.2)
vid.update_idletasks()
vid.after(10, main)
vid.mainloop()
答案 1 :(得分:1)
对于事件驱动程序,通常不建议使用sleep
(tkinter
是事件驱动的,因为大多数GUI库都是这种情况)。在这里,最好将动画基于after
方法:
import random
import tkinter as tk
string = "Hello World this is a Test String"
def animate(n=0):
text.insert(tk.END, string[n])
n += 1
if n == len(string): # reached end of string
text.insert(tk.END, '\n') # insert newline
n = 0 # and reset current char index
text.after(200, lambda:animate(n)) # call function again in 200ms
vid = tk.Tk()
vid.title('Terminal')
text = tk.Text(vid, width=100, height=50, highlightthickness=1, bg='black',
highlightbackground="black", font=('Courier', 14), fg='green')
text.pack()
vid.after(10, animate)
vid.mainloop()
注意::我已经稍微改变了您的动画,以创建一个无限循环,在该循环中逐个字符地不停地打印字符串,并在到达末尾时插入新行。只是为了好玩...