Search code examples
pythonimagecanvaswindowtkinter

Image in tkinter window by clicking on button


I need help about this program, this program should open image in new tkinter window by clicking on button, but it doesn't it just opens new window without image. Where is the problem?

Using: python 3.3 and tkinter

This is program:

import sys
from tkinter import *


def button1():
    novi = Toplevel()
    canvas = Canvas(novi, width = 300, height = 200)
    canvas.pack(expand = YES, fill = BOTH)
    gif1 = PhotoImage(file = 'image.gif')
    canvas.create_image(50, 10, visual = gif1, anchor = NW)


mGui = Tk()
button1 = Button(mGui,text ='Sklop',command = button1, height=5, width=20).pack()

mGui.mainloop()

Solution

  • create_image needs a image argument, not visual to use the image, so instead of visual = gif1, you need image = gif1. The next problem is that you need to store the gif1 reference somewhere or else it'll get garbage collected and tkinter won't be able to use it anymore.

    So something like this:

    import sys
    from tkinter import * #or Tkinter if you're on Python2.7
    
    def button1():
        novi = Toplevel()
        canvas = Canvas(novi, width = 300, height = 200)
        canvas.pack(expand = YES, fill = BOTH)
        gif1 = PhotoImage(file = 'image.gif')
                                    #image not visual
        canvas.create_image(50, 10, image = gif1, anchor = NW)
        #assigned the gif1 to the canvas object
        canvas.gif1 = gif1
    
    
    mGui = Tk()
    button1 = Button(mGui,text ='Sklop',command = button1, height=5, width=20).pack()
    
    mGui.mainloop()
    

    It's also probably not a good idea to name your Button the same name as the function button1, that'll just cause confusion later on.