简单的python画图代码_Python使用tkinter制作一个简易的绘图程序四(Python GUI编程)...
时间: 2024-02-20 17:02:00 浏览: 104
python通过tkinter实现画图小程序
好的,以下是一个简单的 Python 绘图程序的代码,使用了 tkinter 库:
```
import tkinter as tk
class PaintApp:
def __init__(self, master):
self.master = master
self.master.title("Python 绘图程序")
self.master.geometry("800x600")
# 创建画布
self.canvas = tk.Canvas(self.master, bg="white", width=600, height=400)
self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# 创建工具栏
self.toolbar = tk.Frame(self.master)
self.toolbar.pack(side=tk.RIGHT, fill=tk.Y)
self.pen_btn = tk.Button(self.toolbar, text="画笔")
self.pen_btn.pack(side=tk.TOP)
self.line_btn = tk.Button(self.toolbar, text="直线")
self.line_btn.pack(side=tk.TOP)
self.rect_btn = tk.Button(self.toolbar, text="矩形")
self.rect_btn.pack(side=tk.TOP)
self.oval_btn = tk.Button(self.toolbar, text="椭圆")
self.oval_btn.pack(side=tk.TOP)
self.clear_btn = tk.Button(self.toolbar, text="清除")
self.clear_btn.pack(side=tk.TOP)
# 设置默认工具
self.current_tool = "pen"
# 绑定事件
self.canvas.bind("<B1-Motion>", self.draw)
self.pen_btn.config(command=lambda: self.set_tool("pen"))
self.line_btn.config(command=lambda: self.set_tool("line"))
self.rect_btn.config(command=lambda: self.set_tool("rect"))
self.oval_btn.config(command=lambda: self.set_tool("oval"))
self.clear_btn.config(command=self.clear)
def draw(self, event):
if self.current_tool == "pen":
self.canvas.create_oval(event.x, event.y, event.x+5, event.y+5, fill="black")
elif self.current_tool == "line":
self.canvas.create_line(event.x, event.y, event.x+10, event.y+10, fill="black")
elif self.current_tool == "rect":
self.canvas.create_rectangle(event.x, event.y, event.x+20, event.y+20, fill="black")
elif self.current_tool == "oval":
self.canvas.create_oval(event.x, event.y, event.x+30, event.y+15, fill="black")
def set_tool(self, tool):
self.current_tool = tool
def clear(self):
self.canvas.delete("all")
if __name__ == "__main__":
root = tk.Tk()
app = PaintApp(root)
root.mainloop()
```
这个程序创建了一个窗口,左侧是画布,右侧是工具栏,可以选择不同的工具进行绘画,支持画笔、直线、矩形、椭圆等基本绘图功能。
阅读全文