My goal is to allow the user to input RGB values for both variables, but I do not know how to get Python to recognise an RGB value with a tag beforehand, such as with the int
and float
tags. An example of my code is shown below.
shape_fill = input ("Which color do you want to fill your shape? Please enter an RGB value. ") )
shape_pen = input ("Which color do you want the outline of your shape to be? Please enter an RGB value. ")
Does anyone have the solution?
BTW - I am using Turtle Graphics, does this have any effect?
Just let the user input comma-separated values:
R, G, B = map(float, input("Enter comma-separated: ").split(','))
So, when one enters 2.3, 6.7, 34.8
, the values of R
, G
and B
will be floats extracted from the input.
You can also do:
shape_fill = map(...)
shape_pen = map(...)
And then unpack the floats later on with R, G, B = shape_something
.
The following might do what you want -- an issue that hasn't been mentioned in the previous discussion is turtle.colormode()
which affects whether you want int or float input:
from turtle import Turtle, Screen
def input_rgb(prompt=""):
triple = None
text = prompt + "Enter comma-separated RGB values: "
while True:
try:
triple_string = input(text).split(',', maxsplit=2)
if len(triple_string) != 3:
continue
if isinstance(screen.colormode(), float):
triple = map(float, triple_string)
else:
triple = map(int, triple_string)
except ValueError:
continue
break
return triple
screen = Screen()
yertle = Turtle(shape="turtle")
yertle.fillcolor(input_rgb("Fill color? "))
yertle.pencolor(input_rgb("Outline color? "))
yertle.begin_fill()
yertle.circle(100)
yertle.end_fill()
screen.exitonclick()
USAGE
% python3 test.py
Fill color? Enter comma-separated RGB values: 1.0,0.0,0.0
Outline color? Enter comma-separated RGB values: 0.0,0.0,1.0
OUTPUT
The next challenge (for you) is to convert input_rgb()
to use the turtle graphic input routines instead of input()
:
turtle.textinput(title, prompt)
turtle.numinput(title, prompt, default=None, minval=None, maxval=None)
如果您使用海龟图形,我相信它确实会改变输入法尝试查看此网站,看看是否有帮助。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.