首页 > 解决方案 > 如何在 Python 中的框前显示文本?

问题描述

我创建了一个框和一个文本,我希望文本显示在框的前面。但是当我尝试这样做时,我看不到它,因为它在盒子后面。

import turtle

wn= turtle.Screen()

style = ("Courier", "36", "bold")

#Box -------------------------- ([Text] Box)

b1 = turtle.Turtle()
b1.color("black")
b1.shape("square")
b1.speed(0)
b1.shapesize(stretch_wid=5, stretch_len=10)
b1.penup()
b1.goto(-400, -150)



#Text ------------------------ "[Text]"

t1= turtle.Turtle()
t1.speed(0)
t1.color("white")
t1.ht()
t1.penup()
t1.goto(-400, -150)
t1.write("[Text]", font=style, align = "center")

#Main loop

while True:

    wn.update()

我检查了代码的顺序是否错误,但没有发现任何错误。我也试过删除t1.ht(),但这不是问题。我如何解决它?

标签: pythonpython-turtle

解决方案


下面是一种混合了您尝试做的和@furas 推荐的方法。它使用冲压而不是绘图来简化问题:

from turtle import Screen, Turtle

FONT_SIZE = 36
FONT = ('Courier', FONT_SIZE, 'bold')

screen = Screen()

textbox = Turtle()
textbox.hideturtle()
textbox.color('black')
textbox.shape('square')
textbox.shapesize(stretch_wid=5, stretch_len=10)
textbox.penup()
textbox.goto(-300, -150)
textbox.stamp()
textbox.color('white')
textbox.goto(-300, -150 - FONT_SIZE/2)  # center vertically based on font size
textbox.write("[Text]", align='center', font=FONT)

screen.mainloop()

textbox乌龟也可以重复使用和重塑以绘制其他文本框。通过一些思考和猜测,您可以根据字体大小和文本本身计算出合理的文本框大小。

在此处输入图像描述


推荐阅读