Python3用tkinter和PIL实现看图工具

yipeiwu_com7年前Python基础

需求

想做看图工具的,必然要支持jpg、png等常见格式,但tkinter是个纯粹的GUI库,不像GTK、QT那样大而全,所以只支持gif和ppm两种格式,局限很大,必须搭配图像处理库,才能实现基本的看图功能
在python生态系统里,最常用的图像处理库是PIL

Python3下库的安装

这两个库在python3下跟python2有一定差异:
tkinter首字母变成小写
PIL官方还不支持Python3,但有个fork叫Pillow,可以替代官方并且接口保持不变,需要pip install Pillow安装

技术原理

那么怎么让PIL读取jpg文件生成的内存对象被tkinter处理呢?PIL的开发人员很贴心的提供了一个PhotoImage类,跟tkinter包里的同名类接口兼容,所以可以直接将PIL生成的PhotoImage对象赋给tkinter中能接收PhotoImage入参的所有控件(比如Label、Canvas等)

代码示例

#encoding=utf-8
import tkinter as tk
from PIL import Image, ImageTk

class App(tk.Frame):
  def __init__(self, master=None):
    super().__init__(master, width=400, height=300)
    self.pack()
    self.pilImage = Image.open("CSDN.png")
    self.tkImage = ImageTk.PhotoImage(image=self.pilImage)
    self.label = tk.Label(self, image=self.tkImage)
    self.label.pack()

  def processEvent(self, event):
    pass

if __name__ == '__main__':
  root = tk.Tk()
  app = App(root)
  root.mainloop()

最终显示效果

相关文章

python访问类中docstring注释的实现方法

本文实例讲述了python访问类中docstring注释的实现方法。分享给大家供大家参考。具体分析如下: python的类注释是可以通过代码访问的,这样非常利于书写说明文档 clas...

教你使用python实现微信每天给女朋友说晚安

教你使用python实现微信每天给女朋友说晚安

本文为大家分享了教你用微信每天给女朋友说晚安的python实战,供大家参考,具体内容如下 但凡一件事,稍微有些重复。我就考虑怎么样用程序来实现它。 这里给各位程序员朋友分享如何每天给朋友...

Python3.6.x中内置函数总结及讲解

Python3.6.x中内置函数总结 # -*- coding:utf-8 -*- """ abs() dict() help() min() s...

Python字符串的encode与decode研究心得乱码问题解决方法

为什么会报错“UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not...

Python+tkinter使用40行代码实现计算器功能

Python+tkinter使用40行代码实现计算器功能

本文实例为大家分享了40行Python代码实现计算器功能,供大家参考,具体内容如下 偶尔用脚本写点东西也是不错的。 效果图 代码 from tkinter import *...