Home > Blockchain >  Tkinter- How to display picture inside text widget at right position
Tkinter- How to display picture inside text widget at right position

Time:04-27

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

CodePudding user response:

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)
  • Related