Home > Mobile >  Tkinter is not showing an image, what does this error mean and how can I get the correct image to sh
Tkinter is not showing an image, what does this error mean and how can I get the correct image to sh

Time:03-08

I am creating a dice roller in VSCode with Python for a class and we are to use Tkinter to create our widget to achieve this. I followed a tutorial to a T and yet I am still receiving errors saying the images do not exist. I have tried making my images .gif and .png and neither works.

Here is the code:

import tkinter as tk
from PIL import Image, ImageTk 
import random

root = tk.Tk ()
root.title("Cassie's Dice Roller")
root.geometry("500x500")

six_dice= ["one.png" , "two.png" , "three.png" , "four.png" , "five.png" , "six.png"]

roll_one = ImageTk.PhotoImage(Image.open(random.choice(six_dice)))

label = tk.Label(root, image=roll_one)

label.pack(side=tk.CENTER)

def six_roll():
    roll_one = ImageTk.PhotoImage(Image.open(random.choice(six_dice)))
    label.configure(image=roll_one)
    label.image=roll_one

Button = tk.Button(root, text='Roll', foreground='blue', command='six_roll')

Button.pack()

root.mainloop()

Here is the error I'm receiving:

File "C:\Users\brind\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\Image.py", line 2953, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: '4.gif'

CodePudding user response:

When I ran this code I got no similar error. The only problem was with the image.CENTER statement within the pack. But remove that and the code ran fine. I would try out an absolute path to the images as they don't seem to be appearing in your run level directory.

CodePudding user response:

Where have you stored the pictures? You can get the location which the python interpreter searches files through

os.getcwd()(link):

Return a string representing the current working directory.

In default, it's the path of the workspace folder, because it's the default value in the terminal.

  • Related