|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 张育玮 于 2020-11-14 13:30 编辑 - from tkinter import *
- from tkinter.colorchooser import *
- root = Tk()
- root.configure(background="gray")
- instruction = Label(root,text="用鼠标左键在画布上画画吧",background= "gray")
- instruction.pack() # 1
- colorButton = Button(root,text="选择颜色")
- colorButton.pack() # 2
- rectButten = Button(root,text="方形")
- rectButten.pack() # 3
- lineButton = Button(root,text="线条")
- lineButton.pack() # 4
- circleButton = Button(root,text="圆圈")
- circleButton.pack() # 5
- clearButton = Button(root,text="清除")
- clearButton.pack() # 6
- myCanvas = Canvas(root,width=400,height=300)
- myCanvas.pack() # 7
- myShape = "line" #使用myShape变量存储当前绘画的图形
- myColor = "black"
- def pen_down(event):
- global prevX
- global prevY
- prevX = event.x
- prevY = event.y
- myCanvas.bind("<ButtonPress-1>",pen_down)
- # 按下鼠标左键时,得到X、Y的坐标
- def draw (event):
- global prevX
- global prevY
- if myShape == "line":
- myCanvas.create_line(prevX,prevY,event.x,event.y,fill=myColor)
- prevX = event.x
- prevY = event.y
- myCanvas.bind("<B1-Motion>",draw)#当移动鼠标时,如果选择画线,就画线。
- def pen_up(event):
- if myShape == "circle":
- myCanvas.create_oval(prevX,prevY,event.x,event.y,fill=myColor)
- if myShape == "rectangle":
- myCanvas.create_rectangle(prevX,prevY,event.x,event.y,fill=myColor)
- myCanvas.bind("<ButtonRelease-1>",pen_up)
- #松开鼠标左键时,如果myShape里是圆形,就绘制圆形,松开鼠标左键时,如果myShape里是矩形,就绘制炬形。
- def pick_color(event):
- global myColor
- myColor = askcolor()
- myColor = myColor[1]
- colorButton.bind("<Button-1>",pick_color)
- def clear(event):
- myCanvas.delete(ALL)
- clearButton.bind("<Button-1>", clear)
- def set_line(event):
- global myShape
- myShape = "line"
- lineButton.bind("<Button-1>",set_line)
- #点击线条按钮时,设myShape为线条“line”
- def set_rect(event):
- global myShape
- myShape = "rectangle"
- rectButten.bind("<Button-1>",set_rect)
- #点击方形按钮,设myShape为矩形。
- def set_circle(event):
- global myShape
- myShape = "circle"
- circleButton.bind("<Button-1>",set_circle)
- mainloop()
复制代码 |
|