Home > OS >  tuple index out of range when calling create_image on a Canvas object
tuple index out of range when calling create_image on a Canvas object

Time:01-29

I am running a program with tkinter. I have put my code below as well as the error I'm facing:

from tkinter import *

window = Tk()
window.title("The password generator")
canvas = Canvas(width=200, height=200)
photo = PhotoImage(file="logo.png")
canvas.create_image(x=100, y=100, image=photo)
canvas.pack()

window.mainloop()

I am not able to get a window with an image, every time I run it I get:

Traceback (most recent call last):
  File "C:\Users\shaun\Downloads\password-manager-start\main.py", line 11, in <module>
    canvas.create_image(x=100,y=100,image=photo)
  File "C:\Users\shaun\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2790, in create_image
    return self._create('image', args, kw)
  File "C:\Users\shaun\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2771, in _create
    cnf = args[-1]
IndexError: tuple index out of range

CodePudding user response:

By carefully inspecting the error trace, something problematic can be noticed. The create_image function is:

def create_image(self, *args, **kw):
    """Create image item with coordinates x1,y1."""
    return self._create('image', args, kw)

So all positional arguments are packed into an args tuple and all key-word arguments are packed into the kw dict. Then, they are passed as-is to the _create function, without unpacking.

The way you call the function, canvas.create_image(x=100, y=100, image=photo), means that you only pass key-word arguments, and no positionals. This means that args will be an empty tuple. Further ahead, _create expects some arguments in the args tuple which it doesn't find in this line:

cnf = args[-1]

To overcome this, simply pass x and y as positionals:

canvas.create_image(100, 100, image=photo)

This way they are packed into the args tuple and not the kw dict and _create can access the last item of that tuple.

  •  Tags:  
  • Related