在Python 3.4中在一个窗口中创建多个彩色海龟

0 投票
1 回答
2329 浏览
提问于 2025-04-18 03:11

到目前为止,我做了这个代码,它能画出两个圆圈,但有一个在屏幕外面。我想把它们放在中间,并且让它们之间有一些距离。现在这个代码是做了两个循环,但我想先画一个小圆圈,然后再画一个更大的圆圈,把它放在第一个圆圈的周围,并且要在屏幕的中间。两个圆圈的颜色也要不一样。

def sun_and_earth():   
    import turtle  #allows me to use the turtles library
    turtle.Turtle()
    turtle.Screen()  #creates turtle screen
    turtle.window_height()
    turtle.window_width()
    turtle.bgcolor('grey')  #makes background color
    turtle.color("red", "green")
    turtle.circle(2, 360)  #draws a (size, radius) circle
    turtle.circle(218, 360)
    turtle.exitonclick()  #exits out of turtle window on click of window

1 个回答

0

我觉得你可能对海龟库里的某些函数有些误解。首先,turtle.window_height()turtle.window_width() 这两个函数是用来获取窗口的高度和宽度的,但因为这些值没有被赋值给任何变量,所以这两行代码其实是没有任何作用的。同样,turtle.Screen() 也是返回一个对象,所以这一行也没有做什么。

如果你想让你的圆心居中,你需要通过使用 turtle.setpos() 函数来改变海龟的起始位置。这个函数会改变海龟的 x 和 y 坐标。如果你把海龟的起始位置往下移动一个半径,这样就能把圆心有效地放在 (0, 0) 的位置,因为根据文档,圆心的位置是向左一个半径。

记得在移动的时候把笔抬起来,这样就不会不小心在两个点之间画出线条了;当你想要再次绘图时,再把笔放下。

试试这个代码:

import turtle
turtle.Turtle()
turtle.bgcolor('grey')

# decide what your small circle will look like
smallColour = "red"
smallRadius = 5

# draw the small circle
turtle.color(smallColour)
turtle.penup()
turtle.setpos(0, -smallRadius)
turtle.pendown()
turtle.circle(smallRadius)

# decide what your large circle will look like
largeColour = "white"
largeRadius = 100

# draw the large circle
turtle.color(largeColour)
turtle.penup()
print(turtle.pos())
turtle.setpos(0, -largeRadius)
print(turtle.pos())
turtle.pendown()
turtle.circle(largeRadius)

turtle.penup()
turtle.setpos(0, 0)

希望这些对你有帮助,不过我觉得你对海龟的使用还有一些误解,看看这个 教程 或者查看一下 文档 可能会是个好主意。

祝你好运!

撰写回答