Python Tkinter Canvas 显示图片的正确方式与全局变量处理

晚来风
晚来风
发布时间:2026-10-13| 6人浏览过
原创

本文介绍在 Python Tkinter 中使用 Canvas 显示图片的方法。重点强调必须保持对 image 对象的引用,否则图片可能因垃圾回收而消失。通过示例展示如何正确创建 PhotoImage 对象,并解决在函数内部调用时因局部变量作用域导致图片无法显示的问题,提供使用 global 声明全局变量的解决方案。

Canvas 显示图片的基本原理

首先查看该方法的相关说明。


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 参数时,有两个关键点需要注意:一是图片的格式,二是必须保持对该 image 对象的持续引用。

这里的 image 对象应当是一个

1. 它应该是 PhotoImage 或 BitmapImage 类型,或者是兼容的对象(例如 PIL 库中的 PhotoImage)。

2. 应用程序必须保留对该 image 对象的引用。

因此,代码应如下编写,且变量 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 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。