Tkinter错误 - 元组索引超出范围

时间:2015-04-23 22:12:44

标签: python tkinter

这个程序应该在画布上放一个精灵,供用户使用左右箭头键进行控制,但我不断得到一个超出范围的元组索引错误,我的程序中没有任何元组。我知道我正确导入了图片,所以它可能与按键事件有关。

#4/22/15
#Test game, user controlled sprite
import random
from Tkinter import *
import Tkinter
from PIL import Image, ImageTk

root = Tk()
root.geometry('700x600')

canvas = Canvas(root,width=700,height=600,bg='white')
canvas.place(x=0,y=0)

class Character_sprite(object):
    '''Creates the users sprite and handles the events'''
    def __init__(self):
        self.im = Image.open('grey_mario_mushroom_sprite.png')
        self.tkimage = ImageTk.PhotoImage(self.im)
        self.char_sprite = canvas.create_image(image=self.tkimage)

    def moveLeft(event):
        '''Handles the left arrow key press event, moves char_sprite to the left'''
        canvas.move(self.char_sprite,-20,0)
        canvas.update()
    def moveRight(event):
        '''Handles the right arrow key press event, moves the char_sprite to the right'''
        canvas.move(self.char_sprite,20,0)
        canvas.update()


root.bind('<Left>', Character_sprite.moveLeft)
root.bind('<Right>', Character_sprite.moveRight)
Character_sprite()
root.mainloop()

这是错误:

Traceback (most recent call last):
  File "C:\Users\Calvin\Documents\Python Programs\Test_game_example.py", line 57, in <module>
    Character_sprite()
  File "C:\Users\Calvin\Documents\Python Programs\Test_game_example.py", line 36, in __init__
    self.char_sprite = canvas.create_image(image=self.tkimage)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 2310, in create_image
    return self._create('image', args, kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 2294, in _create
    cnf = args[-1]
IndexError: tuple index out of range

请帮忙!

1 个答案:

答案 0 :(得分:4)

问题是create_image需要position。像这样:

self.char_sprite = canvas.create_image((0, 0), image=self.tkimage)

如果以更友好的方式定义了Tkinter,则会收到更友好的错误消息:

>>> def create_image(position, **options):
...     pass
>>> create_image(image=0)
TypeError: create_image() takes exactly 1 argument (0 given)

不幸的是,Tkinter通常有点复杂,所以它的定义更像是这样:

>>> def create_image(*args, **options):
...     position = args[-1]
...     pass

因此,您会收到一条不太有用的错误消息。 *args最终为空元组,因此position = args[-1]会引发IndexError。当然,变量甚至不是position,而是cnf,它无助于您理解问题。

但这是同样的问题。您忘记传递position参数。