Python - Tkinter - Paint:如何平滑地绘制并使用不同的名称保存图像? [英] Python - Tkinter - Paint: How to Paint smoothly and save images with a different names?
问题描述
我制作了一个绘图程序,但我无法流畅地绘制并每次以不同的名称保存图像.请帮忙!
I made a paint program, but I can not draw smoothly and save the images each time with a different names. Please help!
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()
推荐答案
您可以使用连续绘图而不是单独绘制小圆圈.
下面的示例存储鼠标位置的最后一个值,以绘制一条线到当前值.
You could use continuous drawing instead of drawing separate small circles.
The following example stores the last values of the position of the mouse to draw a line to the current value.
您需要点击,并移动鼠标进行绘制;松开点击停止.
You need to click, and move the mouse to draw; release the click to stop.
图像名称包含一个数字,每次保存时增加 1;因此,您可以在绘制完整图片时保存所有中间图像.
The image name includes a number that is incremented by 1 each time you save; you can therefore save all the intermediate images as you draw the full picture.
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()
<小时>
据称不比你的更糟糕,但线条是连续的......
Allegedly not less terrible than yours, but the lines are continuous...
这篇关于Python - Tkinter - Paint:如何平滑地绘制并使用不同的名称保存图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!