-1

So I have a list of files and a random file is selected then the image should be displayed.

The code I has thus far is as follows:

    def DisplayQ(self):
        dir = path.dirname(__file__)
        examQ_dir = path.join(dir, 'Exam Questions')
        questions = os.listdir(examQ_dir)  # put the files into a list
        question = random.choice(questions)
        img = ImageTk.PhotoImage(Image.open(question))
        img.place(x=100, y=100)

I have checked each section individually whilst implementing it and all the correct files are put into a list as I want them to also a random file is selected when I want it to be but the issue is that I get an error message everytime I run it saying:

 File "C:\Users\cj_he\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2809, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Particle Q3.png'

which I don't understand because I can go into my files and I can see the file is there and I can open it but for some reason python can't find the file. I am using the PyCharm IDE. Any suggestions on what the issue is?

Charlotte
  • 11
  • 2
  • 1
    While listing you are giving a path. But while reading the file you are passing just file name. You need to append path before file name during opening file. – Prashant Kumar Feb 18 '20 at 11:45
  • Check your current working directory using: `print(os.getcwd())`. Compare with the location of your image. – stovfl Feb 18 '20 at 11:45
  • Use `Image.open(path.join(examQ_dir, filename))`. – acw1668 Feb 18 '20 at 11:47
  • ***"img.place("***: This will fail, you can't place a image. Read [Why does Tkinter image not show up if created in a function?](https://stackoverflow.com/a/16424553/7414759) – stovfl Feb 18 '20 at 11:47

1 Answers1

2

While listing you are giving a path. But while reading the file you are passing just file name. You need to append path before file name during opening file.

Try this :

import os

def DisplayQ(self):
        dir = path.dirname(__file__)
        examQ_dir = path.join(dir, 'Exam Questions')
        questions = os.listdir(examQ_dir)  # put the files into a list
        question = random.choice(questions)
        img = ImageTk.PhotoImage(Image.open(os.path.join(examQ_dir, question)))

Prashant Kumar
  • 2,057
  • 2
  • 9
  • 22
  • @PrashantKumar thank you this solved the issue of finding the file. – Charlotte Feb 18 '20 at 12:00
  • @stovfl Thanks for the link I followed it and now the image is displayed. I didn't realise that was an issue because nothing was working but killed 2 birds with one stone in this questions so thanks :) – Charlotte Feb 18 '20 at 12:00
  • @stovfl, changed it. Charlotte, great we could be of help. Please mark the answer as accepted if it helped solve your problem. And thanks to stovfl for pointing out another problem in the code. Cheers :D – Prashant Kumar Feb 18 '20 at 12:09