I have a project for minecraft, and after converting it to exe with this command:
pyinstaller "F:\pythonprojetcs\minecraft file mover\splashscreen.py" -F --icon="F:\pythonprojetcs\minecraft file mover\app.ico"
It wont launch. This is the error:
Traceback (most recent call last):
File "splashscreen.py", line 21, in <module>
image = tk.PhotoImage(file=image_file)
File "tkinter\__init__.py", line 4064, in __init__
File "tkinter\__init__.py", line 4009, in __init__
_tkinter.TclError: couldn't open "C:\Users\REINER~1\AppData\Local\Temp\_MEI248722\data\image.png": no such file or directory
[4692] Failed to execute script splashscreen
It works fine when its in the .py format, with to errors.
Its says that tkinter is the error, but I don't understand it.
The code:
# create a splash screen, 80% of display screen size, centered,
# displaying a GIF image with needed info, disappearing after 5 seconds
import os
import tkinter as tk
import shutil
import time
root = tk.Tk()
root.overrideredirect(True)
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
root.geometry('%dx%d+%d+%d' % (width*0.8, height*0.8, width*0.1, height*0.1))
image_file = os.path.dirname(__file__) + '\\data\\image.png'
image = tk.PhotoImage(file=image_file)
canvas = tk.Canvas(root, height=height*0.8, width=width*0.8, bg="brown")
canvas.create_image(width*0.8/2, height*0.8/2, image=image)
canvas.pack()
root.after(2000, root.destroy)
root.mainloop()
print("Világ vagy textúrát akkarsz? (világ = 1 / textúra = 2 / világ másolás = 3 / tutorial = 4)")
choosing = input()
if choosing == "1":
print("\n")
print("\n")
print("Ok, szóval világ.")
print("Hol van?")
original = input()
target = 'C:\\Users\\Refi\\AppData\\Roaming\\.minecraft\\saves'
shutil.move(original,target)
time.sleep(1)
print("Kész!")
print("Ha ezt írja ki: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Reiner Regő\\Downloads\\test', akkor az a fálj nem létezik!")
print("Kérlek várj! Ne zárd be!")
time.sleep(3)
if choosing == "2":
print("\n")
print("\n")
print("Ok, szóval textúra.")
print("Hol van?")
original = input()
target = 'C:\\Users\\Refi\\AppData\\Roaming\\.minecraft\\resourcepacks'
shutil.move(original,target)
time.sleep(1)
print("Kész!")
print("Ha ezt írja ki: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Reiner Regő\\Downloads\\test', akkor az a fálj nem létezik!")
print("Kérlek várj! Ne zárd be!")
time.sleep(3)
if choosing == "3":
print("\n")
print("\n")
print("Ok, szóval világot akarsz másolni.")
print("Mi a neve?")
inputfromuser = input()
original = 'C:\\Users\\Refi\\AppData\\Roaming\\.minecraft\\saves\\' + inputfromuser
target = 'D:'
shutil.move(original,target)
time.sleep(1)
print("Kész! A D:-ben fogod megtlálni!")
print("Ha ezt írja ki: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Refi\\Downloads', akkor az a fálj nem létezik!")
print("Kérlek várj! Ne zárd be!")
time.sleep(3)
print('\n')
input("nyomd meg az entert a kilépéshez")
This copies files from one diretory from another, the splashscreen code is just an example.
Please help!
Your script is trying to access image files from a directory relative to the script itself; this works when the script is installed unpacked, with resources actually on the file system. But when bundled into an executable, that can't work; the image isn't going to be there unless you've copied it in with the executable (an ugly hack of a solution); you need to bundle it into the executable itself in such a way that it can be extracted at runtime by your script.
You need to read the docs on spec files, specifically, adding data files (to bundle the data with the executable when you build it) and using data files from a module (to extract the bundled data in memory at runtime).
You'll only have access to the data from the file, it won't be a file on disk anymore, so you'll need to use alternate means of loading, e.g. from base64 encoded data.
Related
I want to make a list of files .max from a directory that the user can choose and then open it when the 3ds Max is not running.
The problem is that I am using os.starfile() to open the .max file and even tryied to use subprocess but none of them works and the following message appears:
"FileNotFoundError: [WinError 2] the system cannot find the file specified:"
As you can you see, the program recognizes the path of the directory and the files .max that are inside of it.
I've already used os.startfile to open a .max file once and it did it works, but can't figure it out why it's not working this time.
import os
import psutil
import easygui
import time
from tkinter import filedialog
from tkinter import *
root = Tk()
msg = "Select a folder to render the .max files inside"
title = "3DS MAX AUTO RENDER"
choice = ["Select Folder"]
reply = easygui.buttonbox(msg, title, choices = choice)
if reply == "Select Folder":
root.directoryPath = filedialog.askdirectory(initialdir="/", title="Select a folder")
print(root.directoryPath)
directoryFiles = os.listdir(root.directoryPath)
print(directoryFiles)
isRunning = "3dsmax.exe" in (i.name() for i in psutil.process_iter())
if (isRunning == False):
for file in directoryFiles:
os.startfile(file)
The file names returned by os.listdir are relative to the directory given. As you are not in that directory when you run the script it can't find the file which is why you get an error.
Use os.path.join to join the directory and file name:
directoryFiles = [os.path.join(root.directoryPath, x) for x in os.listdir(root.directoryPath)]
directoryFiles will then contain the absolute paths so you won't get the error.
I am new to python and have been messing with Tkinter and PyInstaller.
When I package my script using;
pyinstaller --onefile --noconsole window.py
and try to open it I get this error;
Traceback (most recent call last):
File "window.py", line 10, in <module>
File "tkinter\__init__.py", line 4093, in __init__
File "tkinter\__init__.py", line 4038, in __init__
_tkinter.TclError: couldn't open "orange.png": no such file or directory
Maybe I am missing something,
Here is my code;
import tkinter as tk
from tkinter import PhotoImage
casement = tk.Tk() # Window
casement.title('Squeeze') # Window Title
casement.geometry('800x800') # Window Size
casement.resizable(True, True) # Winow Resizable x, y
casement.configure(bg='white') # Window Background Color
icon=PhotoImage(file="orange.png") # Window Icon File Var
casement.iconphoto(True,icon) # Window Icon
icon = tk.PhotoImage(file='orange.png') # Button Icon
button = tk.Button(casement, image=icon, text="Open Image", compound=tk.LEFT, bg='orange') # Button
button.pack(ipadx=5, ipady=5) #Button Placement
casement.mainloop()
When you create a single-file executable with Pyinstaller it will place resources in a specially created "MEI" directory in your user temp folder (named something like "_MEI1234"). You'll need to tell Pyinstaller where to look for assets when you run the build command like so:
pyinstaller -w -F -i ".\src\assets\icons\appicon.ico" "<your filename.py here>" --add-data ".\src\assets\;assets"
This way, Pyinstaller understands that it needs to include everything from your source assets folder (src\assets\ in my example, but yours is probably different). Then, everything in your assets folder will be included in the MEI directory used by the executable.
To access these resources when your Python app runs as an exe, you can retrieve the sys._MEIPASS and prepend it to the resource path. I've put together a function that handles exactly this below!
import sys
from pathlib import Path
def fetch_resource(rsrc_path):
try:
base_path = sys._MEIPASS
except AttributeError: # running as script, return unmodified path
return rsrc_path
else: # running as exe, return MEI path
return base_path.joinpath(rsrc_path)
Then, for any external assets you can retrieve them by calling fetch_resource() on them like this
icon = PhotoImage(file=fetch_resource("my_assets/orange.png"))
Just make sure that whatever the root directory containing my_assets/orange.png is included with the build via --add-data ".\my_source_code_dir\my_assets\;my_assets" (and again, use whatever path names are appropriate to your particular project)
studying foundation year ComSci and I'm trying to get a file to open. Here's my code:
def main():
filename = raw_input("Please enter file name ")
infile = open(filename,'r')
data = infile.read()
print data
main()
I believe the code is correct but when I try and open a file, for example
C:\Users\Manol\OneDrive\Documents\Uni\Programming\File Processing File
It comes back with
Traceback (most recent call last):
File "C:\Users\Manol\OneDrive\Documents\Uni\Programming\File Processing File\FirstFileProcessingRead.py", line 6, in <module>
main()
File "C:\Users\Manol\OneDrive\Documents\Uni\Programming\File Processing File\FirstFileProcessingRead.py", line 3, in main
infile = open(filename,'r')
IOError: [Errno 13] Permission denied: 'C:\\Users\\Manol\\OneDrive\\Documents\\Uni\\Programming\\File Processing File'
Aside from your permissions problem, does open() not need the file extension to function correctly?
aa = open("C:\\aaa\\bbb\\ccc\\ddd.json","r")
will work, whereas
aa = open("C:\\aaa\\bbb\\ccc\\ddd","r")
will return
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\aaa\\bbb\\ccc\\ddd'
As a way of testing folder permissions - copy the file to the same area as your .py and try opening it there. If you've still got same problems, then does your account have rights to the file? (right-click >> security)
See if file is encrypted and put two Backslash ( \\ ) or replace to Forward slash ( / ) and put extension of file
I change a few your code.
def main():
print("Please enter file name:")
filename = input()
infile = open(filename,'r')
data = infile.read()
print(data)
main()
Problem:
While installation when you select install python only for me then this issue is likely to happen because python is not granted with the permission to read every location, in your case One Drive.
Solution:
Place the file in your python file's root folder i.e inside the folder where you have placed the python file, then this will work.
You are also not providing extension (.txt). Don't forget to provide it while inputting the data.
I have a file of images and I want the folder to have a random file selected and that image to be displayed. This is the code I have so far:
dir = path.dirname(__file__)
examQ_dir = path.join(dir, 'Exam Questions')
question = choice(path.join(examQ_dir))
image_surface = pg.display.set_mode((850, 500))
image = pg.image.load(question)
And the error I get is as follows:
Traceback (most recent call last):
File "D:/A level Comp Sci/Platformer Game in Development Stages/Question.py", line 13, in <module>
image = pg.image.load(question)
pygame.error: Couldn't open E
And everytime I run it, the last letter of the error is slightly different sometimes it will say
pygame.error: Couldn't open i
And other times there's nothing there at all. I think there's something wrong with my logic of setting this up but I can't work out what. I'm using the PyCharm IDE.
You have to use os.listdir to get entries in the directory. Use os.isfile to evaluate if an entry is a file:
import os
import random
dir = os.path.dirname(__file__)
examQ_dir = os.path.join(dir, 'Exam Questions')
allpaths = [os.path.join(examQ_dir, entry) for entry in os.listdir(examQ_dir)]
filepaths = [p for p in allpaths if os.isfile(p)]
question = random.choice(filepaths)
Note, when you do question = choice(path.join(examQ_dir)), then the argument to choice is a string (the file path). You actually select a random letter form the file path.
I want to open a few files for game in kivy (instructions, about info...), so I don't have to have everything typed in the main.py but using those two methods it gives me an error.
class MenuScreen(Screen):
try:
#os.path.dirname(sys.argv[0])
#fullpath = os.path.join(os.path.dirname(sys.argv[0]), 'navodila.txt')
#instructions = StringProperty("")
#with open(fullpath, "r") as inst:
# for line in inst:
# instructions += line
instructions = ""
with open("navodila.txt", "r") as file:
for line in file:
instructions += line
except: instructions = "Instructions failed to load."
def show_popup_inst(self):
p = InstructionsPopup(content=Label(text=self.instructions, text_size=self.size))
p.open()
They both give me the same FileNotFoundError. I've checked at least five times and the file is there.
Traceback (most recent call last):
File "C:\Users\Lara\Desktop\KIVY\LARA\Snaky Game\SNAKY REAL\SnakyGame4.py", line 361, in <module>
class MenuScreen(Screen):
File "C:\Users\Lara\Desktop\KIVY\LARA\Snaky Game\SNAKY REAL\SnakyGame4.py", line 371, in MenuScreen
with open("navodila.txt", "r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'navodila.txt'
The try, except part is there just because I was working on code after trying reading a file.
Am I using the methods wrong? I've tried writing both of them outside any of the classes but it gave me the same error so I returned it inside in MenuScreen class.
It sounds like you want the working directory to be the same as the directory where the script lives. Here's a technique I use to keep track of relative paths (which revert to the calling path by default).
import os
script_path = os.path.dirname(os.path.realpath(__file__))
with open( os.path.join(script_path,"navodila.txt") , "r") as f:
do_stuff()
This way you just need to have the script and text file in the same directory and it doesn't matter where exactly they are stored in your filesystem or where you are calling the program from.