How should I create a shortcut using Python and add it to the startup folder of the computer?

166 Views Asked by At

I am trying to create a Python code that I will later convert to a Windows executable (.exe) using PyInstaller. The code is supposed to display a message in a window, and add a Windows shortcut (.lnk) of the code to the startup folder (shell:startup) of the computer it is run on so that the code is run every time the computer starts up.

Here is my code:

import tkinter as tk
import tkinter.messagebox as messagebox
import os
import shutil

# Create a message box with a button
root = tk.Tk()
root.withdraw()
messagebox.showinfo("Startup App", "Hello! This is a startup application.")
# Get the path to the current directory
current_dir = os.path.dirname(os.path.abspath(__file__))
# Create a shortcut file
shortcut_path = os.path.join(os.path.expanduser('~'), 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', 'StartupApp.lnk')
# Create a shortcut to the executable in the startup folder
shutil.copy2(os.path.join(current_dir, 'experiment.py'), shortcut_path)
# Exit the application
exit()

I was expecting this code to display the message in a box, and add a shortcut of the code to the startup folder. It did everything I expected it to, but the shortcut was invalid of some kind, and had no 'Open' button. See photos: invalid shortcut generated by code, valid shortcut manually made.

0

There are 0 best solutions below