【问题标题】:Drawing Lines and Limiting Them by Screen Size in Python Turtle Graphics在 Python Turtle Graphics 中绘制线条并通过屏幕大小限制它们
【发布时间】:2016-04-01 02:35:20
【问题描述】:

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

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 之间的长度时,它会超出窗口大小。此外,当它完成第一条线的绘制并旋转 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)

【问题讨论】:

  • 只显示你拥有的整个代码,不能那么多。请注意,您也可以将屏幕截图放入您的问题中。
  • 这是完整代码的图像。 imgur.com/IZctg2i
  • 我知道这听起来可能令人沮丧,但不要将代码发布为图像,只需像上面的代码 sn-ps 一样输入即可。这样人们就可以复制它并尝试快速复制您的问题。
  • 好的,没问题。我已将其添加到原始问题中。

标签: python turtle-graphics


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多