Bac*_*chi 1 tkinter paint python-imaging-library python-3.x tkinter-canvas
我制作了一个绘画程序,但我无法顺利绘制并且每次都用不同的名称保存图像。请帮忙!
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()
Run Code Online (Sandbox Code Playgroud)

您可以使用连续绘制而不是绘制单独的小圆圈。
以下示例存储鼠标位置的最后值以绘制一条线到当前值。
需要点击,移动鼠标进行绘制;松开单击即可停止。
图像名称包含一个数字,每次保存时该数字加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()
Run Code Online (Sandbox Code Playgroud)
据说不比你的可怕,但是线条是连续的......
| 归档时间: |
|
| 查看次数: |
10285 次 |
| 最近记录: |