When we create an elaborate shape using Tkinter, we often want to preserve that shape for later use. In fact, we would like to build up a whole library of shapes. If other people do similar work, we may want to share and exchange shapes. Such community efforts are the key to the success of the most powerful and successful open-source programs.
If we go back to the example titled "Drawing Intricate Shapes the Curly Vine", in Chapter 2, Drawing Fundamental Shapes, we see that the shapes are defined by the two coordinate lists vine_x
and vine_y
. We are going to first save these shapes in a disk file and then see what is needed to successfully retrieve and draw them.
Create a folder /constr/vector_shapes
on your hard drive ready to receive your stored data.
Execute the program shown in the usual way.
# save_curly_vine_1.py #>>>>>>>>>>>>>>>>> vine_x = [23, 20, 11, 9, 29, 52, 56, 39, 24, 32, 53, 69, 63, 47, 35, 35, 51, 82, 116, 130, 95, 67, 95, 114, 95, 78, 95, 103, 95, 85, 95, 94.5] vine_y = [36, 44, 39, 22, 16, 32, 56, 72, 91, 117,125, 138, 150, 151, 140, 123, 107, 92, 70, 41, 5, 41, 66, 41, 24, 41, 53, 41, 33, 41, 41, 39] vine_1 = open('/constr/vector_shapes/curley_vine_1.txt', 'w') vine_1.write(str(vine_x )) vine_1.write(" ") vine_1.write(str(vine_y ))
The first thing to note is that stored data does not have a 'type' it is just text characters. So any data being appended to an open file must be converted into string format using the string conversion function str(some_integer_or_float_object)
.
The second thing to note is that storing the whole list as a list object, like str(vine_x)
, is the best way to do things because when stored this way it can be read back directly as a whole line read into a similar list object see the next recipe to how to do this. In typical Python fashion, the simple and obvious method always seems to be the best.
The problem we face when retrieving lists of mixed integer and floating point data is that it is stored as a long string of characters. So how do we get Python to convert the long lists of characters that include square brackets, commas, spaces and new-line characters, into a normal Python numerical list? We want our drawing back undamaged. There is a lovely function eval()
that does this effortlessly.
There is another method called pickle that does the same thing.
3.145.103.154