我正在尝试创建一个 Python 代码,稍后我将使用 PyInstaller 将其转换为 Windows 可执行文件 (.exe)。该代码应该在窗口中显示一条消息,并将代码的Windows快捷方式(.lnk)添加到运行它的计算机的启动文件夹(shell:startup)中,以便每次计算机运行该代码启动。
这是我的代码:
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()
我希望这段代码能够在一个框中显示消息,并将代码的快捷方式添加到启动文件夹中。它完成了我期望的一切,但快捷方式在某种程度上无效,并且没有“打开”按钮。看照片:,。
检查这个答案,它将很有用:如何使用 setuptools Windows 安装程序在开始菜单中创建快捷方式
或者,这是链接帖子的答案:
就像其他人在这里和其他地方评论的那样,支持功能并不 似乎完全可以工作(至少不能使用setuptools)。经过一整天的搜索各种资源后,我找到了一种方法来至少创建 桌面快捷方式。我正在分享我的解决方案(基本上是我的代码的混合体) 在这里和这里找到)。我应该补充一点,我的情况与 yasar 的,因为它创建了已安装包的快捷方式(即 Python 脚本目录中的 .exe > 文件)而不是脚本。
简而言之,我在 setup.py 中添加了一个 post_install 函数,然后使用 用于 Windows 的 Python 扩展,用于创建快捷方式。的位置 桌面文件夹是从 Windows 注册表中读取的(还有其他方法可以实现这一点,但如果桌面处于非标准状态,它们可能不可靠) 位置)。
#!/usr/bin/env python
import os
import sys
import sysconfig
if sys.platform == 'win32':
from win32com.client import Dispatch
import winreg
def get_reg(name,path):
# Read variable from Windows Registry
# From https://stackoverflow.com/a/35286642
try:
registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0,
winreg.KEY_READ)
value, regtype = winreg.QueryValueEx(registry_key, name)
winreg.CloseKey(registry_key)
return value
except WindowsError:
return None
def post_install():
# Creates a Desktop shortcut to the installed software
# Package name
packageName = 'mypackage'
# Scripts directory (location of launcher script)
scriptsDir = sysconfig.get_path('scripts')
# Target of shortcut
target = os.path.join(scriptsDir, packageName + '.exe')
# Name of link file
linkName = packageName + '.lnk'
# Read location of Windows desktop folder from registry
regName = 'Desktop'
regPath = r'Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders'
desktopFolder = os.path.normpath(get_reg(regName,regPath))
# Path to location of link file
pathLink = os.path.join(desktopFolder, linkName)
shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(pathLink)
shortcut.Targetpath = target
shortcut.WorkingDirectory = scriptsDir
shortcut.IconLocation = target
shortcut.save()
setup(name='mypackage',
...,
...)
if sys.argv[1] == 'install' and sys.platform == 'win32':
post_install()