Pergunta

Hi there I'm just starting to learn python. I have a problem with a program i want to modify called LineGenerator.py from the Mag Pi issue 7. Full code:

http://www.themagpi.com/issue/issue-7/

This program introduces the command line arguments.

I am trying to add a command line argument to change the color of a graphic.

first i defined the colors: ...

WH = 255,255,255

RE = 255,0,0

and so on...

then i defined the command line argument: ...

parser.add_argument('-c', action='store', dest='colour', type=str, 
                    help='Choose Colour')

...

later in my program i want to draw the line ...

pygame.draw.line(screen, args.colour,(nSX),(nSY),(nEX,nEY),1)

...

When I start the script with

python LineGenerator.py -c WH

I get this Error message:

TypeError: invalid color argument

When i change the "args.colour" directly in the Code with "WH" then it works.

Can you help me, please?

Foi útil?

Solução

Use a dictionary to store your color values by name:

colors = { "WH": (255, 255, 255),
           "RE": (255, 0, 0),
         }

Then access the correct color using the string passed to the -c option:

pygame.draw.line(screen, colors[args.colour], (nSX), (nSY), (nEX,nEY), 1)

Outras dicas

You need to pass -c as a string. Wrap it in quotes:

parser.add_argument('-c', action='store', dest='colour', type=str, 
                    help='Choose Colour')

Otherwise python will pass the value of the variable -c, whatever it is. Hope it helps!

Edit: Oh, that wasn't the problem... hahaha

Well, i figured out what it is anyway. When you're passing WH as an argument to the script, you are not passing the value of the variable WH - which is 255, 255, 255 - but instead you're passing the string literal "WH" as the argument to draw.line. Hence the error.

To fix this, you should specify the parameter nargs, and discard the type parameter, since the latter isn't needed:

parser.add_argument('-c', action='store', dest='colour', nargs=3,
                    help='Choose Colour')
...
colours = (int(i) for i in args.colours)
pygame.draw.line(screen, *colours,(nSX),(nSY),(nEX,nEY),1)

And when you're running it:

python LineGenerator.py -c 255, 255, 255

That's all! Hope it helps!

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top