简体   繁体   English

How to Python Tkinter saving canvas object by dump all canvas object?

[英]How to Python Tkinter saving canvas object by dump all canvas object?

I want to save canvas all "object" not the graph of canvas to save.我想保存 canvas 所有“对象”而不是 canvas 的图形来保存。 And load the saving to modify the object(maybe change position,color) I know that is no way to save widget object by pickle.并加载保存以修改对象(可能更改 position,颜色)我知道这是无法通过泡菜保存小部件 object 的方法。 So I want to save the entire config of object and recreate object when loading.所以我想保存 object 的整个配置并在加载时重新创建 object。 Is any one know how to achieve pickle_save/pickle_load this two function which will load/save self.c.有谁知道如何实现 pickle_save/pickle_load 这两个 function 将加载/保存 self.c。

from tkinter.ttk import *
from tkinter import *
import tkinter.filedialog
import pickle



class Test_Gui(Frame):

   def __init__(self, root, run_class=None):

      Frame.__init__(self, root)
      self.run_class = run_class
      self.root = root
      root.geometry("+400+50")
      root.title("This is ping status")
      self.width = 600
      self.height = 400

      # create canvas at begin will be saved or replace by loading 
      self.c = Canvas(self, width=self.width, height=self.height,
                      bd=0, bg="green", highlightthickness=5, relief=RIDGE, borderwidth=2,
                      scrollregion=(0, 0, self.width, self.height))
      self.c.pack()
      self.canvas_bind()
      self.setting_menu()

      self.pack()

   def setting_menu(self):

      self.rootmenu = Menu(self.root, tearoff=False)
      self.root.config(menu=self.rootmenu)
      openmenu = Menu(self.rootmenu, tearoff=False)
      self.rootmenu.add_cascade(label='Open', menu=openmenu, underline=0)

      def pickle_save():
         # Some method to save widget object/config
         # save self.c to file
         pass

      def pickle_load():
         # Some method to loading save
         # destory self.c or origin and load file  tot self.c
         pass


      openmenu.add_command(label='Save', command=pickle_save)
      openmenu.add_command(label='Load', command=pickle_load)
      openmenu.add_command(label='Exit', command=self.root.destroy)

   def canvas_bind(self):
      def left_click(event):
         x, y = self.c.canvasx(event.x), self.c.canvasx(event.y)
         x1, y1 = (x - 3), (y - 3)
         x2, y2 = (x + 3), (y + 3)
         self.c.create_oval(x1, y1, x2, y2, fill="red")
      self.c.bind('<Button-1>', left_click)



if __name__ == '__main__':
   root = Tk()
   root.bind("<Escape>", lambda *x: root.destroy())
   root.geometry("300x200+50+50")

   top = Toplevel(root)
   Test_Gui(root=top)

   root.mainloop()

Use json to save the canvas items to a text file:使用json将 canvas 项目保存到文本文件:

import json
...

self.json_file = 'canvas-items.json'

def json_save():
    with open(self.json_file, 'w') as f:
        for item in self.c.find_all():
            print(json.dumps({
                'type': self.c.type(item),
                'coords': self.c.coords(item),
                'options': {key:val[-1] for key,val in self.c.itemconfig(item).items()}
            }), file=f)

Then you can read the json file and create the items:然后您可以阅读json文件并创建项目:

def json_load():
    # if you want to clear the canvas first, uncomment below line
    #self.c.delete('all')
    funcs = {
        'arc': self.c.create_arc,
        #'bitmap' and 'image' are not supported
        #'bitmap': self.c.create_bitmap,
        #'image': self.c.create_image,
        'line': self.c.create_line,
        'oval': self.c.create_oval,
        'polygon': self.c.create_polygon,
        'rectangle': self.c.create_rectangle,
        'text': self.c.create_text,
         # 'window' is not supported
    }
    with open(self.json_file) as f:
        for line in f:
            item = json.loads(line)
            if item['type'] in funcs:
                funcs[item['type']](item['coords'], **item['options'])


openmenu.add_command(label='Save', command=json_save)
openmenu.add_command(label='Load', command=json_load)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM