我用 textsize 编写文本时遇到零问题,但我不明白我用 textbbox 做错了什么。我收到错误:
File "c:\Users\email\OneDrive\Personal\Documents\Code\Python\TestPatternGenerator\test.py", line 14, in textwidth, textheight = draw.textbbox("text", font=font) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: ImageDraw.textbbox() missing 1 required positional argument: 'text'
from PIL import Image, ImageDraw, ImageFont
# Create an image object
img = Image.new("RGB", (400, 400), (255, 255, 255))
# Create a draw object
draw = ImageDraw.Draw(img)
# Define the font to be used for the text
font = ImageFont.truetype("arial.ttf", 36)
# Get the text bounding box
text = "Hello World!"
textwidth, textheight = draw.textbbox(text, font=font)
# Calculate the position for the text
x = (img.width - textwidth) / 2
y = (img.height - textheight) / 2
# Draw the text on the image
draw.text((x, y), text, (0, 0, 0), font=font)
# Save the image
img.save("hello_world.png")
最佳答案
错误消息表明您在此行中缺少参数:
textwidth, textheight = draw.textbbox(text, font=font)
如果您查找 documentation for textbbox ,您会看到第一个参数应该是 xy,即文本的 anchor 坐标。您的代码行中缺少此内容。
解决方案:您应该首先计算位置,然后在调用 bbox
时使用该位置。或者,在您的情况下,您只想知道代码该点处的边界框的大小,因此您可以使用 (0, 0)
作为位置。
关于python - 由于 textsize 弃用,尝试使用 Python PIL ImageDraw.textbbox 但出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75344148/