创建一幅图像,可在图像中按住鼠标左键移动绘图形,双击鼠标左键可清除绘制的图形
时间: 2024-02-18 08:01:38 浏览: 128
用鼠标左键制图
5星 · 资源好评率100%
好的,我可以用Python中的Tkinter库来实现你的要求。以下是代码示例:
```python
from tkinter import *
class PaintApp:
def __init__(self, master):
self.master = master
self.master.title("绘图程序")
# 创建画布
self.canvas = Canvas(self.master, bg="white")
self.canvas.pack(fill=BOTH, expand=YES)
# 绑定鼠标事件
self.canvas.bind("<Button-1>", self.on_mouse_down)
self.canvas.bind("<B1-Motion>", self.on_mouse_move)
self.canvas.bind("<Double-Button-1>", self.on_double_click)
# 记录绘制状态
self.is_drawing = False
self.prev_x, self.prev_y = None, None
def on_mouse_down(self, event):
# 开始绘制
self.is_drawing = True
self.prev_x, self.prev_y = event.x, event.y
def on_mouse_move(self, event):
# 绘制图形
if self.is_drawing:
x, y = event.x, event.y
if self.prev_x and self.prev_y:
self.canvas.create_line(self.prev_x, self.prev_y, x, y)
self.prev_x, self.prev_y = x, y
def on_double_click(self, event):
# 清除画布
self.canvas.delete("all")
self.is_drawing = False
# 创建主窗口
root = Tk()
app = PaintApp(root)
root.mainloop()
```
你可以将代码保存为一个Python文件,然后在终端中运行,即可看到绘图程序界面。按住鼠标左键并移动,即可绘制线条;双击鼠标左键,即可清除画布。
阅读全文