【问题标题】:Python 3- How to retrieve an image from the web and display in a GUI using TKINTER?Python 3- 如何使用 TKINTER 从 Web 检索图像并在 GUI 中显示?
【发布时间】:2011-05-22 05:37:12
【问题描述】:

我想要一个功能,当单击按钮时,它将使用 URLLIB 从 Web 获取图像并使用 TKINTER 在 GUI 中显示它。

我是 URLLIB 和 TKINTER 的新手,所以我很难做到这一点。
试过这个,但显然不起作用,因为它使用文本框并且只会显示文本。

 def __init__(self, root):
    self.root = root
    self.root.title('Image Retrieval Program')
    self.init_widgets()


def init_widgets(self):
    self.btn = ttk.Button(self.root, command=self.get_url, text='Get Url', width=8)
    self.btn.grid(column=0, row=0, sticky='w')

    self.entry = ttk.Entry(self.root, width=60)
    self.entry.grid(column=0, row=0, sticky='e')

    self.txt = tkinter.Text(self.root, width=80, height=20)
    self.txt.grid(column=0, row=1, sticky='nwes')
    sb = ttk.Scrollbar(command=self.txt.yview, orient='vertical')
    sb.grid(column=1, row=1, sticky='ns')
    self.txt['yscrollcommand'] = sb.set

def get_url(self):
    s = urllib.request.urlretrieve("http://www.smellymonkey.com/monkeys/images/ill-monkey.gif", "dog.gif")
    tkimage = ImageTk.PhotoImage(im)
    self.txt.insert(tkinter.INSERT, s)

【问题讨论】:

    标签: python user-interface tkinter urllib


    【解决方案1】:

    我不使用 python 3,但我可以给出适用于 python 2.5+ 的答案。我假设代码在 python 3 上的工作方式几乎相同。

    在开始之前,我们需要导入 Tkinter 并创建根窗口:

    import Tkinter as tk
    root = tk.Tk()
    

    接下来,使用 urllib 下载图片:

    import urllib
    URL = "http://www.smellymonkey.com/monkeys/images/ill-monkey.gif"
    u = urllib.urlopen(URL)
    raw_data = u.read()
    u.close()
    

    您现在在变量raw_data 中获得了图像的二进制数据。 Tkinter 接受data 选项,但不幸的是,您无法将这些原始数据提供给它。它期望数据被编码为base64。这很容易做到:

    import base64
    b64_data = base64.encodestring(raw_data)
    image = tk.PhotoImage(data=b64_data)
    

    现在我们有了一张图片,是时候把它放到屏幕上了:

    label = tk.Label(image=image)
    label.pack()
    

    您现在应该在屏幕上看到图像。

    以上仅适用于 .gif 图像,但其他图像格式几乎同样易于处理。最简单的方法是将原始图像数据写入磁盘(或使用 urllib 直接将数据下载到文件中)并在创建PhotoImage 对象时引用该文件。当然,这只适用于PhotoImage 类直接支持的图像格式。

    您的另一个选择是使用支持多种不同图像格式的 PIL(Python 图像库)。该技术大致相同,只是您必须首先创建一个 PIL 图像,然后将其转换为 Tkinter 可用的格式。有关 PIL 的更多信息,请咨询 Python Imaging Library Handbookeffbot documentation on The Tkinter PhotoImage Class

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-14
      • 2023-03-09
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 2020-11-28
      相关资源
      最近更新 更多