用python写一个画图软件
时间: 2023-12-18 09:04:15 浏览: 77
好的,您可以使用Python内置的Tkinter库来创建一个画图软件。以下是一个示例代码:
```python
from tkinter import *
from tkinter.colorchooser import askcolor
class PaintApp:
def __init__(self, root):
self.root = root
self.root.title("画图软件")
self.pen_button = Radiobutton(self.root, text='画笔', command=self.use_pen)
self.pen_button.grid(row=0, column=0)
self.color_button = Button(self.root, text='颜色', command=self.choose_color)
self.color_button.grid(row=0, column=1)
self.eraser_button = Radiobutton(self.root, text='橡皮擦', command=self.use_eraser)
self.eraser_button.grid(row=0, column=2)
self.canvas = Canvas(self.root, bg='white', width=600, height=400)
self.canvas.grid(row=1, columnspan=3)
self.setup()
def setup(self):
self.old_x, self.old_y = None, None
self.line_width = 5
self.color = 'black'
self.eraser_on = False
self.active_button = self.pen_button
self.canvas.bind('<B1-Motion>', self.paint)
self.canvas.bind('<ButtonRelease-1>', self.reset)
def use_pen(self):
self.activate_button(self.pen_button)
def choose_color(self):
self.color = askcolor()[1]
def use_eraser(self):
self.activate_button(self.eraser_button, eraser_mode=True)
def activate_button(self, button, eraser_mode=False):
self.active_button.config(relief=RAISED)
button.config(relief=SUNKEN)
self.active_button = button
self.eraser_on = eraser_mode
def paint(self, event):
if self.eraser_on:
self.canvas.create_rectangle(event.x - 10, event.y - 10, event.x + 10, event.y + 10, fill='white', outline='white')
else:
if self.old_x and self.old_y:
self.canvas.create_line(self.old_x, self.old_y, event.x, event.y, width=self.line_width, fill=self.color, capstyle=ROUND, smooth=TRUE, splinesteps=36)
self.old_x = event.x
self.old_y = event.y
def reset(self, event):
self.old_x, self.old_y = None, None
if __name__ == '__main__':
root = Tk()
PaintApp(root)
root.mainloop()
```
这个画图软件包含了画笔、橡皮擦和颜色选择三个功能,同时支持撤销操作。您可以通过改变代码来实现其他画图功能,比如画直线、矩形、圆等。
阅读全文