簡體   English   中英

無法將圖像與 tkinter 標簽相關聯

[英]cannot associate image to tkinter label

我正在嘗試使用 tkinter.Label() 小部件向 tkinter GUI 顯示圖像。 過程看似簡單明了,但是這段代碼行不通!

代碼:

import Tkinter as tk
import Image, ImageTk, sys

filename = 'AP_icon.gif'
im = Image.open(filename) # Image is loaded, because the im.show() works

tkim = ImageTk.PhotoImage(im)

root = tk.Tk()

label = tk.Label(root, image = tkim) # Here is the core problem (see text for explanation)
label.image = tkim # This is where we should keep the reference, right?
label.grid (row = 0, column = 0)

tk.Button(root, text = 'quit', command = lambda: sys.exit()).grid(row = 1, column = 1)
root.mainloop()

當我們執行這段代碼時,它不會編譯,給出一個錯誤:

TclError: image "pyimage9" doesn't exist

當我在沒有父root情況下定義label時,不會發生編譯錯誤,但 GUI 不顯示任何圖像!

誰能確定可能是什么問題?

當我們嘗試在 Ipython 中運行上述代碼時會發生此問題。 並且可以通過換行解決

root = tk.Tk() to

root = tk.Toplevel()

在調用任何其他 tkinter 函數之前,您需要創建根小部件。 root的創建移動到鏡像創建之前。

我用來在 tkinter 中顯示圖像的一般方法是:

import Tkinter as tk
root = tk.Tk()
image1 = tk.PhotoImage(file = 'name of image.gif')
# If image is stored in the same place as the python code file,
# otherwise you can have the directory of the image file.
label = tk.Label(image = image1)
label.image = image1 # yes can keep a reference - good!
label.pack()
root.mainloop()

在上述情況下它有效,但您有類似的東西:

import Tkinter as tk
image = tk.PhotoImage(file = 'DreamPizzas.gif') #here this is before root = tk.Tk()
root = tk.Tk()
# If image is stored in the same place as the python code file,
# otherwise you can have the directory of the image file.
label = tk.Label(image = image)
label.image = image
label.pack()
root.mainloop()

這給了我一個runtime error: too early to create image.

但是你說你的錯誤是image pyimage9不存在,這很奇怪,因為在頂部你已經將filename設置為“AP_icon.gif”,所以你會認為你得到了一個不同的錯誤,因為我不知道pyimage9來自哪里從。 這讓我覺得也許你在某處得到的文件名不正確? 您還需要將root = tk.Tk()移動到導入下的頂部。

重新啟動內核以擺脫錯誤“TclError:圖像“pyimage9”不存在”

嘗試以下代碼,因為我能夠糾正相同的錯誤:

window=Tk()
c=Canvas(window,height=2000,width=2000)
p=PhotoImage(file='flower1.gif',master = c)
c.create_image(500,500,image=p)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM