【问题标题】:Displaying Image with Tkinter Using Label Widget使用标签小部件使用 Tkinter 显示图像
【发布时间】:2018-08-13 14:55:27
【问题描述】:

我正在尝试在 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。

【问题讨论】:

  • 尝试将 img.convert('1').tobitmap() 的结果保存到一个新变量中,并将该变量用作 setParms() 的输入
  • 谢谢,但我得到了同样的错误。

标签: python image tkinter


【解决方案1】:

我明白了。事实证明,图像需要是照片图像。这是有效的:

window.setParms(password,PIL.ImageTk.PhotoImage(img))

【讨论】:

    【解决方案2】:

    试试这个:

    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

    希望对你有帮助,再见:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      • 2020-08-24
      • 1970-01-01
      • 2019-09-16
      • 2021-10-01
      相关资源
      最近更新 更多