【问题标题】:How to put an image inside a function definition?如何将图像放入函数定义中?
【发布时间】:2022-01-03 06:16:40
【问题描述】:

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

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 的实例。对于第二个窗口,您需要使用Toplevel。

标签: python image tkinter button


【解决方案1】:

实际上,您的代码存在 两个 不同的问题。一种是您正在创建Tk() 的多个实例,即problematic,正如@Bryan Oakley 在comment 中提到的那样——改为创建Toplevel 窗口小部件。

另一个问题是你在一个函数中创建了PhotoImage,因为它是一个局部变量,当函数返回时它会被垃圾回收(参见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()

【讨论】:

    猜你喜欢
    • 2015-09-30
    • 2014-12-03
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    相关资源
    最近更新 更多