2017-02-14 81 views
-1

我的目标是允许用户输入两个变量的RGB值,但我不知道如何让Python预先用标签识别RGB值,例如intfloat标签。我的代码示例如下所示。如何让python识别RGB输入?

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. ") 

有没有人有解决方案?

顺便说一句 - 我正在使用龟图形,这是否有任何影响?

+0

我只是想让你知道,我现在已经解决了这个问题。我通过将RGB值分成三个不同的int来实现这一点,并要求用户输入三个不同的值。 –

回答

0

只是让用户输入逗号分隔值:

R, G, B = map(float, input("Enter comma-separated: ").split(',')) 

所以,当一个人进入2.3, 6.7, 34.8,的RGB的值将是从输入提取的浮动。

你也可以这样做:

shape_fill = map(...) 
shape_pen = map(...) 

然后后来解开彩车与R, G, B = shape_something

+0

对不起@ForceBru,但似乎没有工作。错误消息说'字符串'不能被转换为'float'。 –

+0

@ A.Kassam,哦,对不起,我忘了给'split'添加一个重要的参数。应该现在工作。 – ForceBru

-1

我相信它确实会改变输入法,如果你使用乌龟图形 试着找at this website看看是否有帮助。

0

下面可能做你想要的东西 - 还没有在前面的讨论中被提及的一个问题是turtle.colormode()影响你是否希望整数或浮点数输入:

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() 

用法

% 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 

输出

enter image description here

(你)的下一个挑战是转换input_rgb()用乌龟图形输入程序,而不是input()

turtle.textinput(title, prompt) 
turtle.numinput(title, prompt, default=None, minval=None, maxval=None) 
+0

对不起,@cdlane,但我的代码出现了以下错误消息: –

+0

NameError:名称'屏幕'未定义 –

+0

@ A.Kassam我刚刚从SO页面复制我的答案到一个文件,它在Python下运行良好3.6.0。你一定有错误的东西,重新检查并再试一次。 – cdlane