我的这个特殊代码在第一次迭代时运行,但是,它继续显示以下错误:
break
代码如下:
Traceback (most recent call last):
File "test1.py", line 7, in <module>
if len((hex(s)[2:])) == 1:
TypeError: 'str' object is not callable
答案 0 :(得分:3)
在第一次迭代中,hex
指的是一个内置函数,它使数字的十六进制表示。但是这条线路运行......
hex = '#' + '00000' + hex(s)[2:].upper()
永远之后,hex
不再引用一个函数,而是指向一个以&#34;#00000&#34;开头的字符串。您无法调用字符串,因此在第二次迭代中尝试执行hex(...)
会导致崩溃。
要避免此命名冲突,请将hex
变量的名称更改为其他名称。
hex_val = '#' + '00000' + hex(s)[2:].upper()
#or
s = '#' + '00000' + hex(s)[2:].upper()
#or
Kevin = '#' + '00000' + hex(s)[2:].upper()
......或者你喜欢的任何其他东西;除hex
之外的所有内容。
答案 1 :(得分:0)
除了@Kevin很好地指出的hex
与hex()
问题(+1)之外,我不相信您的代码会达到目标,原因有以下几点:
您的最终目标应该是16777216,而不是16777217,因为该值 - 1不适合6位十六进制字符串;你的圆圈相对于原点是歪斜的;您的窗口不足以容纳您生成的颜色数量 - 您需要在for
循环中迈出明显大于1的步骤;您的代码需要很长时间才能完成,并且在此期间大部分时间都会脱离屏幕。
以下是我对代码的修改,解决了上述问题:
from turtle import Turtle, Screen
SIZE = 1000
LIMIT = 2 ** 24
INCREMENT = int(LIMIT / (2 ** 0.5 * SIZE / 2)) # fill to corners
screen = Screen()
screen.setup(SIZE, SIZE)
screen.tracer(0)
yertle = Turtle(visible=False)
yertle.speed('fastest')
for radius, n in enumerate(range(0, LIMIT, INCREMENT)):
my_hex = '#' + format(n, "06X")
yertle.color(my_hex)
yertle.penup()
yertle.sety(yertle.ycor() - 1)
yertle.pendown()
yertle.circle(radius)
screen.update() # only show completed circles
screen.exitonclick()
如果我们想在典型的屏幕上最大化颜色,我们切换到1024 x 1024窗口;不均匀地分配10位颜色但总是作为颜色值中的最高位;只绘制圆圈的一个象限:
from turtle import Turtle, Screen
SIZE = 2 ** 10
MASK_3 = 2 ** 3 - 1 # divide our 10 bits into three uneven
MASK_4 = 2 ** 4 - 1 # groups of r=3, g=3, b=4
screen = Screen()
screen.setup(SIZE + 8, SIZE + 8) # rough adjustment for borders
screen.tracer(0)
yertle = Turtle(visible=False)
yertle.speed('fastest')
yertle.penup()
yertle.goto(-SIZE // 2, -SIZE // 2) # center of circle is LL corner of window
yertle.pendown()
for radius in range(SIZE):
my_hex = "#{:01X}0{:01X}0{:01X}0".format(2 * ((radius // 2 ** 7) & MASK_3), 2 * ((radius // 2 ** 4) & MASK_3), radius & MASK_4)
yertle.color(my_hex)
yertle.penup()
yertle.sety(yertle.ycor() - 1)
yertle.pendown()
yertle.circle(radius)
screen.update() # only show completed arcs
screen.exitonclick()
我们仍然只显示24位颜色范围的10位。