HyperText
HyperText

Reputation: 11

How to make text as a sprite in turtle?

For example I want to do something like this:

textSprite=new object(text("Hello"))
turtle.display(textSprite)

-Then do

time.sleep(10)
textSprite.hide()

-Or

while i<100:
    time.sleep(10)
    textsprite.size=i

-Or

textSprite.x=10
textSprite.y=100
time.sleep(100)
textSprite.x=20
textSprite.y=200

I tried searching google but I got no answers.


update: some question changes have been made

Upvotes: 1

Views: 95

Answers (1)

cdlane
cdlane

Reputation: 41872

Since Python is generally object-oriented, and turtle specifically is, you can create your own TextSprite class using turtle as underpinning:

from turtle import Turtle

class TextSprite(Turtle):
    DEFUALT_FONT = ('Arial', 18, 'normal')

    def __init__(self, text):
        super().__init__(visible=False)

        self.text = text
        self.font = self.DEFUALT_FONT

        self.penup()

    def setfont(self, font):
        self.font = font

    def showtext(self):
        self.write(self.text, align='center', font=self.font)

    def hidetext(self):
        self.clear()

if __name__ == "__main__":
    from turtle import Screen

    screen = Screen()

    sprite = TextSprite("Hello")

    sprite.goto(100, 100)
    sprite.color('blue')
    sprite.setfont(('Times Roman', 24, 'bold'))

    sprite.showtext()

    screen.ontimer(sprite.hidetext, 10_000)  # ten seconds

    screen.exitonclick()

Upvotes: 1

Related Questions