gpt4 book ai didi

python - 当列表索引不能超出范围时,为什么会出现 IndexError : list index out of range.?

转载 作者:太空宇宙 更新时间:2023-11-04 03:40:21 26 4
gpt4 key购买 nike

我一直在构建一个骰子游戏,当我到达为每个 Tkinter 标签分配图像以便显示骰子的部分时,我开始收到此错误:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
return self.func(*args)
File "C:/Users/Logan/Desktop/Dice/dicelab2.py", line 56, in rollDice
self.dice[i].roll()
File "C:/Users/Logan/Desktop/Dice/dicelab2.py", line 35, in roll
self.display.config(image=Photolist[self.value-1])
IndexError: list index out of range

现在列表中有 6 个条目,我从自己调用它。值(value)。 Self.value 应该是 1 到 6 之间的随机整数。在我调用它之前,我减去 1 以便它应该在 Photolist 的索引内。还有什么可能导致此错误?这是我的代码:

import Tkinter
import random
Photolist=[]

class Die:

def __init__(self,frame):
self.value = random.randint(1,6)
print self.value
photo1=Tkinter.PhotoImage(file="1.gif")
photo2=Tkinter.PhotoImage(file="2.gif")
photo3=Tkinter.PhotoImage(file="3.gif")
photo4=Tkinter.PhotoImage(file="4.gif")
photo5=Tkinter.PhotoImage(file="5.gif")
photo6=Tkinter.PhotoImage(file="6.gif")

Photolist=[photo1,photo2,photo3,photo4,photo5,photo6]

self.display = Tkinter.Label(frame,
image=Photolist[self.value-1],
font=('Courier New',30),
relief='ridge',
borderwidth=5,
bg='white')
self.display.pack(side='left')

def roll(self):
self.value = random.randint(1,6)
print self.value
self.display.config(image=Photolist[self.value-1])

class DiceRoller:
def __init__(self):
gameWin = Tkinter.Tk()
gameWin.title('Dice Roller')
diceFrame = Tkinter.Frame(gameWin)
self.dice = [ ]
for i in range(5):
self.dice.append(Die(diceFrame))

rollBtn = Tkinter.Button(gameWin,
text='Roll Again',
command=self.rollDice,
font=('Courier New',30))
diceFrame.pack()
rollBtn.pack(side='bottom')
gameWin.mainloop()

def rollDice(self):
for i in range(5):
self.dice[i].roll()


dice = DiceRoller()
dice

最佳答案

import Tkinter
import random
# PhotoList = [] you are accessing this

class Die(object):
def __init__(self,frame):
self.value = random.randint(1,6)
print self.value
photo1=Tkinter.PhotoImage(file="1.gif")
photo2=Tkinter.PhotoImage(file="2.gif")
photo3=Tkinter.PhotoImage(file="3.gif")
photo4=Tkinter.PhotoImage(file="4.gif")
photo5=Tkinter.PhotoImage(file="5.gif")
photo6=Tkinter.PhotoImage(file="6.gif")
# make it an attribute
self.Photolist=[photo1,photo2,photo3,photo4,photo5,photo6]

self.display = Tkinter.Label(frame,
image=self.Photolist[self.value-1],
font=('Courier New',30),
relief='ridge',
borderwidth=5,
bg='white')
self.display.pack(side='left')

def roll(self):
self.value = random.randint(1,6)
print self.value
self.display.config(image=self.Photolist[self.value-1])

在你的代码中你有 Photolist = [] 所以你试图访问那个空列表而不是你类中的那个,我将它更改为一个属性所以你现在应该没有问题

关于python - 当列表索引不能超出范围时,为什么会出现 IndexError : list index out of range.?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26811694/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com