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设计模式之观察者模式。分享给大家供大家参考,具体如下: 观察者模式是一个软件设计模式,一个主题对象包涵一系列依赖他的观察者,自动通知观察者的主题对象的改变,通常...

pytorch 预训练层的使用方法

pytorch 预训练层的使用方法 将其他地方训练好的网络,用到新的网络里面 加载预训练网络 1.原先已经训练好一个网络 AutoEncoder_FC() 2.首先加载该网络,读取其存储...

python程序 创建多线程过程详解

一、python线程的模块 1.1 thread和threading模块 thread模块提供了基本的线程和锁的支持 threading提供了更高级别、功能更强的线程管理的功能。...

selenium使用chrome浏览器测试(附chromedriver与chrome的对应关系表)

selenium使用chrome浏览器测试(附chromedriver与chrome的对应关系表)

使用WebDriver在Chrome浏览器上进行测试时,需要从http://chromedriver.storage.googleapis.com/index.html网址中下载与本机c...

python中文乱码的解决方法

乱码原因: 源码文件的编码格式为utf-8,但是window的本地默认编码是gbk,所以在控制台直接打印utf-8的字符串当然是乱码了! 解决方法: 1、print mystr.deco...