如何将JPEG图像插入python Tkinter窗口?

Aar*_*sau 18 python jpeg window image tkinter

如何将JPEG图像插入Python 2.7 Tkinter窗口?以下代码有什么问题?该图像称为Aaron.jpg.

#!/usr/bin/python

import Image
import Tkinter
window = Tkinter.Tk()

window.title("Join")
window.geometry("300x300")
window.configure(background='grey')

imageFile = "Aaron.jpg"

window.im1 = Image.open(imageFile)


raw_input()
window.mainloop()
Run Code Online (Sandbox Code Playgroud)

Nor*_*Cat 43

试试这个:

import tkinter as tk
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')

path = "Aaron.jpg"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img = ImageTk.PhotoImage(Image.open(path))

#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)

#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")

#Start the GUI
window.mainloop()
Run Code Online (Sandbox Code Playgroud)

相关文档:ImageTk模块,Tkinter标签小工具,Tkinter包几何管理器

  • 请注意,原始PIL不适用于Python 3,但Pillow几乎是一个替代品:https://pillow.readthedocs.io/en/latest/index.html (7认同)
  • 请注意,包含图像的其他“弹出”窗口也需要在 Label 实例化之外指定图像(例如 `label = tk.Label(window, image=img)`,然后在最后之前指定 `label.image = img` `label.pack()`) (5认同)
  • 回复 @Caspar 的评论,在 Python 3(.6) 的命令行中,执行 `pip installpillow` 来获取模块。 (2认同)