你能在Python turtle中清除特定的字母吗

huangapple go评论130阅读模式
英文:

Can I clear a specific letter in Python turtle

问题

我正在使用Python turtle来在屏幕上绘制字母,我希望能够清除特定的字母。

我知道我可以使用.clear(),但那会清除所有使用.write()函数写入的字母。我的代码中似乎一切正常,我能够发送要更改的值(字母),但我不知道如何删除它。我知道我也可以用不同的颜色重写字母,但这对我的方案不起作用,而且会显著减慢代码(我以前尝试过)。我是否需要为屏幕上的字母数量使用多个turtle?

英文:

I am using Python turtle to draw letters across a screen, and I want to be able to clear specific ones.

I know that I can use .clear(), but that will clear all of the letters that has been written with the .write() function. Everything in my code seems to be working, and I am able to send the value (letter) that I want to change, but I don't know how I would delete it. I know that I can also write over the letter with a different color, but that wouldn't work with my scheme, and it also slows down the code a lot (I have done it before). Would I have to use multiple turtles for the number of letters on the screen?

答案1

得分: 0

排除逐字母乌龟选项,脑海中浮现的下一个想法是使用等宽字体,并在关闭tracer()(即显式更新)的情况下重写字符串:

from turtle import Screen, Turtle

FONT = ('Courier', 24, 'normal')

PHRASE = "The quick brown fox jumps over the lazy dog"

VOWELS = {'a', 'e', 'i', 'o', 'u'}

def write(x=None, y=None):
    turtle.clear()
    turtle.write(PHRASE, align='center', font=FONT)
    screen.update()
    screen.onclick(rewrite)

def rewrite(x=None, y=None):
    consonants = ''.join(' ' if letter in VOWELS else letter for letter in PHRASE)
    turtle.clear()
    turtle.write(consonants, align='center', font=FONT)
    screen.update()
    screen.onclick(write)

screen = Screen()
screen.tracer(False)

turtle = Turtle()
turtle.hideturtle()

write()

screen.mainloop()

在屏幕上单击,所有元音字母将消失并重新出现。

英文:

Ruling out the turtle per letter option, the next thing that comes to mind is using a fixed width font and rewriting the string with tracer() turned off (i.e. explicit updates):

from turtle import Screen, Turtle

FONT = ('Courier', 24, 'normal')

PHRASE = "The quick brown fox jumps over the lazy dog"

VOWELS = {'a', 'e', 'i', 'o', 'u'}

def write(x=None, y=None):
	turtle.clear()
	turtle.write(PHRASE, align='center', font=FONT)
	screen.update()
	screen.onclick(rewrite)

def rewrite(x=None, y=None):
	consonants = ''.join(' ' if letter in VOWELS else letter for letter in PHRASE)
	turtle.clear()
	turtle.write(consonants, align='center', font=FONT)
	screen.update()
	screen.onclick(write)

screen = Screen()
screen.tracer(False)

turtle = Turtle()
turtle.hideturtle()

write()

screen.mainloop()

Click on the screen and all the vowels will disappear and reappear.

huangapple
  • 本文由 发表于 2023年3月7日 04:31:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定