【发布时间】:2017-10-25 13:50:00
【问题描述】:
我已经看到很多关于如何使用图像 URL 在 Tkinter 中显示图像的示例,但这些示例都不适用于我,即
import urllib
from Tkinter import *
import io
from PIL import Image, ImageTk
app = Tk()
app.geometry("1000x800")
im = None #<-- im is global
def search():
global im #<-- declar im as global, so that you can write to it
# not needed if you only want to read from global variable.
tx1get = tx1.get()
Label(app, text="You Entered: \"" + tx1get + "\"").grid(row=1, column=0)
fd = urllib.urlopen("http://ia.media-imdb.com/images/M/MV5BMTc2MTU4ODI5MF5BMl5BanBnXkFtZTcwODI2MzAyOA@@._V1_SY317_CR7,0,214,317_AL_.jpg")
imgFile = io.BytesIO(fd.read())
im = ImageTk.PhotoImage(Image.open(imgFile))
image = Label(app, image = im, bg = "blue")
image.grid(row=2, column=0)
tx1=StringVar()
tf = Entry(app, textvariable=tx1, width="100")
b1 = Button(app, text="Search", command=search, width="10")
tf.grid(row=0, column=0)
b1.grid(row=0, column=1)
app.mainloop()
当我运行此程序时,我收到错误“No module name PIL”并且在此:
from io import BytesIO
import urllib
import urllib.request
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
url = "http://imgs.xkcd.com/comics/python.png"
with urllib.request.urlopen(url) as u:
raw_data = u.read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label = tk.Label(image=image)
label.pack()
root.mainloop()
我收到“无模块名称请求”几乎所有示例都使用 PIL 模块等,但我无法让它们工作,因为 Python 2.7 无法识别其中的许多。我需要显示一个图像作为评估的一部分,虽然我们可以导入 Tkinter 等内容,但该文件需要运行,而无需从标准 Python 库之外添加模块。
值得注意的是,我什至无法导入“tkinter”。它会说没有名为“tkinter”的模块,因为它需要以大写的“T”开头。
所以我的问题是:
PIL 是否需要我安装其他软件/库
不带大写“T”的“tkinter”导入是否不起作用,因为我使用的是 Python 2.7?
使用 Python 2.7 如何在 Tkinter 窗口中从 URL 显示图像
【问题讨论】:
标签: image python-2.7 tkinter