簡體   English   中英

Python烏龜用戶輸入的形狀和顏色

[英]Python turtle user input for shape and color

我一直在嘗試編寫一些代碼,以便在有人輸入所需的顏色和形狀后,立即獲得結果。 基本上,我的意思是,例如,當系統提示您輸入顏色並說“橙色”時,該顏色將立即變為橙色。 這是我編寫的代碼:

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)

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)

它稍微起作用。 進行一次更改后,說顏色變成藍色,然后它將拒絕執行任何操作,無論用戶提示中輸入了什么。

PS我正在運行Python 3.5.2

問題是您確實需要使用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()刪除以前的圖形,然后再進行更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM