在 Python Turtle Graphics 中绘制线条并按屏幕尺寸限制它们

Drawing Lines and Limiting Them by Screen Size in Python Turtle Graphics

我需要为我的方形螺旋绘图程序添加对超出屏幕尺寸的初始长度的正确处理,但是,我不确定屏幕尺寸的长度是多少。我假设因为 Turtle 图形插画器从屏幕中间开始,所以它在程序的中间 window。在这种情况下,下面的代码应该可以工作我只需要知道屏幕尺寸的长度。

while startLength >(screen size here):
    startLength=float(input("please enter a value greater than zero: "))

此外,这需要在所有平台上通用,假设没有像 wx 这样的跨平台。

我试过:

 while startLength >(turtle.forward(turtle.window_width()/2):
        startLength=float(input("please enter a value greater than zero: "))

然而,当我输入 300-350 之间的长度时,它超过了 window 大小。此外,当它完成绘制第一条线并旋转 90 度以绘制下一条螺旋线(向下)时,它也会超出屏幕的大小。

我正在使用 import turtle

这是我程序的完整代码。

from turtle import *
import turtle
startLength = float(input("Please enter the length of first side: "))
while startLength < 0:
    startLength=float(input("please enter a value greater than zero: "))
while startLength > (turtle.window_width()/2):
    startLength=float(input("please enter a value that will fit in the window: "))
decrement = int(input("Please enter the change in length of side: "))
while startLength > decrement:
    forward(startLength)
    right(90)
    startLength = startLength - decrement   
forward(startLength)
right(90)

理想情况下,将起点从中心移到左上角,但这里是如何从中心开始的。 与您的代码唯一真正的区别只是我要求起始长度,然后只继续询问(while 循环)是否太长。忽略我正在使用 raw_input,它用于 Python 2.x,同样适用于打印语句 w/o 括号。

import turtle  

bob = turtle.Turtle()
xx,yy= turtle.window_width(), turtle.window_height() 
print 'window size: ',xx,yy
bob.speed(15)

stl=int(raw_input("Please enter length of first side: "))   

while stl>turtle.window_width()/2:
    stl=int(raw_input("Please enter a shorter length that will fit into the window: "))

dec=int(raw_input("Please enter the change in length per iteration: "))   


while stl > dec:
    bob.forward(stl)
    bob.right(90)
    stl= stl- dec

turtle.done()

文本输出:

window size:  1280 1080
Please enter length of first side: 4000
Please enter a shorter length that will fit into the window: 3000
Please enter a shorter length that will fit into the window: 2000
Please enter a shorter length that will fit into the window: 1000
Please enter a shorter length that will fit into the window: 500
Please enter the change in length per iteration: 2

此外,您可以检查高度,如果 window 可以比宽度更高。