代码下载:canvaswithsave.zip

说明:
点击保存后,将会生成一个.txt文件。若需要重新导入数据,需要将.txt文件和.py文件放置在同一个目录下~

from tkinter import *
import numpy as np
b1 = "up"
xold, yold = None, None
size = 500
list1 = []  #list1用来储存路径

def main():
    root = Tk()
    root.title("小画板")
    drawing_area = Canvas(root,width=size,height=size)
    drawing_area.pack()
    drawing_area.bind("<Motion>", motion)
    drawing_area.bind("<ButtonPress-1>", b1down)
    drawing_area.bind("<ButtonRelease-1>", b1up)
    
    button4=Button(root,fg="green",text="Clear",command=lambda:delete(drawing_area))
    button4.pack(side=LEFT)
    button4=Button(root,fg="green",text="Save image",command=lambda:getter(drawing_area))
    button4.pack(side=LEFT)
    button4=Button(root,fg="green",text="Save path",command=lambda:saving(drawing_area))
    button4.pack(side=LEFT)
    button4=Button(root,fg="green",text="Import File",command=lambda:importfile(drawing_area))
    button4.pack(side=LEFT)
    label1 = Label(root, text='Click The mouse. Start drawing...', width=30, height=1,font=("Arial", 10))
    label1.pack(side=BOTTOM)
    
    def delete(widget):
        widget.delete("all")
        list1 = []
        
    def getter(widget):
        from PIL import ImageGrab
        x=root.winfo_rootx()+widget.winfo_x()
        y=root.winfo_rooty()+widget.winfo_y()
        x1=x+widget.winfo_width()
        y1=y+widget.winfo_height()
        import datetime
        now = datetime.datetime.now()
        ImageGrab.grab().crop((x,y,x1,y1)).save(str(now)+".png")
    
    def saving(widget):
        np.savetxt('data.txt',list1) #将会保存在和python程序所在的文件夹中
    
    def importfile(widget):
        list_text = np.loadtxt('data.txt')
        delete(widget)
        list1 = list_text

        xformer = list_text[0][0]
        yformer = list_text[0][1]

        k = 1
        #这里要做一个防止断触失效的设计
        while k < len(list_text):
            if list_text[k][0] != -1:
                widget.create_line(xformer,yformer,list_text[k][0],list_text[k][1],smooth=TRUE)
                xformer = list_text[k][0]
                yformer = list_text[k][1]
                k = k + 1
            else:
                xformer = list_text[k+1][0]
                yformer = list_text[k+1][1]
                k = k + 2

    root.mainloop()

def b1down(event):
    global b1
    b1 = "down"
def b1up(event):
    global b1, xold, yold
    b1 = "up"
    xold = None
    yold = None
    list1.append([-1,-1])

def motion(event):
    if b1 == "down":
        global xold, yold
        if xold is not None and yold is not None:
            event.widget.create_line(xold,yold,event.x,event.y,smooth=TRUE)
        
        list1.append([event.x,event.y])
        xold = event.x
        yold = event.y

if __name__ == "__main__":
    main()
Last modification:January 18th, 2020 at 08:00 pm