在TKinter画布中重新加载图像的一部分(即擦除)

时间:2017-07-18 15:46:43

标签: python tkinter tkinter-canvas

我想在图像顶部制作一个遮罩,为此我在TKinter中创建了一个打开图像的编辑器,允许我在它上面绘图。不幸的是我不知道如何实现“擦除”功能。

在下面的代码中,我创建了一个示例图像,然后使用编辑器加载。我现在可以通过按下鼠标左键以蓝色绘制它。要擦除我想使用鼠标右键。现在我只是简单地画红色以显示我想要删除的位置。最后,我想“重新加载”我现在有红色的图像,以便它删除我添加的蓝色。

from __future__ import division
import numpy as np
import Tkinter as tk
from PIL import Image, ImageTk

class ImgEditor(object):

    def __init__(self,FileImg):
        self.root = tk.Tk()        

        #Picture
        self.Img = Image.open(FileImg)
        self.Imgtk = ImageTk.PhotoImage(self.Img)

        #Canvas
        self.Cv = tk.Canvas(self.root, width=800 , height=600)
        self.Cv.grid(row=0, column=0)

        #Set-up
        self.Drawing=False
        self.Erasing=False
        self.xold=None
        self.yold=None
        self.line_width = 40
        self.Color="#ff0000"

        # Mouse Actions (Left Click = Draw, Right Click = Erase)
        self.Cv.bind("<Motion>", self.Motion)
        self.Cv.bind("<ButtonPress-1>", self.B1Down)
        self.Cv.bind("<ButtonPress-3>", self.B3Down)
        self.Cv.bind("<ButtonRelease-1>", self.BUp)
        self.Cv.bind("<ButtonRelease-3>", self.BUp)

        # Fit Image
        self.ImRes = self.Img.size
        self.Scale = min(min(800/self.ImRes[0],600/self.ImRes[1]),1.0)
        self.Imgtk = ImageTk.PhotoImage(self.Img.resize((int(self.ImRes[0]*self.Scale),int(self.ImRes[1]*self.Scale)),Image.LANCZOS))
        self.Cv.create_image(0, 0, anchor="nw", image=self.Imgtk)

        self.root.mainloop()

    def B1Down(self,event): #Draw
        self.xold=event.x
        self.yold=event.y
        self.Color="#0000ff"
        self.Drawing=True
        self.Erasing=False
        self.Draw(self.xold,self.yold,self.xold,self.yold)

    def B3Down(self,event): #Erase
        self.xold=event.x
        self.yold=event.y
        self.Color="#ff0000"
        self.Drawing=False
        self.Erasing=True
        self.Draw(self.xold,self.yold,self.xold,self.yold)

    def BUp(self,event):
        self.Drawing=False
        self.Erasing=False

    def Draw(self,xo,yo,xn,yn):
        self.Cv.create_line(xo,yo,xn,yn,width=self.line_width,fill=self.Color,capstyle=tk.ROUND, smooth=tk.TRUE)

    def Motion(self,event):
        if self.Drawing or self.Erasing:
            xo=self.xold
            yo=self.yold
            xn=event.x
            yn=event.y
            self.Draw(xo,yo,xn,yn)
            self.xold=xn
            self.yold=yn


if __name__ == "__main__":
    # Example Image
    sx,sy=600,800
    MBase=np.fromfunction(lambda i, j: 255/2*(i/sx + (j/sy)**2), (sx, sy), dtype=float)
    Image.fromarray(np.uint8(MBase),mode="L").save("Test.png","png")   
    # Main Editor
    ge=ImgEditor("Test.png")

0 个答案:

没有答案