python tkinter canvas 显示图片的示例

yipeiwu_com5年前Python基础

先来看一下该方法的说明

create_image(position, **options) [#]
Draws an image on the canvas.

position
Image position, given as two coordinates.
**options
Image options.
activeimage=
anchor=
Where to place the image relative to the given position. Default is CENTER.
disabledimage=
image=
The image object. This should be a PhotoImage or BitmapImage, or a compatible object (such as the PIL PhotoImage). The application must keep a reference to the image object.
state=
Item state. One of NORMAL, DISABLED, or HIDDEN.
tags=
A tag to attach to this item, or a tuple containing multiple tags.
Returns:
The item id.

关于image有两个重要的点要注意,一个是格式,第二是要保持持续引用

The image object. This should be a

1.This should be a PhotoImage or BitmapImage, or a compatible object (such as the PIL PhotoImage).

2.The application must keep a reference to the image object.

因此代码应该这样写,并且变量im应该是全局变量

image = Image.open("img.jpg") 
im = ImageTk.PhotoImage(image) 

canvas.create_image(300,50,image = im) 

但如果我就是想要在方法里调用怎么办?

那么可以提前声明全局变量

image = None
im = None

之后在方法里使用global来声明变量为全局变量

即:

def method():
  global image
  global im
  image = Image.open("img.jpg") 
  im = ImageTk.PhotoImage(image) 
  ...

以上这篇python tkinter canvas 显示图片的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python读取图片任意范围区域

python读取图片任意范围区域

使用python进行图片处理,现在需要读出图片的任意一块区域,并将其转化为一维数组,方便后续卷积操作的使用。 下面使用两种方法进行处理: convert 函数 from PIL i...

Python学习笔记基本数据结构之序列类型list tuple range用法分析

本文实例讲述了Python学习笔记基本数据结构之序列类型list tuple range用法。分享给大家供大家参考,具体如下: list 和 tuple list:列表,由 []...

用Python将动态GIF图片倒放播放的方法

用Python将动态GIF图片倒放播放的方法

这次让我们一个用 Python 做一个小工具:将动态 GIF 图片倒序播放! GIF(Graphics Interchange Format) 是一种可以用来呈现动画效果的图片格式,原...

详解Python中的format格式化函数的使用方法

详解Python中的format格式化函数的使用方法

format函数实现字符串格式化的功能 基本语法为: 通过 : 和 {} 来控制字符串的操作 一、对字符串进行操作 1. 不设置指定位置,按默认顺序插入 ①当参数个数等于{}个数的时候...

Python socket实现的文件下载器功能示例

本文实例讲述了Python socket实现的文件下载器功能。分享给大家供大家参考,具体如下: 文件下载器 先写客户端再写服务端 1.tcp下载器客户端 import socket...