python - 使用标签小部件使用 Tkinter 显示图像
问题描述
我正在尝试在 Tkinter 类中使用 PIL 显示图像:
class PasswordCheck(Frame):
def __init__(self,master=None):
Frame.__init__(self,master)
self.pack()
def create_widgets(self):
self.title=Label(self,text='Curretly using password')
self.pwfield=Entry(self,text=self.password)
self.web=Label(self,image=self.image)
self.ok=Button(self)
self.ok['text']='OK'
self.ok['command']=root.destroy
self.ok.pack(side='top')
self.quit=Button(self,text="Quit",command=root.destroy)
self.quit.pack(side='bottom')
def setParms(self,password,image):
self.password=password
self.image=image
我需要提一下我是 Tkinter 初学者。我从网站(使用 HTMLParser)创建图像并设置窗口:
with open(authFile,'r') as f:
lines=f.read().splitlines()
password=lines[1]
f=urllib.urlopen(URL)
parser=PWParser()
parser.feed(f.read())
response=requests.get(URL+imageURL.replace(" ","%20"))
img=PIL.Image.open(BytesIO(response.content))
root=Tk()
window=PasswordCheck(master=root)
window.setParms(password,img.convert('1').tobitmap())
window.create_widgets()
window.mainloop()
图像很好(img.show()),所以我将其转换为位图并将其传递给 Tkinter 类。当我运行脚本时,我收到一条错误消息,提示 static char image_bits[] = { ... 不存在:
(无法发布回溯,表单错误地认为它是格式不正确的代码,这里需要帮助)
我在几个地方读到了关于垃圾收集在图像显示之前摆脱图像的信息,但不清楚如何阻止它。如果这是原因,我如何防止“img”被删除或者还有其他问题?TIA。
解决方案
尝试这个:
import tkinter as tk
root = tk.Tk()
logo = tk.PhotoImage(file="program_logo.gif")
explanation = """At present, only GIF and PPM/PGM
formats are supported, but an interface
exists to allow additional image file
formats to be added easily."""
w = tk.Label(root,
compound = tk.CENTER,
text=explanation,
image=logo).pack(side="right")
root.mainloop()
program_logo.gif 是您的徽标,但为 .gif 文件。
我从这个网站得到它:https ://www.python-course.eu/tkinter_labels.php
希望它有帮助,再见:)
推荐阅读
- google-cloud-platform - Anthos GKE on Prem 上的 Apigee Hybrid
- java - 运算符 < 未定义参数类型 String, int ? 在java中
- java - 想要所有不在反引号或引号内的 %n 组
- reactjs - React Forward Ref 无法与自定义组件一起使用
- microsoft-teams - MS Teams - 自定义个人应用程序的深层链接在移动应用程序中返回“不支持链接”
- python-3.x - 如何加快包含正则表达式函数的复杂循环以在 Python 中构建数据框?
- sql - 仅使用一个命令(不使用多个 GO 语句)从 VB.net 应用程序强制 sql 缓存特定 sql 语句的查询计划
- azure-devops - AppCenter Google Play 部署
- canvas - Konva 缩放填充到舞台上的内容
- git - Git pull 没有用远程仓库填充我的本地文件夹?