Search code examples
pythonpython-3.xtkintertkinter-text

How do i read all the links present in a file using open function in Python?


imagelist=[]
with open("imagelink.txt") as url:
    for url2 in url:
        if url2.strip():
            raw_data= urllib.request.urlopen(url2.strip()).read()
            im = ImageTk.PhotoImage(data=raw_data)
            result = maintext.image_create(0.0, image=im)
            imagelist.append(im) # save a reference of the image    

EDIT

Ok so i copied/followed the code exactly but when i run the images are not seen the in the text widget just white screen is visible


Solution

  • Only the first image in the text widget is shown because you used same variable for all instances of PhotoImage(), so the previous loaded images will be garbage collected.

    You need to save a reference for all the instances of image:

    imagelist = []  # list to store references of image
    with open("imagelink.txt") as url:
        for url2 in url:
            if url2.strip():
                raw_data = urllib.request.urlopen(url2.strip()).read()
                im = ImageTk.PhotoImage(data=raw_data)
                result = maintext.image_create(0.0, image=im)
                imagelist.append(im) # save a reference of the image
    

    Note that the result of maintext.image_create(...) is not a tkinter widget, so you cannot call .pack() on it.