python简单的画板应用程序

实现一个简单的画板应用程序,用户可以通过鼠标在画布上绘制线条,并可以选择不同的颜色进行绘画。此外,程序还提供了橡皮擦功能,可以用来清除画布上的线条。

具体的技术点包括:

  1. Tkinter:这是Python的标准GUI库,用于创建图形用户界面。
  2. Canvas:这是一个Tkinter小部件,允许用户在其上绘制图形和其他项目。
  3. 事件绑定:通过bind方法将鼠标按下和移动事件与相应的处理函数关联起来。
  4. 颜色选择器:使用colorchooser.askcolor()方法弹出一个颜色选择对话框,让用户选择绘图的颜色。
  5. 状态管理:通过变量来跟踪当前的绘图模式(绘画或橡皮擦)以及当前选定的颜色。

以下是完整的可运行代码:

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()




你可以直接运行这段代码来启动这个简单的画板应用程序。
效果图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编织幻境的妖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值