The PyQT5 ui file fails to load correctly when running the executable

Currently, I am in the process of developing a PyQt5 application using the designer to create interfaces and then exporting them as .ui files. These files are subsequently loaded by my primary class. Below is an excerpt from my code snippet, named main.py:

main.py

import os.path
import PyQt5.QtWidgets as qtw
from PyQt5.uic import loadUi
import sys

class MainUI(qtw.QMainWindow):
    def __init__(self, parent=None):
        super(MainUI, self).__init__()
        self._ui_path = os.path.dirname(os.path.abspath(__file__))
        loadUi(os.path.join(self._ui_path, 'main.ui'), self)

if __name__ == "__main__":
    # Initialize the application
    app = qtw.QApplication(sys.argv)
    # Create and display the main window of the application
    win = MainUI()
    win.show()
    sys.exit(app.exec())

main.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>320</width>
    <height>240</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QPushButton" name="pushButton">
    <property name="geometry">
     <rect>
      <x>110</x>
      <y>100</y>
      <width>88</width>
      <height>27</height>
     </rect>
    </property>
    <property name="text">
     <string>ok</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>320</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

To generate an executable for this project, I utilize pyinstaller with the command pyinstaller -F -w main.py.

Upon initial execution, the executable file must be located in the same directory as the .ui file. To resolve issues related to loading the UI, I modified the loadUI function based on the response provided here.

However, upon running the executable, an error message emerged along with the following traceback:

Traceback (most recent call last):
  File "main.py", line 17, in <module>
    win = MainUI()
  File "main.py", line 11, in __init__
    loadUi(os.path.join(self._ui_path, 'main.ui'), self)
  File "PyQt5\uic\__init__.py", line 238, in loadUi
  File "PyQt5\uic\Loader\loader.py", line 66, in loadUi
  File "PyQt5\uic\uiparser.py", line 1020, in parse
  File "xml\etree\ElementTree.py", line 1202, in parse
  File "xml\etree\ElementTree.py", line 584, in parse
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\username\\AppData\\Local\\Temp\\_MEI187162\\main.ui'

The issue arises from the fact that after executing the .exe file, a temporary directory is created containing various dll files. Unfortunately, the program attempts to locate the .ui file within this directory, leading to failure. What steps can I take to direct the executable to the correct location of the .ui file?

Answer №1

Make sure to include the following code snippet at the beginning of your program:

import sys
import os

if getattr(sys, 'frozen', False):
    RELATIVE_PATH = os.path.dirname(sys.executable)
else:
    RELATIVE_PATH = os.path.dirname(__file__)

Next, when you are ready to use loadUi():

self._ui_path = RELATIVE_PATH + "/ui_path"  # Modify this accordingly

loadUi(os.path.join(self._ui_path, 'main.ui'), self)

Sometimes, running compiled programs in different locations can cause directory issues. Give this solution a try and let me know if it works for you. If not, feel free to reach out for further assistance.

Answer №2

I decided to revert back from using PyQt5 version 5.15.7 to version 5.15.1 by running the command "pip install PyQt5==5.15.1". Thankfully, this solved my issue.

Here's a snippet of my code:

from PyQt5.QtWidgets import QApplication
from PyQt5 import uic

class UI(QWidget):
    def __init__(self):
        super(UI,self).__init__()

        # Loading the ui file with uic module
        uic.loadUi("*xxxxxx*.ui", self)

app = QApplication([])
window = UI()
window.show()
app.exec()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Python: Techniques for zooming out from a webpage with selenium

In an attempt to zoom out to 25% using my Python Selenium program, I want to go from this: https://i.stack.imgur.com/6hPjF.png to this: https://i.stack.imgur.com/4LFMj.png When zoomed out to 25%, all the elements that should be visible while scrolling d ...

Error: WebDriverException - Error message: Unable to establish connection with Chrome browser, despite working perfectly just a minute

