python tkinter使用(九)

python tkinter使用(九)

本文主要讲下scrolledText中图片的插入,以及常见的错误.

  1. 使用Image.open来打开图片
  2. 使用ImageTk.PhotoImage()方法将图片转换为tkinter中的图片对象
  3. 使用insert()方法插入图片

ImageTk 直接引入后,会遇到如下错误:

Traceback (most recent call last):
  File "ScrolledTextTest.py", line 11, in <module>
    from PIL import Image, ImageTk
ImportError: cannot import name 'ImageTk' from 'PIL' (/usr/lib/python3/dist-packages/PIL/__init__.py)

这里需要我们install:

sudo apt-get install python3-pil python3-pil.imagetk
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
 @Author: zh
 @Time 2023/11/27 上午11:40  .
 @Email:
 @Describe:
"""
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
from PIL import Image, ImageTk

# 创建窗口
root = tk.Tk()
root.title("simpleDialog")

# 创建一个框架并使用pack()方法
frame1 = tk.Frame(root)
frame1.pack()
text2 = ScrolledText(frame1)
text2.pack()
# text2.grid(column=0, row=0)
text2.insert(tk.INSERT, "Hello, world!")
text2.tag_add("tag1", 1.0, 1.5)
text2.tag_config("tag1", background="green")

text2.tag_remove("tag1", 1.3, 1.5)
img = Image.open("img/test.png")
photo = ImageTk.PhotoImage(img)
text2.image_create(tk.END, image=photo)


root.mainloop()

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值