用python画随机颜色随机大小的正方形
新手练习
练习题目:用python画出随机颜色随机大小的正方形
基本知识:turtle库,random库
随机颜色,通过颜色的十六进制完成:
1 def random_color(): 2 color_list=['0','1','2','3','4','5','6','7','8','9', 3 'A','B','C','D','E','F'] 4 color = '' 5 #一个以“#”开头的6位十六进制数值表示一种颜色,所以要循环6次 6 for i in range(6): 7 #random.randint表示产生0~15的一个整数型随机数 8 color_number = color_list[random.randint(0,15)] 9 color += color_number 10 color = '#' +color 11 return color
随机大小:
def draw_square(size): #size表示正方形的边长 for i in range(4): turtle.forward(size) turtle.right(90) size = random.randrange(-200,200)
随机位置
#改变画笔起始点的位置 for i in range(20): x = random.randrange(-200,200) y = random.randrange(-200,200) turtle.penup() # goto(x,y)移动到x,y所确定的那个点上 turtle.goto(x,y) turtle.pendown()
具体总代码:
1 ''' 2 作者:唐梓文 3 版本:1.0 4 日期:08/05/2020 5 功能:随机的在画布画多个正方形,并涂色 6 7 ''' 8 9 import turtle 10 import random 11 12 def random_color(): 13 color_list=['0','1','2','3','4','5','6','7','8','9', 14 'A','B','C','D','E','F'] 15 color = '' 16 for i in range(6): 17 color_number = color_list[random.randint(0,15)] 18 color += color_number 19 color = '#' +color 20 return color 21 22 def draw_square(size): 23 for i in range(4): 24 turtle.forward(size) 25 turtle.right(90) 26 27 def main(): 28 for i in range(20): 29 x = random.randrange(-200,200) 30 y = random.randrange(-200,200) 31 turtle.penup() 32 # goto(x,y)移动到x,y所确定的那个点上 33 turtle.goto(x,y) 34 turtle.pendown() 35 36 # turtle.pencolor(random_color())正方形边框颜色随机 37 turtle.color(random_color()) 38 turtle.begin_fill() 39 size = random.randrange(-200,200) 40 draw_square(size) 41 turtle.end_fill() 42 43 turtle.exitonclick() 44 45 if __name__ =='__main__': 46 main()
实现效果图: