float在Python 3.2中没有int属性
我遇到了一个错误,提示“float没有int这个属性”。这个问题是要写一个函数,接收一个图片作为参数,然后在图片上画两条竖线,一条是红色的,从(50,0)到(50,300),另一条是由随机颜色的像素组成的,从(150,50)到(150,250)。奇怪的是,随机颜色的部分,我用的randomcolor.int(0,255)就出现了这个错误。是不是我需要转换什么东西?这是我的代码:
from cImage import*
import random
RandomColor = random.random()
myImWin = ImageWin("Line Image", 300, 300)
lineImage = EmptyImage(300,300)
redPixel = Pixel(255,0,0)
randomRed = Pixel(RandomColor.int(0,255))
for i in range(300):
for x in range(250):
lineImage.setPixel(50,i,redPixel)
randomRed.setPixel(150,x,randomRed)
lineImage.draw(myImWin)
randomRed.save("lineImage.gif")
任何建议都很有帮助,谢谢。
2 个回答
1
RandomColor
是通过 random.random()
得到的结果,这个结果是一个小数(也叫浮点数)。如果你想从中得到一个在 0 到 255 之间的整数,你应该使用 int(RandomColor*256)
,或者使用 random
模块里其他更具体的函数。
6
random.random()
会返回一个在 0.0 到 1.0 之间的随机小数(包括 0.0,但不包括 1.0)。如果你想要一个整数,就得这样做:
int(RandomColor) # would be 0 because random() is < 1.0
int(RandomColor * 256) # to get 0-255
如果你想要一个在 0 到 255 之间的随机数,那你是不是可以直接这样做:
random.randint(0,255)