获取Python龟窗口以显示图形并保持打开状态

时间:2018-01-13 02:49:11

标签: python turtle-graphics

在这段代码中,我看不出为什么它不是24次打印六边形。我告诉它制作一个六边形的线条之间有60度(六边形)并告诉它每次都转15度。对于我想要绘制的图片,这最终会变成24分。

import turtle

Hex_Count = 0

x = turtle.Turtle()
x.speed(.25)
def Hexagon():
    for i in range(24):
        for i in range(6):
            x.forward(100)
            x.left(60)
        Hex_Count = Hex_Count + 1
        x.left(15)
        print(Hex_Count)
Hexagon

但是,出于某种原因,当我运行此代码时,乌龟屏幕弹出大约半秒然后关闭。如何让它以我想要的方式运行?

4 个答案:

答案 0 :(得分:1)

您的程序存在多个问题。一个是在运行程序之后关闭它创建的窗口。您可以在脚本的末尾添加turtle.exitonclick(),告诉python等待图形窗口中的单击,之后它将退出。

第二个问题是你没有调用Hexagon函数,因为你错过了括号。即使一个函数没有参数,你仍然需要调用它:

Hexagon()

最后一个问题是,在尝试增加Hex_Count之前,需要先定义它。如果尚未分配Hex_Count + 1,则Hex_Count会抛出错误。您可以通过添加

来解决此问题
Hex_Count = 0
Hexagon中的for循环之前

答案 1 :(得分:1)

你有一些参考问题,你只需要将变量hex_count放在需要它的位置,这样就不会有错误访问它。

import turtle

x = turtle.Turtle()
x.speed(.25)
def Hexagon():
    Hex_Count = 0
    for i in range(24):
        for i in range(6):
            x.forward(100)
            x.left(60)
        Hex_Count += 1
        x.left(15)
    print(Hex_Count)
Hexagon()

打印24

答案 2 :(得分:1)

我为您纠正了几个错误;我在评论中添加了解释:

import turtle

hexagons_count = 0

my_turtle = turtle.Turtle()       # x is not a good name for a Turtle object
# my_turtle.speed(.25)            # see @cdlane comment reported in a note under.

def draw_hexagon():               # use explicit names respecting python conventions (no camel case)
    global hexagons_count         # need global to modify the variable in the function scope
    for idx in range(24):         # use different dummy variable names in your loops 
        for jdx in range(6):      # use different dummy variable names in your loops
            my_turtle.forward(100)
            my_turtle.left(60)
        hexagons_count += 1
        my_turtle.left(15)
        print(hexagons_count)

draw_hexagon()             # need parenthesis to call the function

turtle.exitonclick()       # this to exit cleanly

enter image description here

  

注意:我知道你只是从OP复制了它,但my_turtle.speed(.25)   没有意义,因为参数应该是从0到10或a的int   像'慢','最快'等字符串我特别不明白为什么   没有工作的乌龟代码的初学者调用turtle.speed()   所有 - 在我看来,一切都是在一切之后进行调整的功能   工作。 @cdlane

答案 3 :(得分:0)

一种方法在许多细节上有所不同,但主要是使用circle()来更快速地绘制六边形:

from turtle import Turtle, Screen  # force object-oriented turtle

hex_count = 0  # global to count all hexagons drawn by all routines

def hexagons(turtle):
    global hex_count  # needed as this function *changes* hex_count

    for _ in range(24):  # don't need explicit iteration variable
        turtle.circle(100, steps=6)  # use circle() to draw hexagons
        turtle.left(15)  # 24 hexagons offset by 15 degrees = 360
        hex_count += 1  # increment global hexagon count
        print(hex_count)

screen = Screen()

yertle = Turtle(visible=False)  # keep turtle out of the drawing
yertle.speed('fastest')  # ask turtle to draw as fast as it can

hexagons(yertle)

screen.exitonclick()  # allow dismiss of window by clicking on it