在16章图形中,设计随机彩圈程序时出现以下错误
TypeError: 'dict_keys' object does not support indexing
翻看资(百)料(度)后发现是python3返回的是dict_keys对象,支持iterable 但不支持indexable,所以需要将XX.keys()先转换为list(XX.keys())再进行其他处理,以下是随机彩圈的代码:
import pygame,sys,random
from pygame.color import THECOLORS
pygame.init()
screen=pygame.display.set_mode([640,480])
screen.fill([255,255,255])
for i in range(100):
width=random.randint(0,250)
height=random.randint(0,100)
top=random.randint(0,400)
left=random.randint(0,500)
color_name=random.choice(list(THECOLORS.keys()))
color=THECOLORS[color_name]
line_width=random.randint(3,5)
pygame.draw.rect(screen,color,[left,top,width,height],line_width)
pygame.display.flip()
running=True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
pygame.quit()