'Python script on MacOS - Unix executable works, exectuable (.app) doesn't (using py2app)

My code seems to somewhat be working when I run it via the Unix executable but whenever I run it with the .app after compiling it with py2app, I get the usual MacOS crash error message "script quit unexepectedly".

Here is my code in the two files that I use as well as the py2app setup.py file:

script.py:

import subprocess
import time
from tkinter import *
import gui

def batlvl_loop():
    while True:
        batLevel = subprocess.run(['''pmset -g batt | grep -Eo "\d+%" | cut -d% -f1'''], shell=True, capture_output=True, encoding="utf", errors="ignore")
        batLevel = batLevel.stdout.split("\n")[0]
        batLevel = int(batLevel)
        if batLevel < 1:
            gui.tkWin()
            break
        else:
            continue
batlvl_loop()

gui.py:

from tkinter import *
import subprocess
import time

win=Tk()
def btnClick():
    win.quit()

def tkWin():
    # Terminal command to verify current powerState (Charging or Discharging)
    powerState = subprocess.run(["pmset -g ps"], shell=True, capture_output=True, encoding="utf", errors="ignore")
    powerState = str(powerState)
    
    btn=Button(win, text="Close window", fg='green', command=btnClick)
    btn.place(x=80, y=100)

    # text label
    lbl=Label(win, text="This is Label widget", fg='red', font=("Helvetica", 16))
    lbl.place(x=60, y=50)

    win.title('BATTERY')

    Tk_Width = 350
    Tk_Height = 150

    # calculate coordination of screen and window form
    positionRight = int( win.winfo_screenwidth()/2 - Tk_Width/2 )
    positionDown = int( win.winfo_screenheight()/2 - Tk_Height/2 )

    # centered window
    win.geometry("{}x{}+{}+{}".format(500,200,positionRight, positionDown))
    
    if "discharging" in powerState:
        lbl=Label(win, text="You need to plug the cable", fg='red', font=("Helvetica", 16))
        lbl.place(x=80, y=75)
    elif " charging" in powerState:
        lbl=Label(win, text="unplug cable", fg='green', font=("Helvetica", 16))
        lbl.place(x=80, y=25)

    # window always on-top
    win.attributes('-topmost', True)
    win.update()

    #removes navigation buttons
    win.overrideredirect(1)

    win.mainloop()

setup.py (py2app setup file) :

from setuptools import setup

APP=['script.py']
OPTIONS={
    'argv_emulation': True,
}

setup(
    app=APP,
    options={'py2app': OPTIONS},
    setup_requires=['py2app']
)

What am I missing? Is it my code or how I've setup the py2app setup file?

Thank you



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source