For the past 15 minutes, my Selenium scraper was functioning perfectly fine until it suddenly started throwing an error every time I run it. Here is the relevant code snippet: searchDate = wait.until(EC.element_to_be_clickable((By.XPATH, "/input[@placehol ...

Issue encountered with Stylegan2-ada tfrecords: ValueError due to mismatched axes in array causing images to function intermittently

Currently, I am in the process of training a GAN using Google Colab with a dataset of images sourced from Wikiart that have been converted to 1024x1024 resolution. However, I keep encountering an error when attempting to create the tfrecords: Traceback (mo ...

Unable to access Twitter through Selenium WebDriver

Check out my code snippet driver_path = Service(r"C:\Users\Lenovo\Desktop\chromedriver.exe") driver = webdriver.Chrome(service=driver_path) driver.get('https://twitter.com/login/') WebDriverWait(driver, 10).until(EC ...

Issue with database setup in Django-Pytest setup_method

I am currently working on Ubuntu 14.04 with the following setup: python 2.7.6 django 1.7 [I have also tested with django 1.9] pytest-django 2.8.0 [also tried with 2.9.1] pytest 2.7.2 [also experimented with 2.8.3] Below is a snippet of the test code in ...

Python application for flattening and mapping nested JSON keys

I am completely new to JSON and struggling with understanding the structure of a JSON file. Here is an example of a JSON file I have: {"employeeId":{"0":02100, "1":02101, "2":02102,... "1000000":021000000}, "employeeName":{"0":"Smith", "1":"John", "2":" ...

Using Python and BeautifulSoup to Extract CME Data

Seeking assistance in extracting a specific list of symbols along with their corresponding prices from the CME website. I have successfully gathered a list of symbols, but am struggling to retrieve the prices displayed in each row. Encountering difficulti ...

Simpler method for generating a JSON object from an SQL data entity

UPDATE - I have modified the code below to handle ForeignKeys, Decimal numbers (even though a forced float conversion is used). It now returns a dictionary so it can be recursive. from sqlobject import SQLObject from decimal import Decimal def sqlobject_ ...

Discovering the art of clicking at random on a webpage using Selenium in Python, along with mastering the techniques of zooming in on a webpage

Is there a way to click randomly within a specific area on a webpage using selenium? I am also curious about how to zoom in on a designated portion of a page, rather than the entire page. For example, if a page is x by y in dimensions, how can one zoom int ...

Integrating Python Script with User Input and Output within a JavaScript Web Application

I have an existing JS website that requires additional functionality, and after some research I believe Python is the best tool to handle the necessary calculations. My goal is for users to input information that will then be used as input for my Python ...

List with dynamic substrings. Ten elements preceding the variable

I am struggling with dynamic substrings. My list can vary in size, containing anywhere from 20 to 1000 elements. I want to create a new list based on a variable number that includes elements starting from -10 up to that variable. For instance (using pseudo ...

Python - error: exceeding index range

I am currently working on an example text from Python. Afghanistan:32738376 Akrotiri:15700 Albania:3619778 Algeria:33769669 American Samoa:57496 Andorra:72413 Angola:12531357 Anguilla:14108 Antigua and Barbuda:69842 Argentina:40677348 ...

Optimal method for shuffling a matrix in either R or Python

Currently, I am dealing with a large numeric matrix M in R that consists of 11000 rows and 20 columns. Within this matrix, I am conducting numerous correlation tests. Specifically, I am using the function cor.test(M[i,], M[j,], method='spearman' ...

Accessing and manipulating web elements using either XPath or CSS selectors

Having trouble selecting a specific piece of information using xpath or css selector. Error messages keep appearing. Can someone help identify the issue? This snippet is from my code: output = driver.find_element_by_xpath("//td[@class_= 'sku']" ...

Exploring the interactions between two interconnected dynamic systems using Python simulation

I am looking to visualize two identical dynamical systems that are connected in a coupled manner. Given the following: X = [x0,x1,x2] U = [u0,u1,u2] And Xdot = f(X) + alpha*(U-X) Udot = f(U) + alpha*(X-U) My goal is to plot the solution of this syst ...

Can you please provide the password needed to enable the "safaridriver" command?

Can you remind me of the password needed for running the command "safaridriver --enable" on my MAC? Whenever I try to execute "safaridriver --enable" in the terminal, my MAC prompts me for a password. I have entered the sudo command's password, but i ...

When it comes to E2E testing with an Angular, Python, and MongoDB web stack, which tool is more effective: Selenium or Protractor?

Just discovered the protractor framework, which offers end-to-end testing for Angular applications. I'm curious to know which test framework is more suitable for the webstack I am using - Angular, Python, and MongoDB. Should I go with Selenium or Pro ...

Regular Expression - Replace all non-alphanumeric characters and accents with empty strings

Is there a way to remove all special characters except alphanumeric and accents? I attempted the following: text = 'abcdeáéí.@# ' re.sub(r'[^a-zA-Z0-9áéíóúÁÉÍÓÚâêîôÂÊÎÔãõÃÕçÇ: ]', ' ', text) Unfor ...

What are the ways in which Ajax can be utilized to interact with a dynamically updated Django dropdown

I'm currently developing a web application that involves calculating the distance between two addresses using Google Maps and determining the gas cost based on the vehicle's mpg rating. The project is almost complete, but I need to implement AJAX ...

Removing the Add button from inline forms in Django 1.7

I'm currently facing an issue with a seemingly simple task. I have editable models (Prodotto, Comune) displayed as "addable" fields in the form below. However, I want to remove the + (add) button for these specific fields without disabling the ability ...