python - 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()
解决方案
PhotoImage
从改变
PhotoImage('E:\\v1.1\\import.png')
至
PhotoImage( file = 'E:\\v1.1\\import.png')
推荐阅读
- java - 嵌入式 Jetty 在优雅终止期间关闭打开的连接
- node.js - 如何使用 node.js 应用程序中的内部存储位置从 Firebase 存储中获取 DownloadableURL?
- javascript - 有没有更好的方法从 JavaScript event.target 对象中获取选择器字符串?
- java - 生成一个三位数字Java
- laravel-5.7 - 如何获取包含所有帖子的身份验证追随者用户的帖子
- javascript - 如何在特定的基础上解析 BigInt?
- python - 未找到带有参数“(”,)”的“后详细信息”的反向
- python - 自定义模糊模糊字符串匹配以编辑距离 <= 1
- java - 无法访问类 com.sun.javafx.util.Utils(在模块 javafx.graphics 中)-JavaFX 和 Eclipse
- python - 对象是属性的命名集合?