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进阶教程之动态类型详解

动态类型(dynamic typing)是Python另一个重要的核心概念。我们之前说过,Python的变量(variable)不需要声明,而在赋值时,变量可以重新赋值为任意值。这些都与...

对PyQt5基本窗口控件 QMainWindow的使用详解

对PyQt5基本窗口控件 QMainWindow的使用详解

QMainWindow基本介绍 QMainWindow主窗口为用户提供了一个应用程序框架,它有自己的布局,可以在布局中添加控件。 窗口类型介绍 PyQt5中,主要使用以下三个类来创建窗...

Python3实现zip分卷压缩过程解析

Python3实现zip分卷压缩过程解析

使用zipfile库 查看 官方中文文档 利用 Python 压缩 ZIP 文件,我们第一反应是使用 zipfile 库,然而,它的官方文档中却明确标注“此模块目前不能处理分卷 ZIP...

python web基础之加载静态文件实例

在web运行中很重要的一个功能就是加载静态文件,在django中可能已经给我们设置好了,我们只要直接把模板文件 放在templates就好了,但是你知道在基础中,像图片是怎么加载以及找到...

pymongo实现控制mongodb中数字字段做加法的方法

本文实例讲述了pymongo实现控制mongodb中数字字段做加法的方法。分享给大家供大家参考。具体分析如下: 这个非常实用,比如我们需要给文章做访问统计,可以设置一个数字字段:hit,...