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基于递归和非递归算法求两个数最大公约数、最小公倍数示例

本文实例讲述了Python基于递归和非递归算法求两个数最大公约数、最小公倍数。分享给大家供大家参考,具体如下: 最大公约数和最小公倍数的概念大家都很熟悉了,在这里就不多说了,今天这个是因...

Python随机生成均匀分布在单位圆内的点代码示例

Python随机生成均匀分布在单位圆内的点代码示例

Python有一随机函数可以产生[0,1)区间内的随机数,但是如果我们想生成随机分布在单位圆上的,那么我们可以首先生成随机分布在单位圆边上的点,然后随机调整每个点距离原点的距离,但是我们...

Django实现登录随机验证码的示例代码

Django实现登录随机验证码的示例代码

登录验证码是每个网站登录时的基本标配,网上也有很多相应的文章, 但是从生成验证码到 应用到自己的网站上的全步骤,并没有看到很多, 为了节约大家的时间,我把整体步骤写下来, 即拿即用哈 1...

python binascii 进制转换实例

如下所示: #coding:utf-8 import binascii a = 'worker' #先把worker转换成二进制数据然后在用十六进制表示 b = binasc...

Python的条件锁与事件共享详解

1:事件机制共享队列: 利用消息机制在两个队列中,通过传递消息,实现可以控制的生产者消费者问题 要求:readthread读时,writethread不能写;writethread写...