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程序设计有所帮助。

相关文章

django 类视图的使用方法详解

 前言 当我们在开发一个注册模块时。浏览器会通过get请求让注册表单弹出来,然后用户输完注册信息后,通过post请求向服务端提交信息。这时候我们后端有两个视图函数,一个处理ge...

浅谈pandas中DataFrame关于显示值省略的解决方法

浅谈pandas中DataFrame关于显示值省略的解决方法

python的pandas库是一个非常好的工具,里面的DataFrame更是常用且好用,最近是越用越觉得设计的漂亮,pandas的很多细节设计的都非常好,有待使用过程中发掘。 好了,发完...

Python实现冒泡,插入,选择排序简单实例

本文所述的Python实现冒泡,插入,选择排序简单实例比较适合Python初学者从基础开始学习数据结构和算法,示例简单易懂,具体代码如下: # -*- coding: cp936 -...

Python学习之用pygal画世界地图实例

Python学习之用pygal画世界地图实例

有关pygal的介绍和安装,大家可以参阅《pip和pygal的安装实例教程》,然后利用pygal实现画世界地图。代码如下: #coding=utf-8 import json i...

Python实现计算长方形面积(带参数函数demo)

Python实现计算长方形面积(带参数函数demo)

如下所示: # 计算面积函数 def area(width, height): return width * height def print_welcome(name):...