一、Canvas画布练习
1)简单的绘制图框
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from tkinter import * # 构建一个窗口 tk = Tk() # 画布 canvas= Canvas(tk,width=400,height=400) # 单位像素 canvas.pack() def python(): # 槽函数 print("very good") btn = Button(tk,text="oldboyedu",command=python) # 显示窗口 btn.pack() canvas.create_arc(20,20,100,50,extent=145,style=ARC) # 20 20 100 50 145 # x轴 y轴 x走了100 y走了50 角度145 canvas.create_rectangle(10,10,50,50,fill="green") canvas.create_polygon(200,30,240,40,120,100,150,120,fill="red",outline="black") # 运行窗口 tk.mainloop()
2)循环随机绘制图框
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from tkinter import * import random # 构建一个窗口 tk = Tk() # 画布 canvas= Canvas(tk,width=400,height=400) # 单位像素 canvas.pack() myColor = ["red","orange","yellow","green","cyan","blue","purple"] def random_rectangle(width,height,myColor): x = random.randrange(width) y = random.randrange(width) x1 = x + random.randrange(height) y1 = y + random.randrange(height) canvas.create_rectangle(x,y,x1,y1,fill=myColor,stipple="gray12",outline=myColor,dash=10) # 循环200个随机矩形 for nums in range(100): random_rectangle(200,200,myColor[nums%7]) tk.mainloop()