2017-08-05 62 views

回答

1

字体大小只告诉你一半你需要知道的,即高度

字体的大小一般取为距离的顶部 最高字符到最低字符的底部。

FontSize.html

但是,我们可以通过的turtle.write()move=选项设置为True得到宽度。这里有一个例子,我想提请文本周围的紧密箱我刚刚得出:

from turtle import Turtle, Screen 

TEXT = "Penny for your thoughts" # arbitrary text 
POSITION = (150, 150) # arbitrary position 

FONT_SIZE = 36 # arbitrary font size 
FONT = ('Arial', FONT_SIZE, 'normal') 

X, Y = 0, 1 

def box(turtle, lower_left, upper_right): 
    """ Draw a box but clean up after ourselves """ 

    position = turtle.position() 
    isdown = turtle.isdown() 

    if isdown: 
     turtle.penup() 
    turtle.goto(lower_left) 
    turtle.pendown() 
    turtle.goto(upper_right[X], lower_left[Y]) 
    turtle.goto(upper_right) 
    turtle.goto(lower_left[X], upper_right[Y]) 
    turtle.goto(lower_left) 

    turtle.penup() 
    turtle.setposition(position) 
    if isdown: 
     turtle.pendown() 

screen = Screen() 

marker = Turtle(visible=False) 
marker.penup() 
marker.goto(POSITION) 

start = marker.position() 
marker.write(TEXT, align='center', move=True, font=FONT) 
end = marker.position() 

# Since it's centered, the end[X] - start[X] represents 1/2 the width 
box(marker, (2 * start[X] - end[X], start[Y]), (end[X], start[Y] + FONT_SIZE)) 

screen.exitonclick() 

enter image description here

现在,这里的第一个绘制箱,加油吧,再画一个困难的问题把文字放进去。所使用的技巧是绘制文本关闭屏幕:

from turtle import Turtle, Screen 

TEXT = "Penny for your thoughts" # arbitrary text 
POSITION = (150, 150) # arbitrary position 

FONT_SIZE = 36 # arbitrary font size 
FONT = ('Arial', FONT_SIZE, 'normal') 

X, Y = 0, 1 

def box(turtle, lower_left, upper_right): 
    """ same as above example """ 

screen = Screen() 

marker = Turtle(visible=False) 
marker.penup() 
marker.speed('fastest') 
marker.fillcolor('pink') 
marker.setx(screen.window_width() + 1000) 

start = marker.position() 
marker.write(TEXT, align='center', move=True, font=FONT) 
end = marker.position() 
marker.undo() # clean up after ourselves 

marker.speed('normal') 
marker.goto(POSITION) 

# Since it's centered, the end[X] represents 1/2 the width 
half_width = end[X] - start[X] 
marker.begin_fill() 
box(marker, (POSITION[X] - half_width, POSITION[Y]), (POSITION[X] + half_width, POSITION[Y] + FONT_SIZE)) 
marker.end_fill() 

marker.write(TEXT, align='center', font=FONT) 

screen.exitonclick() 

enter image description here

另一种方法是绘制文本在背景色的地方首先,衡量它,绘制和填充的框,最后用不同的颜色重新绘制文本。

+0

哇,你所做的是我的最终目标。非常感谢你。我想用乌龟图形来排列像乳胶这样的文字。 – LessonWang

-1

turtle.write的缺省字体是'Arial',字体大小为8px,如文档https://docs.python.org/3/library/turtle.html#turtle.write中所述。

文本的高度和宽度取决于参数font

+0

这样我就可以通过'len(string)* 8'来估计宽度了吗? – LessonWang

+0

https://stackoverflow.com/questions/2922295/calculating-the-pixel-size-of-a-string-with-python – LessonWang

+0

我发现了一个关于tkinter的类似解决方案,但没有解决龟图形的问题... – LessonWang

-1

虽然布兰登几乎放弃了答案,让我给你举个例子:

>>>>import turtle 
>>>>turtle.write('hey hello this is DSP',font=('consolas',8,'bold')) 

这将做你的工作,索拉是字体类型,8是字体的大小,和大胆的字体类型。除了粗体之外,您还可以选择斜体或正常。

相关问题