Emmeline writes:
I'm twelve and I recently got a raspberry Pi camera module. I really wanted to do stop animation with it but, when I used Tkinter to make a button it would take a picture when I pressed it and save it as I specified. The problem is if I wanted to use the button again it deleted the old image ex image.jpg and replaced it with a new image (image.jpg). Do you have any suggestions of how to change the code so it will name the photos numerically. Ex image1.jpg then image2.jpg. I'm doing all this in idle3. Thanks a lot for the book. "Python for kids" is great.
Glad you like the book.
There's a few ways you can change your code to have an incrementing filename. You could write a class, which uses a variable to store the current number. The class would have a function which increments the variable and returns the value. Something like this would work:
>>> class Counter:
... def __init__(self):
... self.counter = 0
... def next(self):
... self.counter += 1
... return self.counter
...
You could use the class by creating an object like this:
>>> c = Counter()
>>> c.next()
1
>>> c.next()
2
You could then create a function to return a unique image name each time it's called:
c = Counter()
def get_image_name():
return 'image%s.jpg' % c.next()
You could also just adapt the code above to create a class which returns unique image names:
>>> class ImageNames:
... def __init__(self):
... self.counter = 0
... def next_image_name(self):
... self.counter += 1
... return 'image%s.jpg' % self.counter
...
>>> im = ImageNames()
>>> im.next_image_name()
'image1.jpg'
>>> im.next_image_name()
'image2.jpg'
By the way, you can find more about embedding values in strings in Chapter 3, and classes and objects in Chapter in Chapter 8.
Hope that helps.