如何修复我的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()
答案 0 :(得分:0)
使用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()