|
| 1 | +from tkinter import * |
| 2 | +from tkinter.colorchooser import askcolor |
| 3 | + |
| 4 | +class Paint(object): |
| 5 | + DEFAULT_PEN_SIZE=5.0 |
| 6 | + DEFAULT_COLOR='black' |
| 7 | + |
| 8 | + def __init__ (self): |
| 9 | + self.root=Tk() |
| 10 | + |
| 11 | + self.pen_button=Button(self.root,text='Pen',command=self.use_pen) |
| 12 | + self.pen_button.grid(row=0,column=0) |
| 13 | + |
| 14 | + self.brush_button=Button(self.root,text='Brush',command=self.use_brush) |
| 15 | + self.brush_button.grid(row=0,column=1) |
| 16 | + |
| 17 | + self.color_button=Button(self.root,text='Color',command=self.choose_color) |
| 18 | + self.color_button.grid(row=0,column=2) |
| 19 | + |
| 20 | + self.eraser_button=Button(self.root,text='Eraser',command=self.use_eraser) |
| 21 | + self.eraser_button.grid(row=0,column=3) |
| 22 | + |
| 23 | + self.choose_size_button=Scale(self.root,from_=1,to=10,orient=HORIZONTAL) |
| 24 | + self.choose_size_button.grid(row=0,column=4) |
| 25 | + |
| 26 | + self.c=Canvas(self.root,bg='white',width=1000, height=1000) |
| 27 | + self.c.grid(row=1,columnspan=5) |
| 28 | + |
| 29 | + self.setup() |
| 30 | + self.root.mainloop() |
| 31 | + |
| 32 | + def setup(self): |
| 33 | + self.old_x=None |
| 34 | + self.old_y=None |
| 35 | + self.line_width=self.choose_size_button.get() |
| 36 | + self.color=self.DEFAULT_COLOR |
| 37 | + self.eraser_on=False |
| 38 | + self.active_button=self.pen_button |
| 39 | + self.c.bind('<B1-Motion>',self.paint) |
| 40 | + self.c.bind('<ButtonRelease-1>',self.reset) |
| 41 | + |
| 42 | + |
| 43 | + def use_pen(self): |
| 44 | + self.activate_button(self.pen_button) |
| 45 | + |
| 46 | + def use_brush(self): |
| 47 | + self.activate_button(self.brush_button) |
| 48 | + |
| 49 | + def choose_color(self): |
| 50 | + self.eraser_on=False |
| 51 | + self.color=askcolor(color=self.color)[1] |
| 52 | + |
| 53 | + def use_eraser(self): |
| 54 | + self.activate_button(self.eraser_button) |
| 55 | + |
| 56 | + |
| 57 | + def activate_button(self,some_button,eraser_mode=False): |
| 58 | + self.activate_button.config(relief=RAISED) |
| 59 | + some_button.config(relief=SUNKEN) |
| 60 | + self.activate_button=some_button |
| 61 | + self.eraser_on=eraser_mode |
| 62 | + |
| 63 | + |
| 64 | + def paint(self,event): |
| 65 | + self.line_width=self.choose_size_button.get() |
| 66 | + paint_color='white' if self.eraser_on else self.color |
| 67 | + if self.old_x and self.old_y: |
| 68 | + self.c.create_line(self.old_x,self.old_y,event.x,event.y,width=self.line_width,fill=paint_color,capstyle=ROUND,smooth=TRUE,splinesteps=36) |
| 69 | + self.old_x=event.x |
| 70 | + self.old_y=event.y |
| 71 | + |
| 72 | + def reset(self,event): |
| 73 | + self.old_x,self.old_y=None,None |
| 74 | + |
| 75 | + |
| 76 | + |
| 77 | +if __name__=='__main__': |
| 78 | + Paint() |
| 79 | + |
0 commit comments