用python生成一个工业级的智能画板,画板模糊且透明,可在画板上用鼠标画画,设置画笔颜色,设置画笔粗细,可保存画板,读取画板,关闭画板,最小化画板
时间: 2024-02-28 21:26:02 浏览: 83
要实现这个功能,我们可以使用 Python 的 GUI 库 Tkinter 来创建一个画板界面,并使用 Pillow 库来处理图像。以下是一个简单的示例代码:
```python
import tkinter as tk
from tkinter import filedialog
from tkinter.colorchooser import askcolor
from PIL import Image, ImageDraw
class PaintApp:
def __init__(self, master):
self.master = master
self.master.title("智能画板")
self.master.geometry("800x600")
self.color = "#000000"
self.thickness = 5
self.image = Image.new("RGBA", (800, 600), (255, 255, 255, 0))
self.draw = ImageDraw.Draw(self.image)
self.canvas = tk.Canvas(self.master, bg="white", width=800, height=600)
self.canvas.pack(fill=tk.BOTH, expand=True)
self.canvas.bind("<B1-Motion>", self.draw_line)
self.canvas.bind("<ButtonRelease-1>", self.save_image)
self.create_menu()
def create_menu(self):
menubar = tk.Menu(self.master)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="保存画板", command=self.save_canvas)
filemenu.add_command(label="读取画板", command=self.load_canvas)
filemenu.add_command(label="关闭画板", command=self.close_app)
menubar.add_cascade(label="文件", menu=filemenu)
colormenu = tk.Menu(menubar, tearoff=0)
colormenu.add_command(label="选择颜色", command=self.choose_color)
menubar.add_cascade(label="颜色", menu=colormenu)
thicknessmenu = tk.Menu(menubar, tearoff=0)
thicknessmenu.add_radiobutton(label="细", variable=self.thickness, value=1)
thicknessmenu.add_radiobutton(label="适中", variable=self.thickness, value=5)
thicknessmenu.add_radiobutton(label="粗", variable=self.thickness, value=10)
menubar.add_cascade(label="粗细", menu=thicknessmenu)
self.master.config(menu=menubar)
def draw_line(self, event):
x1, y1 = (event.x - self.thickness), (event.y - self.thickness)
x2, y2 = (event.x + self.thickness), (event.y + self.thickness)
self.canvas.create_oval(x1, y1, x2, y2, fill=self.color, outline=self.color)
self.draw.ellipse([x1, y1, x2, y2], fill=self.color, outline=self.color)
def save_image(self, event):
self.image.save("canvas.png")
def save_canvas(self):
filename = filedialog.asksaveasfilename(defaultextension=".png", filetypes=[("PNG", "*.png")])
if filename:
self.image.save(filename)
def load_canvas(self):
filename = filedialog.askopenfilename(filetypes=[("PNG", "*.png")])
if filename:
self.image = Image.open(filename)
self.draw = ImageDraw.Draw(self.image)
self.canvas.delete("all")
self.canvas.create_image(0, 0, image=self.image, anchor=tk.NW)
def close_app(self):
self.master.destroy()
def choose_color(self):
self.color = askcolor(title="选择颜色")[1]
if __name__ == "__main__":
root = tk.Tk()
app = PaintApp(root)
root.mainloop()
```
这个程序创建了一个 800x600 的画板界面,并在画板上响应鼠标事件来绘制图形。可以通过菜单栏选择画笔颜色和粗细,并可以保存和读取画板。关闭画板时程序会退出。
阅读全文