python tkinter canvas 显示图片的示例

yipeiwu_com6年前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实现matplotlib显示中文的方法详解

Python实现matplotlib显示中文的方法详解

本文实例讲述了Python实现matplotlib显示中文的方法。分享给大家供大家参考,具体如下: 【注意】 可能与本文主题无关,不过我还是想指出来:使用matplotlib库时,下面两...

Python利用多进程将大量数据放入有限内存的教程

Python利用多进程将大量数据放入有限内存的教程

简介 这是一篇有关如何将大量的数据放入有限的内存中的简略教程。 与客户工作时,有时会发现他们的数据库实际上只是一个csv或Excel文件仓库,你只能将就着用,经常需要在不更新他们的数据仓...

Python在图片中添加文字的两种方法

Python在图片中添加文字的两种方法

本文主要介绍的是利用Python在图片中添加文字的两种方法,下面分享处理供大家参考学习,下来要看看吧 一、使用OpenCV 在图片中添加文字看上去很简单,但是如果是利用OpenCV来做...

Django权限机制实现代码详解

本文研究的主要是Django权限机制的相关内容,具体如下。 1. Django权限机制概述 权限机制能够约束用户行为,控制页面的显示内容,也能使API更加安全和灵活;用好权限机制,能让系...

Python随手笔记之标准类型内建函数

Python提供了一些内建函数用于基本对象类型:cmp(),repr(),str(),type()和等同于repr()的(' ')操作符 (1)type()    t...