我正在研究python turtle以便习惯并且想要创建一个输入语句,要求用户选择笔颜色,然后根据用户的选择执行乌龟。需要将其写为字符串
试试这个:
PenColor_choice = input("Enter the pen color, please!")
if PenColor_choice == something :
do_something()
既然你标记了你的问题[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()