【问题标题】:Tkinter error - Tuple index out of rangeTkinter 错误 - 元组索引超出范围
【发布时间】:2015-04-23 22:12:43
【问题描述】:

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

#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

请帮忙!

【问题讨论】:

  • 您能否向我们展示实际的异常(如果已打印,则带有完整的回溯),而不仅仅是向我们描述它吗?另外,你什么时候得到异常?在至少不知道它出现在哪一行的情况下,解决这个问题的唯一方法是阅读所有代码并尝试猜测您可能在哪里犯了错误。
  • 同时,这是对类的一种非常奇怪的用法。您根本没有真正将Character_sprite 用作一个类,而只是将三个单独的函数转储到其中的垃圾箱。
  • 我添加了错误以更清楚地说明问题所在

标签: python tkinter


【解决方案1】:

问题是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 参数。

【讨论】:

  • 非常感谢!现在我不再遇到以前的错误了。但是现在我有一个逻辑错误,图像只是不会移动。这次我会在寻求帮助之前做更多的研究。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-10
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多