Python Forum

Full Version: Use of input function to change screen background color in Turtles
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am teaching myself Python on Python 3.8 following Think Like a Computer Scientist and having difficulties as I am a newcomer to coding

I have this code, which works:

import turtle

wn = turtle.Screen()
wn.bgcolor("lightgreen")

alex = turtle.Turtle()
alex.color("red")
alex.pensize(3)

alex.forward(50)
alex.left(120)
alex.forward(50)

wn.mainloop()

I want to get user input to change the screen color (wn.bgcolor) and have modified the code to:


import turtle

screen_color = input("Enter color ") #get user input
wn = turtle.Screen()
wn.bgcolor("screen_color") #change color to user selection

alex = turtle.Turtle()
alex.color("red")
alex.pensize(3)

alex.forward(50)
alex.left(120)
alex.forward(50)

wn.mainloop()

This does not work and I get the following error message:

Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
= RESTART: C:/Users/John/Documents/John''s files/Work/Coding/Think Like a Computer Scientist/Programmes/turtles.py
Enter color blue
Traceback (most recent call last):
File "C:/Users/John/Documents/John''s files/Work/Coding/Think Like a Computer Scientist/Programmes/turtles.py", line 5, in <module>
wn.bgcolor("screen_color")
File "C:\Users\John\AppData\Local\Programs\Python\Python38-32\lib\turtle.py", line 1237, in bgcolor
color = self._colorstr(args)
File "C:\Users\John\AppData\Local\Programs\Python\Python38-32\lib\turtle.py", line 1158, in _colorstr
raise TurtleGraphicsError("bad color string: %s" % str(color))
turtle.TurtleGraphicsError: bad color string: screen_color
>
I am at a loss of what to do and would appreciate any help or advice.

Thanking you in advance
Quotes make a string. When referencing a variable, do not put it in quotes.

wn.bgcolor(screen_color) # No quotes so it uses the value of screen_color, which is a string
Hello Tullis

Thanks for the prompt reply.

That certainly got rid of the error message but wn.bgcolor(screen_color) has not activated any change whereas if I remove the screen_color variable from the code and manually insert a color into the wn.bgcolor variable the code all works and the screen colour changes!

Can you please advise?
Good Morning Stullis

Apologies for getting your name wrong last time.

I don't quite know what changed but when I opened up my programme this morning it worked perfectly, so your simple fix was dead right. Thank you so much and apologies for the confusion