首页 > 解决方案 > Photoimage 无法在导入的类上加载图像

问题描述

我正在用 Tkinter 制作一个程序,我决定使用图像按钮以便于交互,但 PhotoImage 不知何故不起作用。该脚本的代码示例包含图像按钮:

from tkinter import *

class test:
    def __init__(self,master):
        self.master = master
        img = PhotoImage(r'E:\v1.1\import.png')
        b1 = Button(self.master, image = img).pack()

包含将加载上述脚本的源代码的脚本:

from test2 import *
maingui = Tk() 
gui = test(maingui) 
maingui.mainloop()

不知何故,图像没有加载,留下非常小的按钮。有人知道我有什么问题吗?

编辑 1:我已经尝试过这个解决方案(acw1668 提到)并编辑了第一个脚本的代码,但它不起作用

from tkinter import *

class test:
    def __init__(self,master):
        global img
        self.master = master
        img = PhotoImage('E:\\v1.1\\import.png')
        imglabel = Label(image=img)
        imglabel.image = img
        imglabel.pack()

        b1 = Button(self.master, image = img).pack()

结果与您在链接 [1] 上看到的相同:https ://i.stack.imgur.com/Mo1XH.png

编辑 2:我试图添加 self. 进入 img 和 imglabel 但它也不起作用。

from tkinter import *

class test:
    def __init__(self,master):
    # I cannot global self.img so I have to delete it
        self.master = master
        self.img = PhotoImage('E:\\v1.1\\import.png')
        self.imglabel = Label(image=img)
        self.imglabel.image = self.img
        self.imglabel.pack()

        self.b1 = Button(self.master, image = self.img).pack()

标签: pythontkinter

解决方案


PhotoImage从改变

PhotoImage('E:\\v1.1\\import.png')

PhotoImage( file = 'E:\\v1.1\\import.png')

推荐阅读