Python实例讲解 -- tkinter canvas (设置背景图片及文字)

本文介绍了使用Python的Tkinter库进行基本图形绘制的方法,包括直线、矩形和文字等元素,并展示了如何加载和显示图像。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先来一个绘图:

from Tkinter import *

master = Tk()

w = Canvas(master, width=200, height=100)
w.pack()

w.create_line(0, 0, 200, 100)
w.create_line(0, 100, 200, 0, fill="red", dash=(4, 4))

w.create_rectangle(50, 25, 150, 75, fill="blue")

mainloop()


tk 默认处理图片格式为gif 处理其他格式的图片,否则需要下载image的mod,见附件


# -*- coding:utf-8 -*-
# file: TkinterCanvas.py
#
import Tkinter # 导入Tkinter模块
from PIL import Image, ImageTk

root = Tkinter.Tk()
canvas = Tkinter.Canvas(root,
width = 500, # 指定Canvas组件的宽度
height = 600, # 指定Canvas组件的高度
bg = 'white') # 指定Canvas组件的背景色
#im = Tkinter.PhotoImage(file='img.gif') # 使用PhotoImage打开图片
image = Image.open("img.jpg")
im = ImageTk.PhotoImage(image)

canvas.create_image(300,50,image = im) # 使用create_image将图片添加到Canvas组件中
canvas.create_text(302,77, # 使用create_text方法在坐标(302,77)处绘制文字
text = 'Use Canvas' # 所绘制文字的内容
,fill = 'gray') # 所绘制文字的颜色为灰色
canvas.create_text(300,75,
text = 'Use Canvas',
fill = 'blue')
canvas.pack() # 将Canvas添加到主窗口
root.mainloop()


参看: http://effbot.org/tkinterbook/canvas.htm#when-to-use

wxpython 的canvas


# create a canvas on top of a blank bitmap
# any canvas drawings can now be saved to a standard image file
# tested with Python27 and wxPython28 by vegaseat 05jan2011

import wx

class MyFrame(wx.Frame):
def __init__(self, parent=None, id=-1, title=None):
wx.Frame.__init__(self, parent, id, title, size=(380,400))
self.statbmp = wx.StaticBitmap(self)
self.draw_image()
self.save_image()

def draw_image(self):
# select the width and height of the blank bitmap
# should fit the client frame
w, h = 340, 340
# create the blank bitmap as a draw background
draw_bmp = wx.EmptyBitmap(w, h)
# create the canvas on top of the draw_bmp
canvas_dc = wx.MemoryDC(draw_bmp)
# fill the canvas white
canvas_dc.SetBrush(wx.Brush('white'))
canvas_dc.Clear()

# draw a bunch of circles ...
# pen colour
canvas_dc.SetPen(wx.Pen('red', 1))
# fill colour
canvas_dc.SetBrush(wx.Brush('yellow'))
for x in range(10, 180, 10):
y = x
r = x
canvas_dc.DrawCircle(x, y, r)

# now put the canvas drawing into a bitmap to display it
# remember the canvas is on top of the draw_bmp
self.statbmp.SetBitmap(draw_bmp)

def save_image(self):
"""save the drawing"""
finished_image = self.statbmp.GetBitmap()
#finished_image.SaveFile("mydrawing.png", wx.BITMAP_TYPE_PNG)
finished_image.SaveFile("mydrawing.jpg", wx.BITMAP_TYPE_JPEG)


app = wx.App(0)
MyFrame(title='canvas draw and save').Show()
app.MainLoop()

