首页 > 解决方案 > 使用标签小部件使用 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。

标签: pythonimagetkinter

解决方案


尝试这个:

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

希望它有帮助,再见:)


推荐阅读