Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter : How to insert an image to a text widget

Tags:

python

tkinter

I'm writing a notepad-like project and I need to insert an image to the Tkinter Text widget (Just like how MS Word does) and I didn't found anything helping me with this.

Here's my code:

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)

But when I run it, it just shows a white image with nothing on it.

What's WRONG with my code ? Can somebody please explain this to me

like image 309
Hung Truong Avatar asked Dec 17 '25 21:12

Hung Truong


1 Answers

You can use image_create or window_create example of both in use

This example doesn't use PIL, only PhotoImage which can only take a gif image file.

Example Code:

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()

Also, in your code I don't see how you are using the image selected. yourImage is not used anywhere

like image 133
Steven Summers Avatar answered Dec 20 '25 10:12

Steven Summers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!