Home > Back-end >  How to put an image inside a function definition?
How to put an image inside a function definition?

Time:11-26

I want to put an image inside my dice function I would really appreciate if someone can tell me what I need to add so I can have the image as the background of the page

def dice():
    tk = Tk()
    tk.geometry('300x300')
    img = PhotoImage(file='dicee.gif')
    lb5 = Label(tk,image=img)
    lb5.pack()

btn4=Button(tk,text="Roll The Dice",command=dice)
btn4.place(x=110,y=130)
tk.mainloop()

The error it shows me is:

 self.tk.call(
   _tkinter.TclError: image "pyimage1" doesn't exist

CodePudding user response:

Actually there are two separate problems with your code. One is that you're creating multiple instances of Tk() which is problematic as @Bryan Oakley mentioned in a comment — create a Toplevel window widget instead.

The other issue is that you're creating the PhotoImage in a function, and since it's a local variable it will be garbage collected when the function returns (see Why does Tkinter image not show up if created in a function?)

Here's code showing how to fix both issues:

from tkinter import *

def dice():
    tk = Toplevel()  # Create new window.
    tk.geometry('300x300')
    img = PhotoImage(file='dicee.gif')
    lb5 = Label(tk, image=img)
    lb5.img = img  # Save reference to image.
    lb5.pack()

tk = Tk()
btn4 = Button(tk, text="Roll The Dice", command=dice)
btn4.place(x=110, y=130)
tk.mainloop()

  • Related