Python3 tkinter基础 Text image 文本框中插入图片

1,099 阅读1分钟
  •        Python : 3.8.11
  •          OS : Ubuntu Kylin 20.04
  •       Conda : 4.10.1
  •     PyCharm : 2021.1.3 (Community Edition)

代码

"""
@Author : 行初心
@Date   : 8/6/21
"""
from tkinter import *


def main():
    root = Tk()
    # 40个字符宽  30行,为了更好的展示图片
    my_text = Text(root, width=40, height=30)
    my_text.pack(padx=10, pady=10)

    my_photo = PhotoImage(file="text_photoimage.png")  # 这里对图片的格式也有要求的
    # 第一次我用的是 jpg 编辑器报错了.

    my_text.image_create(END, image=my_photo)

    mainloop()


if __name__ == '__main__':
    main()

运行结果

text_photoimage_result.png

知识扩展

第一次运行时,报错了:_tkinter.TclError: couldn't recognize data in image file "text_photoimage.png"

错误提示信息的大概意思是:不认得"text_photoimage.png"图片。

通过查找相关的资料,得到参考链接 -> couldn't recognize data in image file---学习tkinter的PhotoImage的一个问题

于是,从新找了一张正宗的png格式图片,再次运行,成功! 从前的那个虽然是以png结尾,但可能是个假的png。

感谢同学的博文!

参考资料

学习推荐


Python具有开源、跨平台、解释型和交互式等特性,值得学习。
Python的设计哲学:优雅,明确,简单。提倡用一种方法,最好是只有一种方法来做一件事。
GUI可以选择PyQt5、PySide2、wxPython、PyGObject、wxWidgets等进行创作。
代码的书写要遵守规范,这样有助于沟通和理解。
每种语言都有独特的思想,初学者需要转变思维、踏实践行、坚持积累。