How to delete an image in Tkinter Text Widget?

95 Views Asked by At

I'm trying to display an image until a user presses a backspace button which would delete the last displayed image. The image is appear alongside text. Here is my code for displaying the image:

im = Image.open(fn)
im_width, im_height = im.size
scale_factor = im_height / 24  # 18 pt font is 24 px
im = im.resize((math.ceil(im_width//scale_factor), math.ceil(im_height//scale_factor)))
emoji_im = ImageTk.PhotoImage(im, master=self.root)
self.textbox.image_create(tk.END, image=emoji_im)

Also, here is how to "backspace" button works for the text components:

self.textbox.delete("end-2c")

I couldn't find any good resources for how to remove an image from a text widget. I'm think of trying to use the canvas object instead, but the Text widget is much more intuitive for typing with text.

EDIT: sorry folks here is what self.textbox is:

self.textbox = scrolledtext.ScrolledText(self.root, height=3, width=30, font=("DejaVu Sans", 18), relief=tk.FLAT,bg='linen', padx=10, pady=10)
self.textbox.place(x=20, y=150)
self.textbox.insert('1.0', '')

I tried using the delete method mentioned above used for the text parts, but it doesn't work for the images for some reason.

1

There are 1 best solutions below

2
Module_art On

This is a possible way with standard Tkinter Text widget.

import tkinter as tk
from PIL import ImageTk, Image

win = tk.Tk()
im = Image.open("your_image.png")
emoji_im = ImageTk.PhotoImage(im, master=win)

def add_img():
    textbox.image_create(tk.END, image=emoji_im)
    
def remove_img():
    textbox.delete("end-2c")
    
textbox = tk.Text(win)
textbox.grid()

b_add = tk.Button(win, command=add_img, text="Add Img")
b_add.grid()
b_remove = tk.Button(win, command=remove_img, text="Delete Img")
b_remove.grid()

win.mainloop()

This is how you delete an image by text index, there is another way by deleting what image_create returns.