By thomas.winckell


2013-05-07 16:30:03 8 Comments

This code works:

import tkinter

root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.grid(row = 0, column = 0)
photo = tkinter.PhotoImage(file = './test.gif')
canvas.create_image(0, 0, image=photo)
root.mainloop()

It shows me the image.

Now, this code compiles but it doesn't show me the image, and I don't know why, because it's the same code, in a class:

import tkinter

class Test:
    def __init__(self, master):
        canvas = tkinter.Canvas(master)
        canvas.grid(row = 0, column = 0)
        photo = tkinter.PhotoImage(file = './test.gif')
        canvas.create_image(0, 0, image=photo)

root = tkinter.Tk()
test = Test(root)
root.mainloop()

2 comments

@Gabriel 2019-03-01 00:45:49

Just add global photo as the first line inside the function.

@Aran-Fey 2019-06-19 20:09:05

And then you create a 2nd Test instance and the first instance loses its image. Congratulations.

@Bryan Oakley 2013-05-07 16:56:04

The variable photo is a local variable which gets garbage collected after the class is instantiated. Save a reference to the photo, for example:

self.photo = tkinter.PhotoImage(...)

If you do a Google search on "tkinter image doesn't display", the first result is this:

http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm

Related Questions

Sponsored Content

14 Answered Questions

2 Answered Questions

[SOLVED] ttk tkinter multiple frames/windows

1 Answered Questions

3 Answered Questions

[SOLVED] Why does Python code run faster in a function?

2 Answered Questions

[SOLVED] TkInter Frame doesn't load if another function is called

1 Answered Questions

[SOLVED] Tkinter: Why the perimeter of a rectangle grid is not showing?

1 Answered Questions

[SOLVED] Tkinter canvas doesn't show entire photo image

  • 2015-09-03 13:13:26
  • helloB
  • 5032 View
  • 3 Score
  • 1 Answer
  • Tags:   python tkinter

1 Answered Questions

[SOLVED] Using instance attributes to create images in tkinter

0 Answered Questions

Python tkinter image not showing up

1 Answered Questions

[SOLVED] tkinter canvas image is not displayed in class

  • 2013-05-30 21:52:14
  • konovalov100
  • 3772 View
  • 4 Score
  • 1 Answer
  • Tags:   python tkinter

Sponsored Content