How to center text using “turtle” module in Python

寵の児 提交于 2021-02-10 14:39:58

问题


How can I draw "turtle" text starting from the center of a window? I know how to create "turtle" text, but I don't know how to center the text so it appears from the center of a window.

turtle.write("I AM HERE", font=("Arial", 50, "bold"))

Thanks for your help,

Howard


回答1:


To center text on a point (e.g. the origin at [0, 0]), in the X dimension, you can use the align=center keyword argument to turtle.write(). To get alignment in the Y dimension, you need to adjust slightly for the font size:

from turtle import Turtle, Screen

FONT_SIZE = 50

FONT = ("Arial", FONT_SIZE, "bold")

yertle = Turtle()

# The turtle starts life in the center of the window
# but let's assume we've been drawing other things
# and now need to return to the center of the window

yertle.penup()
yertle.home()

# By default, the text prints too high unless we roughly
# readjust the baseline, you can confirm text placement
# by doing yertle.dot() after yertle.home() to see center

yertle.sety(-FONT_SIZE/2)

yertle.write("I AM HERE", align="center", font=FONT)

yertle.hideturtle()

screen = Screen()

screen.exitonclick()

However if you instead want to start printing from the center (your post isn't clear), you can change align=center to align=left, or just leave out the align keyword argument altogether.




回答2:


turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))

Parameters:

arg – object to be written to the TurtleScreen

move – True/False

align – one of the strings “left”, “center” or right”

font – a triple (fontname, fontsize, fonttype)



来源:https://stackoverflow.com/questions/42265682/how-to-center-text-using-turtle-module-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!