如何在Tkinter中添加图像?

2024-04-26 04:32:10 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Tkinter中添加图像?

这给了我一个语法错误:

root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()

Tags: path图像imageimgtkinterrootopenlabel
3条回答

以下代码适用于我的机器

  1. 您的代码中可能缺少某些内容。
  2. 请同时检查代码文件的编码。
  3. 确保安装了PIL包

    import Tkinter as tk
    from PIL import ImageTk, Image
    
    path = 'C:/xxxx/xxxx.jpg'
    
    root = tk.Tk()
    img = ImageTk.PhotoImage(Image.open(path))
    panel = tk.Label(root, image = img)
    panel.pack(side = "bottom", fill = "both", expand = "yes")
    root.mainloop()
    

上面的代码中没有“语法错误”-它可能出现在另一行(上面并不是所有代码,因为没有导入,也没有声明path变量),或者您得到了其他错误类型。

上面的例子对我来说很好,在交互式解释器上进行了测试。

Python 3.3.1[MSC v.1600 32位(Intel)]2013年5月14日在win32上

通过遵循上面的代码,这对我有效

from tkinter import *
from PIL import ImageTk, Image
import os

root = Tk()
img = ImageTk.PhotoImage(Image.open("True1.gif"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()

相关问题 更多 >