Saving objects from tk canvas


I'm trying to make a save function in a program im doing for bubbling/ballooning drawings. The only thing I can't get to work is save a "work copy". As if a drawing gets revision changes, you don't need to redo all the work. Just load the work copy, and add/remove/re-arrage bubbles.

I'm using tkinter and canvas. And creates ovals and text for bubbles. But I can't figure out any good way to save the info from the oval/text objects. I tried to pickle the whole canvas, but that seems like it won't work after some googeling. And pickle every object when created seems to only save the object id. 1, 2 etc. And that also won't work since some bubbles will be moved and receive new coordinates. They might also have a different color, size etc.

In my next approach I'm thinking of saving the whole "can.create_oval( x1, y1, x2, y2, fill = fillC, outli...." as a string to a txt and make the function to recreate a with eval()

Any one have any good suggestion on how to approach this?


Answers:


There is no built-in way to save and restore the canvas. However, the canvas has methods you can use to get all of the information about the items on the canvas. You can use these methods to save this information to a file and then read this file back and recreate the objects.

  • find_all - will return an ordered list of object ids for all objects on the canvas
  • type - will return the type of the object as a string ("rectangle", "circle", "text", etc)
  • itemconfig - returns a dictionary with all of the configuration values for the object. The values in the dictionary are a list of values which includes the default value of the option at index 3 and the current value at index 4. You can use this to save only the option values that have been explicitly changed from the default.
  • gettags - returns a list of tags associated with the object