Why do I have to use "global" so much when using Turtle?

John Ladasky john_ladasky at sbcglobal.net
Sun Sep 22 00:39:07 EDT 2013


Hi, folks,

Some of you may remember that I am teaching some high school students how to program.  Because they all love graphics, I have been investigating the turtle module, which I gather is built on top of Tk.  I can see that real-time applications are possible.  I'm writing a classic "bouncing-balls" program to demonstrate to my students.  

In the main program code, I instantiate a turtle.Screen, named sc.  

I draw a bounding box, whose size is described by the variables edgew and edgeh.  I have a list of Turtle objects, which I named balls.  I have a timer interval stored in tick.

In the main loop of my program, I bind a function to update the positions of the balls to a timer, thus:

sc.ontimer(move_balls, tick)

Inside my move_balls function, I could not get ANYTHING done without the following declaration:

global balls, edgew, edgeh, tick

For a while, I had a "quit" function that I bound to the q key:

sc.onkeypress(quit, "q")

The quit function simply printed a message, and then called sc.bye().  As with move_balls, quit wouldn't work unless I had a "global sc" declaration in it.  (My shortened program skips my function and just binds sc.bye to the q key, avoiding the need for globals.)

Once I use globals, everything works fine.  However, I haven't taught my students a thing about the globals declaration.  Furthermore, I was always taught that the need for global variables generally indicated that YOU were writing a SLOPPY program!

However, neither Screen.ontimer() not Screen.onkeypress() appear to give me a way to pass arguments to functions of my own.  Why don't they?  Is this some limitation of Tk?  I have worked with other GUI's before, and I don't remember having to jump through this particular hoop.

I'm torn between proceeding with turtle, burdening my students with comprehending globals (they're young, they just barely grasp the idea of namespaces) -- or, abandoning turtle for another approach.

Comments appreciated!



More information about the Python-list mailing list