如何让Windows 11上下文菜单项与我的PyQt6应用程序一起工作?



我有一个python脚本,我想从Windows 11/10右键单击我的文档文件夹中的上下文菜单运行"C:\Users\me\Documents\PythonScripts\main.py"

from PyQt6.QtWidgets import QApplication, QWidget
app = QApplication([])
window = QWidget()
window.setWindowTitle('My PyQt6 Application')
window.resize(400, 300)
window.move(100, 100)
window.show()
app.exec()

我创建了一个python脚本,通过注册表将一个项目添加到Windows 11的右键上下文菜单中。

但是,我遇到的问题是,当我试图点击"我的Python脚本"在上下文菜单中,应该弹出一个pyqt6窗口。

我试着在终端窗口运行这个命令C:UsersmeAppDataLocalProgramsPythonPython311python.exe C:UsersmeDocumentsPythonScriptsmain.py "%V"运行正常

import winreg
menu_name = "My Python Script"
icon_path = "%SystemRoot%\system32\imageres.dll,3"
python = "C:\Users\me\AppData\Local\Programs\Python\Python311\python.exe"
command = f"{python} C:\Users\me\Documents\PythonScripts\main.py "%V""

key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT,
r"DirectoryBackgroundshell",
0, winreg.KEY_WRITE)
menu_key = winreg.CreateKey(key, menu_name)

winreg.SetValueEx(menu_key, "Icon", 0, winreg.REG_SZ, icon_path)
winreg.SetValueEx(menu_key, "command", 0, winreg.REG_SZ, command)

winreg.CloseKey(menu_key)
winreg.CloseKey(key)

我找到了问题所在。我添加的命令键不正确。我需要使用command_key = winreg.CreateKey(menu_key, "command")来执行命令。然后添加"winreg.SetValueEx(command_key, "", 0, winreg.REG_SZ, command)"。

import winreg
# Name that will appear in the context menu
menu_name = "My Python Script"
# Path to the icon file
icon_path = "%SystemRoot%\system32\imageres.dll,3"
python = "C:\Users\me\AppData\Local\Programs\Python\Python311\python.exe"
# Path to the Python script and any command-line arguments
command = f"{python} C:\Users\me\Documents\PythonScripts\main.py "%V""
# Open the registry key
key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT,
r"DirectoryBackgroundshell",
0, winreg.KEY_WRITE)
# Create a new key for our menu item
menu_key = winreg.CreateKey(key, menu_name)
command_key = winreg.CreateKey(menu_key, "command")
# Set the menu item's icon
winreg.SetValueEx(menu_key, "Icon", 0, winreg.REG_SZ, icon_path)
# Create a new key for our menu item
winreg.SetValueEx(command_key, "", 0, winreg.REG_SZ, command)
# Close the keys
winreg.CloseKey(menu_key)
winreg.CloseKey(command_key)
winreg.CloseKey(key)

最新更新