2

I have created a simple chatting app for now it is only sending and receiving messages but i want to add some more functionality in it and want to share pictures and images. I tried to build some logic but i am still on the way my issue is how can i display picture inside chat box like we do in different chatting apps. Below is my code for this kindly point out what is wrong in it because when i run code and upload image it displayed at chat box but when i upload another image first one got vanished.

def open_img ( self) :
    global img
    f_types = [ ('Jpg Files' , '*.jpg'), ('Png Files' , '*.png'), ('Jpeg Files' , '*.jpeg') ]
    filename = filedialog.askopenfilename ( filetypes = f_types )
    img =  PIL.Image.open ( filename )
    img_resized = img.resize ( (200 , 100) )  # new width & height
    img = PIL.ImageTk.PhotoImage ( img_resized )
    self.text_box.image_create ( END , image = img )


    
    self.text_box.insert(END , "\n")

    
   

    self.text_box.tag_configure ( "right" , justify = 'right' )
    self.text_box.tag_configure ( "right" , foreground = 'slate blue2' )
    
    self.text_box.configure ( state = DISABLED )
    self.text_box.see ( END )

This is my function to upload and display image inside textbox. these are the outputs. enter image description here

above output when i upload first picture but when i again upload any picture it give this type of output enter image description here

sam
  • 309
  • 2
  • 9

1 Answers1

1

The image disappears because you are not saving a reference to the previous image, and then it gets garbage collected. You can fix this by creating a list to hold all image references and then just append every new image to this list.

In the __init__() method:

self.image_list = []

In the open_img() method:

self.image_list.append(img)
figbeam
  • 7,001
  • 2
  • 12
  • 18
  • can we convert image to clickable image means by clicking on the image we get some type of result? – sam Apr 27 '22 at 07:36
  • As far as I can see the Text widget was not really meant for this type of interaction. However it seems that you could work it; have a look at [How to bind an image within a Tkinter Text widget to an event?](https://stackoverflow.com/a/49070786/8172933). – figbeam Apr 27 '22 at 09:58
  • almost done with my task with your now i have only one when i upload image it automatically open the image in a image viewer but i want image to open in a image viewer when i click on it. this is my code `self.text_box.image_create ( END ,image = img ) fop = open ( file , "rb" ) def onclick(): os.startfile(file, 'open') self.text_box.bind("" ,onclick())` – sam Apr 28 '22 at 08:08
  • 1
    Please start a new question instead of continuing in comments. – figbeam Apr 28 '22 at 11:19
  • here is the link of my [new-question](https://stackoverflow.com/questions/72053156/tkinter-unable-to-bind-image-with-an-event) kindly look into it – sam Apr 29 '22 at 05:24