【问题标题】:Python turtle user input for shape and colorPython海龟用户输入形状和颜色
【发布时间】:2016-09-03 01:36:28
【问题描述】:

我一直在尝试编写一些代码,以便在有人输入他们希望它在海龟中的颜色和形状后立即获得结果。基本上,我的意思是,当您收到提示输入颜色并说“橙色”时,例如,颜色会立即变为橙色。这是我写的代码:

def 海龟(形状):

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)

定义形状():

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

def 海龟(颜色):

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

定义颜色():

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

它工作得很好。进行一次更改后,假设颜色变为蓝色,然后无论用户提示中输入了什么内容,它都会拒绝执行任何操作。

附:我正在运行 Python 3.5.2

【问题讨论】:

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


    【解决方案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() 删除以前的绘图,然后再用更改制作新绘图。

    【讨论】: