[英]Displaying Image with Tkinter Using Label Widget
我正在嘗試在 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。
我知道了。 事實證明,圖像需要是照片圖像。 這是有效的:
window.setParms(password,PIL.ImageTk.PhotoImage(img))
嘗試這個:
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
希望它有幫助,再見:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.