循环使用文本对象填充框

2024-04-20 02:18:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python做一个“选择颜色而不是单词”的游戏。 有9种不同颜色的列表:

cnames = [" green ", " blue ", " yellow ", " gray ", " pink ", " orange ", " purple ", " red ", " brown "]

我编写了一个函数,它将这些颜色随机化:

def randomize():
    import random
    cnames=["green", "blue","yellow", "grey", "pink", "orange", "Purple", "red", "brown"]
    color=randint(0, len (cnames)-1)
    cname=randint(0, len(cnames)-1)

    from random import sample
    other_cnames=random.sample(range(len(cnames)),6)

    return (color, cname, other_cnames)

游戏窗口的代码是:

win=GraphWin("New_game", 800,800)
    color, cname, other_names=randomize()

    rcname=cnames[cname]
    rcname=rcname [0].upper() + rcname[1:]
    target=Text(Point(300,100),rcname)
    target.setOutline(cnames[color])
    target.setStyle ("bold")
    target.setSize(24)
    target.draw(win)

    Boxes=[]
    k=0

如何使循环用文本对象填充列表框,其中每个文本对象表示一种颜色和颜色的编号(0到8)?你知道吗

结果应该是这样的: enter image description here


Tags: 游戏targetlen颜色randomgreenbluecolor
2条回答

不完全确定您要的是什么,假设您要返回颜色和颜色列表,而不选择颜色。

cnames = ['green', 'blue'...]

从列表中选择一种颜色随机选择你知道吗

color = random.choice(cnames)

从新列表中获取其他颜色并按索引弹出

other_colors = list(cnames)
other_colors.pop(colors.index(color))

返回所选颜色和其他颜色

return color, other_colors

在graphwin

color, other_colors = randomize()

ucolor = '{0}{1}'.format(color[0].upper(), color[1:])
target = Text(Point(300,100),ucolor)
target.setOutline(color)
...
Boxes = other_colors # 

您可以使用for语句多次迭代代码以填充如下框:

for x in range(*insert number of boxes*): *put other code here*

如果你把范围放进去,这会填满的

相关问题 更多 >