如何将图像放入函数定义中?

How to put an image inside a function definition?

我想在我的骰子函数中放置一张图片 如果有人能告诉我我需要添加什么以便我可以将图片作为页面的背景,我将不胜感激

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()

它向我显示的错误是:

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

实际上您的代码存在两个 个不同的问题。一个是您正在创建 Tk() 的多个实例,而不是 as @Bryan Oakley mentioned in a — create a Toplevel window 小部件。

另一个问题是您在函数中创建 PhotoImage,并且由于它是一个局部变量,因此当函数 returns 时它将被垃圾回收(参见 Why does Tkinter image not show up if created in a function? )

以下代码显示了如何解决这两个问题:

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()