canvas画布
canvas画布是一个矩形区域, 可以放置图形,图像,组件等
1 # coding:utf-8 2 from tkinter import * 3 from tkinter import messagebox 4 import random 5 6 7 class Application(Frame): 8 """一个经典的GUI程序类写法""" 9 def __init__(self, master=None): 10 super().__init__(master) # super代表的是父类的定义,而不是父类的对象 11 self.master = master 12 self.pack() 13 self.createWidget() 14 15 def createWidget(self): 16 self.canvas = Canvas(self, width=200, height=300, bg='skyblue') 17 self.canvas.pack() 18 # 画一条直线 19 line = self.canvas.create_line(10, 10, 20, 70, 70, 70) 20 # 画一个矩形 21 rect = self.canvas.create_rectangle(50, 50, 70, 70) 22 # 画一个椭圆 23 oval = self.canvas.create_oval(50, 50, 70, 70) 24 25 Button(self, text='画十个矩形', command=self.drew).pack(side='left') 26 27 def drew(self): 28 for i in range(0, 10): 29 x1 = random.randrange(int(self.canvas['width'])/2) 30 y1 = random.randrange(int(self.canvas['height'])/2) 31 x2 = x1 + random.randrange(int(self.canvas['width'])/2) 32 y2 = y1 + random.randrange(int(self.canvas['height'])/2) 33 self.canvas.create_rectangle(x1, y1, x2, y2) 34 35 36 if __name__ == "__main__": 37 root = Tk() 38 root.geometry("400x350+200+300") 39 root.title('canvas') 40 app = Application(master=root) 41 root.mainloop()