2016-01-08 45 views
-1

此特定代碼失敗,運行對於第一次迭代,但是,因爲它繼續它顯示以下錯誤:奔跑對於第一次迭代和在礦井的第二

Traceback (most recent call last): 

    File "test1.py", line 7, in <module> 

    if len((hex(s)[2:])) == 1: 

TypeError: 'str' object is not callable 

的代碼如下:

import turtle 

t = turtle.Turtle() 

s = 0 

z = 30 

for i in range(s,16777217):[enter image description here][1] 

    if len((hex(s)[2:])) == 1: 

     hex = '#' + '00000' + hex(s)[2:].upper() 

    elif len((hex(s)[2:])) == 2: 

     hex = '#' + '0000' + hex(s)[2:].upper() 

    elif len((hex(s)[2:])) == 3: 

     hex = '#' + '000' + hex(s)[2:].upper() 

    elif len((hex(s)[2:])) == 4: 

     hex = '#' + '00' + hex(s)[2:].upper() 

    elif len((hex(s)[2:])) == 5: 

     hex = '#' + '0' + hex(s)[2:].upper() 

    else: 

     hex = '#' + hex(s)[2:].upper() 

    t.color(hex) 

    t.circle(z) 

    s += 1 

    z += 1 

回答

3

在第一次迭代中,hex引用了一個內置函數,該函數以數字的十六進制表示。但隨後這條線跑...

hex = '#' + '00000' + hex(s)[2:].upper() 

而且永遠事後,hex不再指的是功能,而是指向開始以「#00000」的字符串。您無法調用字符串,因此在第二次迭代中嘗試執行hex(...)會導致崩潰。

爲避免這種命名衝突,請將您的hex變量的名稱更改爲其他名稱。

hex_val = '#' + '00000' + hex(s)[2:].upper() 
#or 
s = '#' + '00000' + hex(s)[2:].upper() 
#or 
Kevin = '#' + '00000' + hex(s)[2:].upper() 

...或者其他你喜歡的東西;除了hex

0

除了hexhex()問題是@Kevin很好地指出了(+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() 

enter image description here

如果我們想要一個典型的屏幕上最大化的顏色,我們切換到1024×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() 

enter image description here

我們仍然只顯示24位色彩範圍的10位。

相關問題