绘制直线

 1 from tkinter import *
 2 
 3 win_width = 900
 4 win_height = 500
 5 
 6 
 7 class Application(Frame):
 8 
 9     def __init__(self, master=None, bgcolor='#000000'):
10         super().__init__(master)
11         self.master = master
12         self.bgcolor = bgcolor
13         self.pack()
14         self.x = 0
15         self.y = 0
16         self.startDrawFlag = False
17         self.lastDraw = 0
18         self.fgcolor = '#ff0000'
19         self.createWidget()
20 
21     def createWidget(self):
22         # 创建绘图区
23         self.drawpad = Canvas(root, width=win_width, height=win_height*0.9, bg=self.bgcolor)
24         self.drawpad.pack()
25 
26         btn_start = Button(root, text='开始', name='start')
27         btn_start.pack(side='left', padx='10')
28         btn_pen = Button(root, text='画笔', name='pen')
29         btn_pen.pack(side='left', padx='10')
30         btn_rect = Button(root, text='矩形', name='rect')
31         btn_rect.pack(side='left', padx='10')
32         btn_clear = Button(root, text='清屏', name='clear')
33         btn_clear.pack(side='left', padx='10')
34         btn_earser = Button(root, text='橡皮擦', name='earser')
35         btn_earser.pack(side='left', padx='10')
36         btn_line = Button(root, text='直线', name='line')
37         btn_line.pack(side='left', padx='10')
38         btn_lineArrow = Button(root, text='箭头', name='lineArrow')
39         btn_lineArrow.pack(side='left', padx='10')
40         btn_color = Button(root, text='颜色', name='color')
41         btn_color.pack(side='left', padx='10')
42 
43         btn_pen.bind_class('Button', '<1>', self.eventManager)
44         self.drawpad.bind('<ButtonRelease-1>', self.stopDraw)
45 
46 
47     def eventManager(self, event):
48         name = event.widget.winfo_name()
49         print(name)
50         if name == 'line':
51             self.drawpad.bind('<B1-Motion>', self.myline)
52 
53     def stopDraw(self, event):
54         self.startDrawFlag = False
55         self.lastDraw = 0
56 
57     def myline(self, event):
58         self.drawpad.delete(self.lastDraw)
59         self.lastDraw = self.drawpad.create_line(self.x, self.y, event.x, event.y, fill=self.fgcolor)
60         if not self.startDrawFlag:
61             self.startDrawFlag = True
62             self.x = event.x
63             self.y = event.y
64 
65 
66 
67 if __name__ == '__main__':
68     root = Tk()
69     root.geometry(str(win_width)+'x'+str(win_height)+'+100+100')
70     root.title('绘图')
71     app = Application(master=root)
72     root.mainloop()