[Tutor] Resending question with smaller file

Alan Gauld alan.gauld at yahoo.co.uk
Mon Feb 13 12:33:30 EST 2017


On 13/02/17 16:06, Lisa Hasler Waters wrote:

> We are trying to use the random function in the Tkinter module 

> from tkinter import *
> import random

This looks for the random module and tries your local folder first.
If you have a file called random.py it tries to import that.

Based on your error messages there is a file is called random.py
so it tries to import it rather than the standard library version... Try
renaming your file to something more descriptive of what
makes it different from the library version.

> tk = Tk()
> 
> canvas = Canvas(tk, width=400, height=400)
> canvas.pack()
> 
> 
> def random_randrange(height):
>     pass
> 
> 
> def random_randrange(width):
>     pass

These two functions are the same since Python doesn't understand
the parameter names it just sees

def aFunctionName(aParameterName)

so the second def simply overwrites the first.
What you really mean (I think) is

def random_randrange(aNumber): pass

Although that's still not a very descriptive name...

> def random_rectangle(width, height):
>     x1 = random_randrange(width)
>     y1 = random_randrange(height)
>     x2 = x1 + random.randrange(width)
>     y2 = y1 + random.randrange(height)
>     canvas.create_rectangle(x1, y1, x2, y2)
>     random_rectangle(400, 400)

You call this same function recursively, this will
result in an infinite loop until you run out of memory.
I don't know what you are trying to do but this is
surely not it.

This function never gets called and, since
its not assigned as an event handler, it will
never be executed.


> tk.mainloop()

> Here are the error messages:
> 
> Traceback (most recent call last):
>   File "/Users/lwaters/PycharmProjects/tkinternew/rectangles.py", line
> 2, in <module>
>     import random
>   File "/Users/lwaters/PycharmProjects/tkinternew/random.py", line 17,
> in <module>
>     randomRects(100)

Notice the two files listed above are in the same folder and one
is called random.py


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list