python使用Tkinter显示网络图片的方法

yipeiwu_com5年前Python基础

本文实例讲述了python使用Tkinter显示网络图片的方法。分享给大家供大家参考。具体实现方法如下:

''' tk_image_view_url_io.py
display an image from a URL using Tkinter, PIL and data_stream
tested with Python27 and Python33 by vegaseat 01mar2013
'''
import io
# allows for image formats other than gif
from PIL import Image, ImageTk
try:
  # Python2
  import Tkinter as tk
  from urllib2 import urlopen
except ImportError:
  # Python3
  import tkinter as tk
  from urllib.request import urlopen
root = tk.Tk()
# find yourself a picture on an internet web page you like
# (right click on the picture, under properties copy the address)
#url = "/zb_users/upload/202003/v01ovqqs1eg.gif"
# or use image previously downloaded to tinypic.com
#url = "/zb_users/upload/202003/a5a2v0plvnk.jpg"
url = "/zb_users/upload/202003/d1oysqr5atw.jpg"
image_bytes = urlopen(url).read()
# internal data file
data_stream = io.BytesIO(image_bytes)
# open as a PIL image object
pil_image = Image.open(data_stream)
# optionally show image info
# get the size of the image
w, h = pil_image.size
# split off image file name
fname = url.split('/')[-1]
sf = "{} ({}x{})".format(fname, w, h)
root.title(sf)
# convert PIL image object to Tkinter PhotoImage object
tk_image = ImageTk.PhotoImage(pil_image)
# put the image on a typical widget
label = tk.Label(root, image=tk_image, bg='brown')
label.pack(padx=5, pady=5)
root.mainloop()

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python初学之用户登录的实现过程(实例讲解)

要求编写登录接口: 1. 输入用户名和密码 2.认证成功后显示欢迎信息 3.用户名输错,提示用户不存在,重新输入(5次错误,提示尝试次数过多,退出程序) 4.用户名正确,密码错误,提示...

Python 类与元类的深度挖掘 II【经验】

  上一篇解决了通过调用类对象生成实例对象过程中可能遇到的命名空间相关的一些问题,这次我们向上回溯一层,看看类对象本身是如何产生的。   我们知道 type() 方法可以查看一个对象的类...

python逆向入门教程

python逆向入门教程

1、开发环境 我们在Windows 10上开始python逆向之旅,首先开始搭建开发环境,python解释器使用最新的3.6.1,IDE使用PyCharm社区版2017.1.3,下载地址...

Python利用heapq实现一个优先级队列的方法

Python利用heapq实现一个优先级队列的方法

实现一个优先级队列,每次pop的元素要是优先级高的元素,由于heapq.heapify(list)默认构建一个小顶堆,因此要将priority变为相反数再push,代码如下: imp...

Python2.x版本中maketrans()方法的使用介绍

 maketrans()方法返回的字符串intab每个字符映射到字符的字符串outtab相同位置的转换表。然后这个表被传递到translate()函数。 注意:两个intab和...