Home > Net >  How to add a image to a button//Tkinter//Other answers not working
How to add a image to a button//Tkinter//Other answers not working

Time:10-03

I am trying to use a image as a button with the PhotoImage class with tkinter but I keep getting the following error:

_tkinter.TclError: couldn't open "image.png": no such file or directory

I get this error even thought the png file is in the same directory as the .py script. See Photo: Here is a screenshot of the folder layout As you can see both the files are in the same folder so I should not be receiving any errors?? Here is a reproduceable example of the code and see if you get the same error on you machine.

import tkinter as tk
window = tk.Tk()
window.geometry("800x600")
window.resizable(0, 0)

add_word_photo = tk.PhotoImage(file="image.png")
test_btn = tk.Button(image=add_word_photo,width=20)
test_btn.grid(row=0,column=0)
text_box = tk.Entry(width=30)
text_box.grid(row=0,column=1)
title_text=tk.Label(text="Spellings List")
title_text.grid(row=3,column=0, columnspan=2)

spellings_listbox = tk.Listbox(window,width=55,height=30)
spellings_listbox.grid(row=4,column=0,columnspan=2)

spellings_listbox.insert(1 ,"es")

window.mainloop()

The name of the image is listed correctly in the code so I don't really see what the problem is. I hope this post can benefit the community and help others who are facing the same problems as myself.

CodePudding user response:

I turns out this is this weird thing if that the parent folder has a space in its name python can't recognise relative files in the same folder. SOLUTION: change the parent folders space to a underscore.

  • Related