標題,當我執行下面的代碼如何知道python中龜圖形上特定文本的像素大小?
import turtle
turtle.write("some text")
我想知道整個尺寸(包括高度和寬度)烏龜圖形的畫布上的串some text
的。
我該怎麼做?
標題,當我執行下面的代碼如何知道python中龜圖形上特定文本的像素大小?
import turtle
turtle.write("some text")
我想知道整個尺寸(包括高度和寬度)烏龜圖形的畫布上的串some text
的。
我該怎麼做?
字體大小隻告訴你一半你需要知道的,即高度:
字體的大小一般取爲距離的頂部 最高字符到最低字符的底部。
但是,我們可以通過的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()
現在,這裏的第一個繪製箱,加油吧,再畫一個困難的問題把文字放進去。所使用的技巧是繪製文本關閉屏幕:
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()
另一種方法是繪製文本在背景色的地方首先,衡量它,繪製和填充的框,最後用不同的顏色重新繪製文本。
哇,你所做的是我的最終目標。非常感謝你。我想用烏龜圖形來排列像乳膠這樣的文字。 – LessonWang
turtle.write
的缺省字體是'Arial',字體大小爲8px,如文檔https://docs.python.org/3/library/turtle.html#turtle.write中所述。
文本的高度和寬度取決於參數font
。
這樣我就可以通過'len(string)* 8'來估計寬度了嗎? – LessonWang
https://stackoverflow.com/questions/2922295/calculating-the-pixel-size-of-a-string-with-python – LessonWang
我發現了一個關於tkinter的類似解決方案,但沒有解決龜圖形的問題... – LessonWang
雖然布蘭登幾乎放棄了答案,讓我給你舉個例子:
>>>>import turtle
>>>>turtle.write('hey hello this is DSP',font=('consolas',8,'bold'))
這將做你的工作,索拉是字體類型,8是字體的大小,和大膽的字體類型。除了粗體之外,您還可以選擇斜體或正常。
我不認爲這是可能的。 'turtle'是一個玩具模塊,功能非常有限。 – DyZ