使用random.choice时,元组索引超出范围错误

时间:2015-04-07 16:39:23

标签: python canvas random tkinter tuples

在尝试创建随机大小的矩形时,我似乎遇到了这个“元组索引超出范围错误”。在此之前,我只将颜色设置为随机并且有效。但是,当我尝试将坐标设置为随机时,我收到错误,画布上没有任何内容。有什么东西我不见了吗?

from tkinter import *
root = Tk()
import random

canvas = Canvas(root, width=550, height=400)
canvas.pack()

coord = [30, 40, 130, 140]
color = ["red", "orange", "yellow", "green", "blue", "violet"]

for j in range(10):
    rectangle = canvas.create_rectangle(x0 = random.choice(coord) +j*5,
                                        y0 = random.choice(coord)+j*5,
                                        x1 = random.choice(coord)+j*5,
                                        y1 = random.choice(coord)+j*5,
                                        outline="black",
                                        fill = random.choice(color))

1 个答案:

答案 0 :(得分:1)

删除x0 =,y0 = ...

for j in range(10):
    rectangle = canvas.create_rectangle(random.choice(coord) +j*5,
                                    random.choice(coord)+j*5,
                                    random.choice(coord)+j*5,
                                    random.choice(coord)+j*5,
                                    outline="black",
                                    fill = random.choice(color))