实现一个简单的画板应用程序,用户可以通过鼠标在画布上绘制线条,并可以选择不同的颜色进行绘画。此外,程序还提供了橡皮擦功能,可以用来清除画布上的线条。
具体的技术点包括:
- Tkinter:这是Python的标准GUI库,用于创建图形用户界面。
- Canvas:这是一个Tkinter小部件,允许用户在其上绘制图形和其他项目。
- 事件绑定:通过
bind
方法将鼠标按下和移动事件与相应的处理函数关联起来。 - 颜色选择器:使用
colorchooser.askcolor()
方法弹出一个颜色选择对话框,让用户选择绘图的颜色。 - 状态管理:通过变量来跟踪当前的绘图模式(绘画或橡皮擦)以及当前选定的颜色。
以下是完整的可运行代码:
import tkinter as tk
from tkinter import colorchooser
class PaintApp:
def __init__(self, root):
self.root = root
self.root.title("简单画板")
self.canvas = tk.Canvas(root, width=800, height=600, bg='white')
self.canvas.pack(fill=tk.BOTH, expand=True)
self.last_x, self.last_y = None, None
self.color = 'black'
self.eraser_mode = False
# 绑定鼠标事件
self.canvas.bind("<Button-1>", self.on_button_press)
self.canvas.bind("<B1-Motion>", self.on_move_paint)
# 添加颜色选择按钮
self.color_button = tk.Button(root, text="选择颜色", command=self.choose_color)
self.color_button.pack(side=tk.LEFT)
# 添加橡皮按钮
self.eraser_button = tk.Button(root, text="橡皮", command=self.toggle_eraser)
self.eraser_button.pack(side=tk.LEFT)
def on_button_press(self, event):
self.last_x, self.last_y = event.x, event.y
def on_move_paint(self, event):
if self.last_x and self.last_y:
x, y = event.x, event.y
if self.eraser_mode:
self.canvas.create_line(self.last_x, self.last_y, x, y, width=20, fill='white', capstyle=tk.ROUND, smooth=True)
else:
self.canvas.create_line(self.last_x, self.last_y, x, y, width=2, fill=self.color, capstyle=tk.ROUND, smooth=True)
self.last_x, self.last_y = x, y
def choose_color(self):
self.color_code = colorchooser.askcolor(title ="Choose color")[1]
if self.color_code:
self.color = self.color_code
def toggle_eraser(self):
self.eraser_mode = not self.eraser_mode
if self.eraser_mode:
self.eraser_button.config(text="绘画")
else:
self.eraser_button.config(text="橡皮")
if __name__ == "__main__":
root = tk.Tk()
app = PaintApp(root)
root.mainloop()
你可以直接运行这段代码来启动这个简单的画板应用程序。
效果图: