【问题标题】:How to add a URL image to Tkinter in Python 2.7 using only the standard Python library?如何仅使用标准 Python 库在 Python 2.7 中将 URL 图像添加到 Tkinter?
【发布时间】: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”开头。

所以我的问题是:

  1. PIL 是否需要我安装其他软件/库

  2. 不带大写“T”的“tkinter”导入是否不起作用,因为我使用的是 Python 2.7?

  3. 使用 Python 2.7 如何在 Tkinter 窗口中从 URL 显示图像

【问题讨论】:

    标签: image python-2.7 tkinter


    【解决方案1】:

    这可行,在 windows 上使用 python 2.7:

    from io import BytesIO
    import Tkinter as tk
    import urllib  # not urllib.request
    from PIL import Image, ImageTk
    
    root = tk.Tk()
    url = "http://imgs.xkcd.com/comics/python.png"
    
    u = urllib.urlopen(url)
    raw_data = u.read()
    u.close()
    
    im = Image.open(BytesIO(raw_data))
    image = ImageTk.PhotoImage(im)
    label = tk.Label(image=image)
    label.pack()
    root.mainloop()
    

    回答您的问题:

    1. 您需要安装 PIL(它不是 Python 2.7 的标准)。
    2. 是的,需要在Python 2.7中导入Tkintertkinter 适用于 Python 3.x
    3. 您可以使用上面的代码(前提是您安装了 PIL)。

    还有,

    1. 在 Python 2.7 中,您需要 urllib 而不是 urllib.request
    2. 看来你不能在 urllib 中使用with....open(x) as fname所以你需要明确地打开和关闭文件。

    【讨论】:

    • 好的,感谢您的反馈。我将不得不在没有图像的情况下这样做,因为它是为了分配,并且我不允许安装库。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2014-05-08
    • 1970-01-01
    相关资源
    最近更新 更多