【问题标题】:Make write() work like print() in Python turtle graphics?在 Python 海龟图形中让 write() 像 print() 一样工作?
【发布时间】:2016-05-29 20:05:15
【问题描述】:

如何修复我的 Python 代码以在海龟图形窗口中工作?下面,我有我的 Python 代码。代码本身在执行时会显示一个乘法图表。我需要这个在 Turtle Graphics 中工作。我尝试将 print() 更改为 turtle.write() 并导入海龟。我不知道我还需要做什么。请帮忙。

import turtle

turtle.write("      Multiplication Table")


# Display numbers
turtle.write("   ", end = '')
for j in range(1, 10):
    turtle.write(" ", j, end = '')

turtle.write() 
turtle.write("--------------------------------")

# Display body of table
for i in range(1, 10):
    turtle.write(i, "|", end = '')
    for j in range(1, 10): 
        # Display the product and align properly
        turtle.write(format(i * j, '3d'), end = '')
    turtle.write()

【问题讨论】:

  • 您为什么期望turtle.writeprint 的工作方式完全相同?它做了一些相当不同的事情(在海龟的位置写入文本,而不是向控制台写入一行输出)。如果您要多次访问write,则需要移动乌龟以将不同的部分放在正确的位置。

标签: python turtle-graphics


【解决方案1】:

当使用turtle.write() 代替print() 时,它能够与我们相见。在水平方向上,write() 将跟踪我们的位置,如print(),如果我们指定move=True 选项。我们需要自己处理垂直方向,使用当前字体大小移动正确的量:

from turtle import Turtle, Screen

FONT_SIZE = 18
FONT = ('Courier', FONT_SIZE, 'normal')

# Based on number of characters to draw, field width, font aspect ratio, etc.
TABLE_EDGE_ESTIMATE = - ((0.6 * FONT_SIZE) * (11 * 3)) / 2

screen = Screen()
HEIGHT = screen.window_height()/2

turtle = Turtle(visible=False)
turtle.penup()

turtle.goto(0, HEIGHT * 0.9)
turtle.write("Multiplication Table", align="center", font=FONT)

# Display numbers along top
turtle.goto(TABLE_EDGE_ESTIMATE, turtle.ycor() - 2 * FONT_SIZE)
turtle.write("   " * 2, move=True, font=FONT)
for j in range(1, 10):
    turtle.write(format(j, "^3"), move=True, font=FONT)

turtle.goto(TABLE_EDGE_ESTIMATE, turtle.ycor() - FONT_SIZE)
turtle.write("---" * 11, font=FONT)

# Display body of table
turtle.sety(turtle.ycor() - FONT_SIZE)

for i in range(1, 10):
    turtle.setx(TABLE_EDGE_ESTIMATE)
    turtle.write(format(i, "^3"), move=True, font=FONT)
    turtle.write(" | ", move=True, font=FONT)

    for j in range(1, 10):
        # Display the product and align properly
        turtle.write(format(i * j, "^3"), move=True, font=FONT)

    turtle.sety(turtle.ycor() - FONT_SIZE)

screen.mainloop()

【讨论】:

    猜你喜欢
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2020-05-11
    • 1970-01-01
    • 2018-03-19
    相关资源
    最近更新 更多