random_turtle_color借鉴this page.
import turtle, random
r = lambda: random.randint(0,255)
print('#%02X%02X%02X' % (r(),r(),r()))
turtle.width(10) #What does this line do?
length = 5
for count in range(100):
colors = (z) #I want the randomly generated hexadecimal color to be #the pen in the drawing
turtle.speed(0)
turtle.forward(length)
turtle.right(135)
length = length + 5
答案 0 :(得分:1)
您遗失的一个关键部分是告诉乌龟使用您通过turtle.pencolor()
生成的颜色。这是一个重写的例子:
import turtle
import random
color_values = [random.randrange(0, 256) for _ in 'rgb']
hex_string = '#{:02X}{:02X}{:02X}'.format(*color_values)
turtle.speed('fastest')
turtle.pencolor(hex_string) # Set the pen color
turtle.width(10) # Width in pixels of the lines drawn (constant)
length = 5 # Length in pixels of the lines drawn (grows)
for _ in range(100):
turtle.forward(length)
turtle.right(135)
length += 5
turtle.hideturtle()
turtle.done()
您不需要使用十六进制字符串来设置颜色,如果它们与颜色模式匹配,您可以直接传递颜色值。这是一个返工,它也可以在循环过程中改变颜色:
import turtle
import random
turtle.colormode(255)
turtle.speed('fastest')
turtle.width(10) # Width in pixels of the lines drawn (constant)
length = 5 # Length in pixels of the lines drawn (grows)
for _ in range(100):
color_values = [random.randrange(0, 256) for _ in 'rgb']
turtle.pencolor(color_values) # Set the pen color
turtle.forward(length)
turtle.right(135)
length += 5
turtle.hideturtle()
turtle.done()
<强>输出强>
答案 1 :(得分:1)
有关解释,请参阅以下代码中的注释:
import turtle, random
r = lambda: random.randint(0,255)
z = '#{:02X}{:02X}{:02X}'.format(r(),r(),r())
print(z)
length = 5
turtle.pen(fillcolor=z,pencolor=z,pensize=1) # pensize= width of drawed line (here 1 pixel)
turtle.begin_fill() # Called just before drawing a shape which is to be filled.
for _ in range(100): # without '_' unused numbers are generated
turtle.speed(0)
turtle.forward(length)
turtle.right(135)
length = length + 5
turtle.end_fill() # It's question of taste, but I like the filled figure better ...
turtle.done() # the turtle window will stay open
给出:
答案 2 :(得分:1)
你的问题引导我faker,这是一个生成随机数据的好方法,包括random colors,即:
import random
from faker import Faker
length = 1
for count in range(800):
turtle.width(random.randint(2, 15))
turtle.speed(200)
turtle.forward(length)
turtle.right(135)
turtle.left(2)
turtle.color(Faker().hex_color())
length = length + 15
注意:强>
turtle.width()
- 定义画笔的大小
答案 3 :(得分:0)
使用''.format()
代替print()
。如果您希望每次将z
分配行移动到for循环中时获得不同的颜色:
import turtle, random
r = lambda: random.randint(0,255)
z = '#{:02X}{:02X}{:02X}'.format(r(),r(),r())
turtle.width(10) #What does this line do?
length = 5
for count in range(100):
colors = (z) #I want the randomly generated hexadecimal color to be #the pen in the drawing
turtle.speed(0)
turtle.forward(length)
turtle.right(135)
length = length + 5