GraphWin 中的打字效果

Posted

技术标签:

【中文标题】GraphWin 中的打字效果【英文标题】:Typing effect in GraphWin 【发布时间】:2018-03-14 04:08:06 【问题描述】:

我正在尝试在窗口中创建文本输入效果,但它显示为 “TypeError:'Text' 对象不可迭代”。这是我当前的代码:

from graphics import *
import sys
from time import sleep

window = GraphWin('Test', 1000, 700)

text = Text(Point(500, 150), "This is just a test :P")
words = ("This is just a test :P")
for char in text:
    sleep(0.1)
    sys.stdout.write(char)
    sys.stdout.flush()
word.draw(window)

Source for typing effect

如果我使用 'words' 变量,文本会出现在 shell 中,但是如果我尝试使用 text 变量,则会变成 TypeError。有没有办法让它可迭代?

【问题讨论】:

【参考方案1】:

首先,您混淆了变量textwords;其次,你的Text 对象是不可迭代的,但是你可以创建几个在迭代`words'时连续显示的对象

from graphics import *
import sys
from time import sleep

window = GraphWin('Test', 1000, 700)

text = Text(Point(500, 150), "This is just a test :P")
words = "This is just a test :P"

# this prints to console
for char in words:
    sleep(0.1)
    sys.stdout.write(char)
    sys.stdout.flush()

# that displays on canvas
for idx, t in enumerate(words):
    text = Text(Point(300+idx*20, 150), t)
    text.draw(window)
    sleep(0.1)

python 3 中,您可以将对 sys.stdout 的调用替换为标准的 print 调用:

# this prints to console
for char in words:
    sleep(0.1)
    print(char, end='', flush=True)

【讨论】:

以上是关于GraphWin 中的打字效果的主要内容,如果未能解决你的问题,请参考以下文章

如何实现文字逐个出现的打字机效果

discord.py 中的打字机效果(我用谷歌翻译问这个问题,如有错误请见谅)

从打字机效果的 N 种实现看JS定时器机制和前端动画

CSS打字效果

Android仿打字机打字效果

实战用CSS实现文本打字机效果