tkinter PhotoImage doesn't exist? - python

from tkinter import *
root = Tk()
photo = PhotoImage(file='blueface.png')
label = Label(root, image=photo)
label.pack()
root.mainloop()
The image face.png is in the same directory as this .py script, but when I run it, I get the following error:
line 5, in <module>
photo = PhotoImage(file='blueface.png')
line 3539, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
line 3495, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "face.png": no such file or directory

It doesn't matter very much that the image is in the same folder as the script, when you call the file like that without a path python assumes it's in the same folder that you were working on when you started the script. For example, if both the script and the image are in temp folder, and you started your script like this:
python temp/script.py
The interpreter doesn't realize that blueface.png is also in temp and looks for it in the folder that you were in, in this case the parent of temp
What you should do, is either use absolute paths, or use the __file__ to get the full script address first. For example:
photo = PhotoImage(file='/absolute/path/to/image/blueface.png')
Or using the current script's location to build the image's path:
import os
base_folder = os.path.dirname(__file__)
image_path = os.path.join(base_folder, 'blueface.png')
photo = PhotoImage(file=image_path)

Older versions of tkinter can not handle .png's that well. Try making the file a .gif. Or use the PhotoImage from PIL:
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
photo = ImageTk.PhotoImage(Image.open('blueface.png'))
label = tk.Label(root, image=photo)
label.pack()
root.mainloop()

Related

pyinstaller is not attaching my image when I create an executable

How can i make an executable that can load image, and that my friends don't depend on downloading the executable and image or a heavy folder?
I'm trying to create an executable for my python program, but when I try to open its executable, I get this error:
Traceback (most recent call last):
File "main.py", line 49, in <module>
File "tkinter\__init__.py", line 4103, in __init__
File "tkinter\__init__.py", line 4048, in __init__
_tkinter.TclError: couldn't open "logo.png": no such file or directory
The code I'm using to compile is this:
pyinstaller --onefile --windowed --add-data "logo.png;." main.py
Is there any other compilation method or other way to make an executable with the logo attached? I tried some methods like:
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, relative_path)
But to no avail, and my complete code is this:
from pytube import Playlist, YouTube
from tkinter import *
from moviepy import *
import os
import re
if os.name == "nt":
downfolder = f"{os.getenv('USERPROFILE')}\\Downloads"
else:
downfolder = f"{os.getenv('HOME')}/Downloads"
def playlist_audio():
get_link = link_field.get()
p = Playlist(get_link)
p._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")
for video in p.videos:
screen.title('downloading.')
mp3_audio = video.streams.filter(only_audio=True).first().download(downfolder)
audioconvert(mp3_audio)
#
screen.title('completed')
def video_mp3():
get_link = link_field.get()
screen.title('downloading.')
mp3_audio = YouTube(get_link).streams.filter(only_audio=True).first().download(downfolder)
audioconvert(mp3_audio)
#
screen.title('completed')
def audioconvert(mp3_audio):
try:
base, ext = os.path.splitext(mp3_audio)
new_file = base + '.mp3'
os.rename(mp3_audio , new_file)
except WindowsError:
os.remove(new_file)
os.rename(mp3_audio , new_file)
screen = Tk()
title = screen.title('Python mp3')
screen.resizable(False, False)
Canvas = Canvas(screen, width=400, height=200)
Canvas.pack()
logoimg = PhotoImage(file='logo.png')
logo_img = logoimg.subsample(2, 2)
Canvas.create_image(215, 25, image=logo_img)
link_field = Entry(screen, width=50)
link_label = Label(screen, text="Enter the song/playlist URL.")
Canvas.create_window(200, 90, window=link_field)
Canvas.create_window(200, 70, window=link_label)
def convert():
try:
video_mp3()
return True
except:
screen.title("wait a few seconds")
try:
playlist_audio()
return False
except:
screen.title("unknown error, try again")
download = Button(screen, text="download", bg='green', padx='20', pady='5',font=('Arial', 12), fg='#fff', command=convert)
Canvas.create_window(200, 140, window=download)
screen.mainloop()
I was able to get this to work.
In your python code add this to access your image from the MEI directory
photopath = os.path.join(os.path.dirname(__file__), 'logo.png')
logoimg = PhotoImage(file=photopath)
Here are the steps I took.
create empty folder; cd into it; copy the logo.png an script(main.py)
py -m venv venv && venv\Scripts\activate
py -m pip install --upgrade pip pyinstaller moviepy pytube
pyinstaller -F main.py
Then in the spec file add on line 11 (i think) edit datas=[('logo.png','.')],
You can make other adjustments in the spec file as well like setting console=False for it to work in windowed mode and changing the name of the output executable file and other stuff.
pyinstaller main.spec
Thats it... the executable should work fine and load your photo and all.

Python reading file not working through tkinter file chooser

