如何为用户创建输入语句以在python turtle中定义颜色

问题描述 投票:0回答:2

我正在研究python turtle以便习惯并且想要创建一个输入语句,要求用户选择笔颜色,然后根据用户的选择执行乌龟。需要将其写为字符串

python python-3.x turtle-graphics
2个回答
0
投票

试试这个:

PenColor_choice = input("Enter the pen color, please!")
if PenColor_choice == something :
    do_something()

0
投票

既然你标记了你的问题[python-3.x],而不是在控制台窗口中提示颜色,我建议你使用turtle自己的文本输入小部件,Python 3中的新功能:

>>> help(turtle.textinput)
Help on function textinput in module turtle:

textinput(title, prompt)
    Pop up a dialog window for input of a string.

    Arguments: title is the title of the dialog window,
    prompt is a text mostly describing what information to input.

    Return the string input
    If the dialog is canceled, return None.

    Example:
    >>> textinput("NIM", "Name of first player:")

>>> 

这是一个做到这一点的例子。如果用户输入一些它不知道的颜色,如“山羊草”,它会在循环中使用try ... except再次询问颜色。一旦他们选择了有效的颜色,而不是初始默认的“黑色”,它会继续用这种新颜色绘制一个圆圈:

import turtle

while turtle.pencolor() == 'black':
    try:
        color = turtle.textinput("Color", "Enter the pen color:")

        turtle.pencolor(color)
    except turtle.TurtleGraphicsError:
        pass

turtle.penup()
turtle.sety(-100)
turtle.pendown()
turtle.width(10)
turtle.circle(100)

turtle.hideturtle()
turtle.done()
© www.soinside.com 2019 - 2024. All rights reserved.