【问题标题】:How do I set the starting position of my turtle in python to the bottom left of my screen?如何将我的乌龟在 python 中的起始位置设置在屏幕的左下角?
【发布时间】:2019-11-27 14:21:49
【问题描述】:

我正在做一个涉及海龟的项目。而且我一直在尝试找到一种方法让海龟从屏幕的左下方开始,而不是坐标 (0,0)。

#My Code
import turtle
turtle.setworldcoordinates(-1, -1, 20, 20)

turtle.fd(250)
turtle.rt(90)
turtle.fd(250)

当我尝试寻找解决方案时,我遇到了一个线程“Python turtle set start position”,它建议了多种解决问题的方法,例如我的代码中的turtle.setworldcoordinates(-1, -1, 20, 20) 引用。如果有人有想法或解决方案,请告诉我。

【问题讨论】:

  • 'turtle.setworldcoordinates()' 不起作用吗?
  • 乌龟没有从屏幕的最左下角开始。
  • 你在一个长度为 21 的空间中向前移动了 250 个单位。尝试使用turtle.fd(19)
  • 如果它不是从屏幕底部开始的,为什么不直接改变'setworldcoordinates'中的坐标直到得到它?
  • (0, 0) 是坐标。

标签: python python-3.x turtle-graphics


【解决方案1】:
from turtle import Screen, Turtle

screen = Screen()
screen.setworldcoordinates(-1, -1, screen.window_width() - 1, screen.window_height() - 1)

turtle = Turtle('turtle')

# work with your turtle here

screen.exitonclick()

根据系统和角的不同,-1 常量可能需要高达 -10 以说明海龟在显示其整个身体时的中心位置。

您对代码的关注毫无意义:

turtle.fd(250)
turtle.rt(90)
turtle.fd(250)

当乌龟开始向右移动时,左下角的乌龟随后向右转,会将其从屏幕上移开。

【讨论】:

    【解决方案2】:

    如果我们知道你的turtle.Screen的大小会有所帮助

    您可以使用 penup()、goto() 方法。

    import turtle
    
    wn = turtle.Screen()
    wn.setup(width=500, height=500)
    wn.tracer(0)
    wn.bgcolor('black')
    
    bottom_left = turtle.Turtle()
    bottom_left.shape('circle')
    bottom_left.color('white')
    bottom_left.shapesize(stretch_wid=5, stretch_len=5)
    bottom_left.penup()
    bottom_left.goto(-250, -250)
    
    
    while True:
        wn.update()
    

    如您所见,我绘制了一个 500x500 的黑色网格,并根据网格将海龟放置在左下角。

    希望这是您正在寻找的东西,我在游戏中使用了这种方法而不是 turtle.setworldcoordinates() 方法。

    您似乎想使用setworldcoordinates() 我已经编辑了我的答案以包含该方法的解决方案。

    import turtle
    
    wn = turtle.Screen()
    wn.setup(width=500, height=500)
    wn.tracer(0)
    wn.bgcolor('black')
    wn.setworldcoordinates(-1, -1, 20, 20)
    
    bottom_left = turtle.Turtle()
    bottom_left.shape('circle')
    bottom_left.color('white')
    bottom_left.shapesize(stretch_wid=5, stretch_len=5)
    
    
    while True:
        wn.update()
    

    希望这会有所帮助...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 2017-12-19
      • 1970-01-01
      相关资源
      最近更新 更多