from tkinter import * from tkinter.colorchooser import * # 创建一个窗口 window = Tk() # 设置背景颜色 window.configure(background='gray') # 创建解释说明性文字 instruction = Label(window, text='用鼠标左键在画布上画画', background='gray') # 把解释说明文字布局到窗口中 instruction.pack() # 创建颜色选择的标签 colorButton = Button(window, text='选择颜色') # 把颜色选择标签布局到窗口中 colorButton.pack() # 创建清空画布的标签 clearButton = Button(window, text='清除') # 布局到窗口 clearButton.pack() # 创建画布 宽度500 高度400 my_canvas = Canvas(window, width=500, height=400) # 把画布布局 my_canvas.pack() # 改变画笔颜色的程序 my_color = 'black' # 挑选颜色的函数 def pick_color(event): global my_color my_color = askcolor() my_color = my_color[1] colorButton.bind('<Button-1>', pick_color) # 清除画布的方法 def clear(event): my_canvas.delete(ALL) clearButton.bind('<Button-1>', clear) # 画线程序 def pen_down(event): global prevX global prevY prevX = event.x prevY = event.y my_canvas.bind('<ButtonPress-1>', pen_down) def draw(event): global prevX global prevY my_canvas.create_line(prevX, prevY, event.x, event.y, fill=my_color) prevX = event.x prevY = event.y my_canvas.bind('<B1-Motion>', draw) # 让窗口循环展示 window.mainloop()