# help(wx.PaintDC)
<think>我们正在使用PythonTkinter库,特别是Canvas组件来显示图片。根据引用,有几种方法可以实现:1.使用`tkinter.PhotoImage`直接显示图片(如引用[1]所示),但注意`PhotoImage`只支持部分图片格式(如PNG、GIF)。2.如果要显示其他格式(如JPG),可以使用PIL(Python ImagingLibrary)或Pillow库来转换图片格式(如引用[2]所示)。根据用户的问题,他/她想要在Canvas上显示图片。我们将提供两种方法:方法一:使用Tkinter自带的PhotoImage(适用于PNG、GIF)方法二:使用Pillow库(可以支持更多格式,如JPG)注意:使用`PhotoImage`时,必须注意要保留对图片对象的引用,否则图片可能不会显示(因为Python的垃圾回收机制)。这可以通过将图片对象赋值给一个全局变量或实例变量来实现。下面我们分别给出两种方法的代码示例。方法一:使用Tkinter的PhotoImage(仅支持PNG、GIF等)步骤:1.导入tkinter2.创建Tk根窗口3.创建Canvas组件4.使用`tkinter.PhotoImage`加载图片文件5.在Canvas上创建图片项6.打包Canvas并进入主循环示例代码(显示PNG图片): ```pythonimport tkinterroot =tkinter.Tk() canvas= tkinter.Canvas(root,width=800,height=600)#加载图片,注意:这里使用相对路径或绝对路径image_file= tkinter.PhotoImage(file='example.png')#替换为你的图片路径#在Canvas上创建图片,位置(100,100),锚点西北角(左上角)image_item= canvas.create_image(100,100,anchor='nw', image=image_file)canvas.pack()root.mainloop()```方法二:使用Pillow库(支持JPG等格式)步骤:1.导入tkinter和Pillow的ImageTk,Image模块2.创建Tk根窗口3.创建Canvas组件4.使用Pillow的Image打开图片,然后用ImageTk.PhotoImage转换5.在Canvas上创建图片项6.打包Canvas并进入主循环示例代码(显示JPG图片): ```pythonimport tkinterfrom PILimport ImageTk,Imageroot =tkinter.Tk() canvas= tkinter.Canvas(root,width=800,height=600)#使用Pillow打开图片并转换为PhotoImagepil_image =Image.open('example.jpg')#替换为你的图片路径#调整图片大小(可选)# pil_image =pil_image.resize((400,300), Image.ANTIALIAS) image_file= ImageTk.PhotoImage(pil_image) #在Canvas上创建图片image_item =canvas.create_image(100,100, anchor='nw',image=image_file) canvas.pack() root.mainloop()```注意:在方法二中,同样需要保持对image_file的引用,否则图片可能不会显示。上面的代码中,image_file是局部变量,但由于在mainloop运行期间,它不会被回收。如果是在函数内部,需要将其设为全局变量或对象的属性(如引用[2]中提到的)。另外,引用[4]也提到了:应用程序必须保持对图片对象的引用。如果用户需要动态更换图片,可以使用`canvas.itemconfig`来更新图片项(如引用[2]中第17行所示)。总结:-对于PNG、GIF等格式,可以直接使用`tkinter.PhotoImage`。-对于JPG等格式,需要使用Pillow库转换。希望这些信息能帮助用户成功在Canvas上显示图片。相关问题:1.如何在Tkinter Canvas上显示JPG格式的图片?2.为什么在Tkinter中显示的图片有时候会不出现?3.如何动态更新Canvas上的图片?4.TkinterCanvas组件还能绘制哪些图形?</think>在 Python Tkinter 中使用 Canvas 组件显示图片的方法如下: ### 方法一:直接使用 Tkinter 的 PhotoImage(支持 PNG、GIF) ```python import tkinter as tk root = tk.Tk() canvas = tk.Canvas(root, width=400, height=400) canvas.pack() # 加载图片(支持 PNG/GIF) image = tk.PhotoImage(file="image.png") # 替换为你的图片路径 # 在画布上显示图片 (anchor='nw' 表示左上角定位) canvas.create_image(20, 20, anchor="nw", image=image) root.mainloop() ``` ### 方法二:使用 PIL/Pillow 库(支持 JPG/PNG 等格式) ```python import tkinter as tk from PIL import ImageTk, Image # 需要安装 Pillow: pip install Pillow root = tk.Tk() canvas = tk.Canvas(root, width=400, height=400) canvas.pack() # 使用 PIL 打开图片(支持 JPG/PNG 等) pil_image = Image.open("image.jpg") # 替换为你的图片路径 # 转换为 Tkinter 兼容格式 tk_image = ImageTk.PhotoImage(pil_image) # 在画布上显示图片 canvas.create_image(0, 0, anchor="nw", image=tk_image) # 必须保持图片引用(重要!) root.tk_image = tk_image # 防止被垃圾回收 root.mainloop() ``` ### 关键注意事项: 1. **图片引用**:必须保持对图片对象的引用(如 `root.tk_image = tk_image`),否则图片可能无法显示[^2][^4] 2. **文件格式**: - `PhotoImage` 原生支持 PNG/GIF - JPG/JPEG 需要 PIL/Pillow 库支持 3. **锚点定位**: - `anchor="nw"` 表示左上角定位 - 其他选项:center, n, ne, e, se, s, sw, w 4. **坐标系统**: - Canvas 坐标原点 (0,0) 在左上角 - X 轴向右增加,Y 轴向增加 ### 高级功能示例: ```python # 创建带滚动条的图片查看器 canvas = tk.Canvas(root, scrollregion=(0, 0, 1000, 800)) scroll_x = tk.Scrollbar(root, orient="horizontal", command=canvas.xview) scroll_y = tk.Scrollbar(root, orient="vertical", command=canvas.yview) canvas.configure(xscrollcommand=scroll_x.set, yscrollcommand=scroll_y.set) # 动态更新图片 def update_image(new_path): global tk_image pil_image = Image.open(new_path) tk_image = ImageTk.PhotoImage(pil_image) canvas.itemconfig(image_id, image=tk_image) root.tk_image = tk_image # 保持引用 ``` [^1]: 使用 `create_image` 方法在 Canvas 上显示图片 [^2]: 必须保持对图片对象的引用以防止被垃圾回收 [^4]: `PhotoImage` 或 `ImageTk.PhotoImage` 对象需要持久引用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值