Hello I can’t get an app to self uninstall. After converting a .py script to .exe when I press the button it is supposed to delete/uninstall itself from my computer.
Actually I would like it to uninstall completely from my computer after pressing the button from the .exe how to do it?
Here is the code:
from tkinter import * import os root = Tk() root.geometry("300x400") def func(*args): os.remove(__file__) root.destroy() Button1 = Button(root,text="Delete",fg="green",width=10,height=5) Button1.pack(side=TOP) Button1.bind('<Button-1>', func) root.mainloop()
I expect the program to self uninstall after I press the button and I tried the code above that doesn’t work (when I convert the .py file to a .exe file the exe file is not deleting itself when I press the button on the .exe file)
EDIT: The code above work with python file .py but not with .exe files ! why ?
Advertisement
Answer
After a lot of searching, I found a solution using this answer!
The trick is to start a separate external process that deletes the file after a delay
from tkinter import Tk, Button, TOP import subprocess import sys def func(*args): root.destroy() subprocess.Popen(f"cmd /c ping localhost -n 3 > nul & del {sys.executable}") root = Tk() root.geometry("300x400") Button1 = Button(root,text="Delete",fg="green",width=10,height=5) Button1.pack(side=TOP) Button1.bind('<Button-1>', func) root.mainloop()
This answer explains why you should use sys.executable
instead of __file__
inside the exe
I tried these approaches without success
- Registering the removal of the file with
atexit
- Starting a daemon thread to remove the file after a delay with
threading
- Starting a daemon process to remove the file after a delay with
multiprocessing
- Running
os.chmod
to change permissions - Running as administrator
Tested with pyinstaller --onefile randomtesting.py
(pip install pyinstaller
)