繁体   English   中英

"Tkinter:如何将图像插入文本小部件"

[英]Tkinter : How to insert an image to a text widget

我正在编写一个类似记事本的项目,我需要将图像插入到 Tkinter Text 小部件(就像 MS Word 所做的那样),但我没有找到任何帮助我的东西。

这是我的代码:

from PIL import Image,ImageTk
from tkinter import *


text = Text(root)
root.pack()
#Insert Image

yourImage=filedialog.askopenfilename(title = "Select your image",filetypes = [("Image Files","*.png"),("Image Files","*.jpg")])
imgFile=Image.open(yourImage)
imgToInsert=ImageTk.PhotoImage(imgFile)

text.image_create("current",image=imgToInsert)

您可以同时使用image_create<\/code>或window_create<\/code>示例

此示例不使用 PIL,仅使用 PhotoImage,它只能获取 gif 图像文件。

示例代码:

import tkinter as tk

def add_image():
    text.image_create(tk.END, image = img) # Example 1
    text.window_create(tk.END, window = tk.Label(text, image = img)) # Example 2

root = tk.Tk()

text = tk.Text(root)
text.pack(padx = 20, pady = 20)

tk.Button(root, text = "Insert", command = add_image).pack()

img = tk.PhotoImage(file = "myImage.gif")

root.mainloop()

我希望这可以帮助你。

from PIL import Image,ImageTk
from tkinter import *
from tkinter import filedialog
root=Tk()
text = Text(root)
text.pack()
#Insert Image

yourImage=filedialog.askopenfilename(title = "Select your image",filetypes = [("Image Files","*.png"),("Image Files","*.jpg")])
#imgFile=Image.open(yourImage)
imgToInsert=ImageTk.PhotoImage(file=yourImage)

text.image_create("current",image=imgToInsert)
root.mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM