如何绘制图像,以便将我的图像用作画笔

How to draw an image, so that my image is used as a brush

我创建了这个应该绘制图像的小算法(假设我的画笔是图像),这样当我不断单击时我就会绘制图像,但是正如您测试代码时所看到的那样,它不会画画

它所做的只是将图像移动到 Canvas

有没有办法让图像保留在 Canvas 上?

这是我的代码:

from tkinter import *
from PIL import Image, ImageTk

master = Tk()
w = Canvas(master, width=800, height=400)
w.pack(expand = YES, fill = BOTH)
imagen = Image.open('C:/Users/Andres/Desktop/hola.png')
P_img = ImageTk.PhotoImage(imagen)

def paint( event ):
    global w, P_img_crop
    #I get the mouse coordinates
    x, y = ( event.x - 1 ), ( event.y - 1 )
    #I open and draw the image
    img_crop = Image.open('C:/Users/Andres/Desktop/papa.png')
    P_img_crop = ImageTk.PhotoImage(img_crop)
    w.create_image((x,y), anchor=NW, image=P_img_crop)

w.bind( "<B1-Motion>", paint )
mainloop()

您只需删除 paint() 函数中的图像创建即可。然后你会实现你想要的,因为否则它会再次创建图像并且不会在后面保存副本。换句话说,当您移动画笔时,之前的图像将被垃圾收集。

代码:

from tkinter import *
from PIL import Image, ImageTk

master = Tk()
w = Canvas(master, width=800, height=400)
w.pack(expand = YES, fill = BOTH)
img_crop = Image.open('yes.png')
P_img_crop = ImageTk.PhotoImage(img_crop)
def paint(event):
    global P_img_crop
    #I get the mouse coordinates
    x, y = event.x - 1, event.y - 1
    #I open and draw the image
    w.create_image(x, y, image = P_img_crop)
    

w.bind("<B1-Motion>", paint)
master.mainloop()

希望对您有所帮助!

我明白了 我不知道在 canvas 上绘制的图像应该被保存,所以我所做的是将图像存储在属于 canvas 的矩阵中。 这是代码,以防万一...

from tkinter import *
from PIL import Image, ImageTk

master = Tk()
w = Canvas(master, width=800, height=400)
w.dib = [{} for k in range(10000)]
w.pack(expand = YES, fill = BOTH)
puntero = 0

def paint( event ):
    global w, P_img_crop, puntero
    #I get the mouse coordinates
    x, y = ( event.x - 1 ), ( event.y - 1 )
    #I open and draw the image
    img_crop = Image.open('C:/Users/Andres/Documents/PROYECTOS INCONCLUSOS/PAINT MATEW PYTHON/hola.png')
    w.dib[puntero]['image'] = ImageTk.PhotoImage(img_crop)
    w.create_image((x,y), anchor=NW, image=w.dib[puntero]['image'])
    puntero += 1
    if(puntero >=10000):
        puntero = 0

w.bind( "<B1-Motion>", paint )
mainloop()