2017-08-05 57 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是字體的大小,和大膽的字體類型。除了粗體之外,您還可以選擇斜體或正常。

相關問題