import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
filedir = filedialog.askopenfilename()
print(filedir)
items = open(filedir, 'a+')
text = items.read()
print(text)
When I run the code and select a file, it doesn't output anything. Putting the file location manually in the code still outputs nothing, and the .txt file definitely has content.
The mode in which you are trying to open the file is not valid that's why U are unable to read the file. Try using r+ mode to open, read and write (if already exists) the file.
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
filedir = filedialog.askopenfilename()
print(filedir)
items = open(filedir, 'r+')
text = items.read()
print(text)

Pillow - FileNotFoundError: No such file or directory: 'Lit_Bulb.jpg'

I just downloaded and extracted Pillow through PyPI, and it seems the modules are now accessible, but when I try to test it adding an image, it shows this error:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python Projects\Button Puzzle (GUI).py", line 4, in <module>
image = Image.open("Lit_Bulb.jpg")
File "C:\Program Files (x86)\PIL\Image.py", line 2288, in open
fp = builtins.open(fp, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Lit_Bulb.jpg'
I put the jpg file in the PIL folder, hoping it would find it with the module, but I guess I didn't do it right, can anyone help?
The code I tried:
import tkinter
from PIL import Image, ImageTk
image = Image.open("Lit_Bulb.jpg")
photo = ImageTk.PhotoImage(image)
label = tkinter.Label(main_menu, image = phto)
label.image = photo
label.pack()
main_menu = tkinter.Tk()
main_menu.title("Button Puzzle")
main_menu.configure(background ="SlateGray3")
main_menu.geometry("200x100")
play_button = tkinter.Button(main_menu, text="PLAY")
rules_button = tkinter.Button(main_menu, text= "Rules")
play_button.pack()
rules_button.pack()
main_menu.mainloop()
Pass the full path to the file image = Image.open("path_to_/Lit_Bulb.jpg"), unless the file is in the same directory as your your cwd then python won't be able to find the file.
It is always good practice to put your images or resources in the
same folder as your directory of the main .py file. For example if
you have your main files in c:\projects\myProject\ , then you should
put the your images in the same folder myProject.
This way when you open any file or image from within your code, all
you need to do is write the name of the file or image. for eg.
myImage = Image.open('Lit_Bulb.jpg').
If you don't put your images or files in the same folder than you can
access them by specifying the exact directory when you open the file
or image. For example, if my image is in a folder in E: drive, then I can
access it using this.
myImage = Image.open('E:\myFolder\Lit_Bulb.jpg').
Note- if you have a big project where you need a lot of files and images, then you should put those images inside a new folder in the same directory as your .py files. After doing this, if you want to open those files, it would look something like this. myImage = Image.open('Images\Lit_Bulb.jpg') since, the Imagesfolder is in the same directory as the py file, you don't need to specify the whole directory. Hope this helps.

File not found, even though the directory is correct

I am currently trying to make a game, and I am importing an image for a button from a the same folder the python file is from. The method:
dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
imagepath = os.path.join(dirname, "redvase.png")
vase1 = Button(root, relief=FLAT, background="white", image=imagepath)
vase1.place(x=330,y=240,height=30,width=30)
The output (imagepath) comes out as C:\Users\ - - \Desktop\Pythonproject\redvase.png
My file is at that exact path, but I still get an error saying that that file does not exist.
vase1 = Button(root, relief=FLAT, background="white", image=imagepath)
......
_tkinter.TclError: image "C:\Users\- -\Desktop\Pythonproject\redvase.png" doesn't exist
If it helps, I am using Windows and Python 3.4.3.
The image attribute for a button takes an input of an Image object, not a path to an image file.
In order to get an image, you can use a PhotoImage:
photo=PhotoImage(file="redvase.gif")
vase1 = Button(root, relief=FLAT, background="white", image=photo)

How to select a directory and store the location using tkinter in Python

I am creating a GUI with a browse button which I only want to return the path. I've been looking at solutions using code like below.
Tkinter.Button(subframe, text = "Browse", command = self.loadtemplate, width = 10).pack()
def loadtemplate(self):
filename = tkFileDialog.askopenfilename(filetypes = (("Template files", "*.tplate")
,("HTML files", "*.html;*.htm")
,("All files", "*.*") ))
if filename:
try:
self.settings["template"].set(filename)
except:
tkMessageBox.showerror("Open Source File", "Failed to read file \n'%s'"%filename)
However I know Tkinter has a built in askopenfilename which is a super easy one line of code for opening files. Is there some way to modify this to return the directory instead of a file? Is there a smaller option than the larger chunk of code I posted?
It appears that tkFileDialog.askdirectory should work. documentation
This code may be helpful for you.
from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()
Go with this code
First, select the directory for creating a new file
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
# file_path = filedialog.askopenfilename()
file_path = filedialog.askdirectory()
new_file = input("Name file\n")
open_file = open(f"{file_path}\%s.py" % new_file, 'w')
in my case
i created (ok.py) file in ppppp directory
path is: PS C:\Users\demo\Desktop\ppppp\ok.py

Categories