Python - Tkinter - Paint:如何平滑地绘制并使用不同的名称保存图像?

问题描述 投票:0回答:1

我制作了一个绘画程序,但是我无法顺利绘制并且每次使用不同的名称保存图像。请帮忙!

from tkinter import *
# by Canvas I can't save image, so i use PIL
import PIL
from PIL import Image, ImageDraw


def save():
    filename = 'image.png'
    image1.save(filename)

def paint(event):
    x1, y1 = (event.x), (event.y)
    x2, y2 = (event.x + 1), (event.y + 1)
    cv.create_oval((x1, y1, x2, y2), fill='black', width=10)
    #  --- PIL
    draw.line((x1, y1, x2, y2), fill='black', width=10)


root = Tk()

cv = Canvas(root, width=640, height=480, bg='white')
# --- PIL
image1 = PIL.Image.new('RGB', (640, 480), 'white')
draw = ImageDraw.Draw(image1)
# ---- 
cv.bind('<B1-Motion>', paint)
cv.pack(expand=YES, fill=BOTH)

btn_save = Button(text="save", command=save)
btn_save.pack()

root.mainloop()

python-3.x tkinter python-imaging-library paint tkinter-canvas
1个回答
1
投票

您可以使用连续绘图而不是绘制单独的小圆圈。 以下示例存储鼠标位置的最后一个值,以将线条绘制为当前值。

你需要点击,然后移动鼠标进行绘制;释放点击停止。

图像名称包括每次保存时增加1的数字;因此,您可以在绘制完整图片时保存所有中间图像。

from tkinter import *
import PIL
from PIL import Image, ImageDraw


def save():
    global image_number
    filename = f'image_{image_number}.png'   # image_number increments by 1 at every save
    image1.save(filename)
    image_number += 1


def activate_paint(e):
    global lastx, lasty
    cv.bind('<B1-Motion>', paint)
    lastx, lasty = e.x, e.y


def paint(e):
    global lastx, lasty
    x, y = e.x, e.y
    cv.create_line((lastx, lasty, x, y), width=1)
    #  --- PIL
    draw.line((lastx, lasty, x, y), fill='black', width=1)
    lastx, lasty = x, y


root = Tk()

lastx, lasty = None, None
image_number = 0

cv = Canvas(root, width=640, height=480, bg='white')
# --- PIL
image1 = PIL.Image.new('RGB', (640, 480), 'white')
draw = ImageDraw.Draw(image1)

cv.bind('<1>', activate_paint)
cv.pack(expand=YES, fill=BOTH)

btn_save = Button(text="save", command=save)
btn_save.pack()

root.mainloop()

据称并不比你的糟糕,但线条是连续的......

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.