用于形状和颜色的Python龟用户输入

时间:2016-09-03 01:36:29

标签: python-3.x turtle-graphics

我曾经尝试编写一些代码,以便在有人输入他们希望它在乌龟中的颜色和形状后立即获得结果。基本上,我的意思是,当你收到提示颜色并且你说" orange"时,那么颜色会立即变为橙色。这是我写过的代码:

def Turtle(形状):

if shape == "triangle":
    turtle.circle(40, steps=3)
elif shape == "square":
    turtle.circle(40, steps=4)
elif shape == "pentagon":
    turtle.circle(40, steps=5)
elif shape == "hexagon":
    turtle.circle(40, steps=6)

def Shape():

shape = eval(input("Enter a shape: "))
Turtle(shape)

def Turtle(颜色):

if color == "red":
    turtle.color("red")
elif color == "blue":
    turtle.color("blue")
elif color == "green":
    turtle.color("green")
elif color == "yellow":
    turtle.color("yellow")

def Color():

color = eval(input("Enter a color: "))
Turtle(color)

略有效果。进行一次更改后,说颜色变为蓝色,然后在此之后拒绝执行任何操作,无论用户提示中输入的内容如何。

P.S。我正在运行Python 3.5.2

1 个答案:

答案 0 :(得分:1)

问题是你真的需要使用mainloop()将控制权转交给海龟监听器,然后你就不能再通过顶层函数调用与它进行通信了:

color = input("Enter a color: ")

但是,由于您使用的是Python 3,我们可以使用新的输入对话框功能动态提示输入并更改当前图形:

import turtle

current_shape = "triangle"

steps = {"triangle": 3, "square": 4, "pentagon": 5, "hexagon": 6}

def onkey_shape():
    shape = turtle.textinput("Shape Selection", "Enter a shape:")
    if shape.lower() in steps:
        turtle.reset()
        set_color(current_color)
        set_shape(shape.lower())
    turtle.listen()  # grab focus back from dialog window

def set_shape(shape):
    global current_shape
    turtle.circle(40, None, steps[shape])
    current_shape = shape

current_color = "red"

colors = {"red", "blue", "green", "yellow", "orange"}

def onkey_color():
    color = turtle.textinput("Color Selection", "Enter a color:")
    if color.lower() in colors:
        turtle.reset()
        set_color(color.lower())
        set_shape(current_shape)
    turtle.listen()  # grab focus back from dialog window

def set_color(color):
    global current_color
    turtle.color(color)
    current_color = color

set_color(current_color)
set_shape(current_shape)

turtle.onkey(onkey_color, "c")
turtle.onkey(onkey_shape, "s")

turtle.listen()

turtle.mainloop()

让乌龟窗口处于活动状态(选择它,又名让它集中注意力),然后按下“C'您将获得一个新颜色的对话框(来自固定的设置),如果您按下' S'你会得到一个新形状的对话框。代码使用reset()删除上一个绘图,然后再创建一个带有更改的新绘图。