import
tkinter as tk
from
tkinter.colorchooser
import
askcolor
from
PIL
import
ImageGrab, Image, ImageDraw
class
PaintApp:
def
__init__(
self
, root):
self
.root
=
root
self
.root.title(
"画板程序"
)
self
.canvas
=
tk.Canvas(root, bg
=
"white"
, width
=
800
, height
=
600
)
self
.canvas.pack(fill
=
tk.BOTH, expand
=
True
)
self
.brush_color
=
"black"
self
.brush_size
=
2
self
.button_frame
=
tk.Frame(root)
self
.button_frame.pack(side
=
tk.TOP, fill
=
tk.X)
self
.color_button
=
tk.Button(
self
.button_frame, text
=
"选择颜色"
, command
=
self
.choose_color)
self
.color_button.pack(side
=
tk.LEFT, padx
=
5
, pady
=
5
)
self
.size_button
=
tk.Button(
self
.button_frame, text
=
"画笔大小"
, command
=
self
.choose_size)
self
.size_button.pack(side
=
tk.LEFT, padx
=
5
, pady
=
5
)
self
.save_button
=
tk.Button(
self
.button_frame, text
=
"保存"
, command
=
self
.save_canvas)
self
.save_button.pack(side
=
tk.LEFT, padx
=
5
, pady
=
5
)
self
.clear_button
=
tk.Button(
self
.button_frame, text
=
"清空"
, command
=
self
.clear_canvas)
self
.clear_button.pack(side
=
tk.LEFT, padx
=
5
, pady
=
5
)
self
.canvas.bind(
"<B1-Motion>"
,
self
.paint)
self
.canvas.bind(
"<ButtonRelease-1>"
,
self
.reset)
self
.last_x
=
None
self
.last_y
=
None
def
choose_color(
self
):
color
=
askcolor(color
=
self
.brush_color)[
1
]
if
color:
self
.brush_color
=
color
def
choose_size(
self
):
size
=
tk.simpledialog.askinteger(
"画笔大小"
,
"输入画笔大小"
, initialvalue
=
self
.brush_size)
if
size:
self
.brush_size
=
size
def
paint(
self
, event):
if
self
.last_x
and
self
.last_y:
self
.canvas.create_line(
self
.last_x,
self
.last_y, event.x, event.y,
width
=
self
.brush_size, fill
=
self
.brush_color,
capstyle
=
tk.
ROUND
, smooth
=
tk.TRUE)
self
.last_x
=
event.x
self
.last_y
=
event.y
def
reset(
self
, event):
self
.last_x
=
None
self
.last_y
=
None
def
clear_canvas(
self
):
self
.canvas.delete(
"all"
)
def
save_canvas(
self
):
x
=
self
.root.winfo_rootx()
+
self
.canvas.winfo_x()
y
=
self
.root.winfo_rooty()
+
self
.canvas.winfo_y()
x1
=
x
+
self
.canvas.winfo_width()
y1
=
y
+
self
.canvas.winfo_height()
image
=
ImageGrab.grab(bbox
=
(x, y, x1, y1))
image.save(
"canvas_image.png"
)
tk.messagebox.showinfo(
"保存成功"
,
"画布已保存为 canvas_image.png"
)
if
__name__
=
=
"__main__"
:
root
=
tk.Tk()
app
=
PaintApp(root)
root.mainloop()