423,851 Members | 2,771 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 423,851 IT Pros & Developers. It's quick & easy.

Global variables in function object

P: 7
The following code is from the turtle graphics demos. The program is a color mixer and allows the user to change the background color of the window using three turtle sliders.

Under the function definition "main" there are three global variables defined ("screen", "red", and "blue").

I'm trying to understand the purpose of defining these variables as global within the function definition.

Expand|Select|Wrap|Line Numbers
  1.  
  2. from turtle import Screen, Turtle, mainloop
  3.  
  4. class ColorTurtle(Turtle):
  5.  
  6.     def __init__(self, x, y):
  7.         Turtle.__init__(self)
  8.         self.shape("turtle")
  9.         self.resizemode("user")
  10.         self.shapesize(3,3,5)
  11.         self.pensize(10)
  12.         self._color = [0,0,0]
  13.         self.x = x
  14.         self._color[x] = y
  15.         self.color(self._color)
  16.         self.speed(0)
  17.         self.left(90)
  18.         self.pu()
  19.         self.goto(x,0)
  20.         self.pd()
  21.         self.sety(1)
  22.         self.pu()
  23.         self.sety(y)
  24.         self.pencolor("gray25")
  25.         self.ondrag(self.shift)
  26.  
  27.     def shift(self, x, y):
  28.         self.sety(max(0,min(y,1)))
  29.         self._color[self.x] = self.ycor()
  30.         self.fillcolor(self._color)
  31.         setbgcolor()
  32.  
  33. def setbgcolor():
  34.     screen.bgcolor(red.ycor(), green.ycor(), blue.ycor())
  35.  
  36. def main():
  37.     global screen, red, green, blue
  38.     screen = Screen()
  39.     screen.delay(0)
  40.     screen.setworldcoordinates(-1, -0.3, 3, 1.3)
  41.  
  42.     red = ColorTurtle(0, .5)
  43.     green = ColorTurtle(1, .5)
  44.     blue = ColorTurtle(2, .5)
  45.     setbgcolor()
  46.  
  47.     writer = Turtle()
  48.     writer.ht()
  49.     writer.pu()
  50.     writer.goto(1,1.15)
  51.     writer.write("DRAG!",align="center",font=("Arial",30,("bold","italic")))
  52.     return "EVENTLOOP"
  53.  
  54. if __name__ == "__main__":
  55.     msg = main()
  56.     print(msg)
  57.     mainloop()
  58.  
  59.  
2 Weeks Ago #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.