将Python程序标记为高DPI感知的无缝窗口

2024-09-28 22:21:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想分享我发现的最好的方法,以防其他人和我一样有问题。如果您的Python/Kivy程序在虚拟DPI伸缩方面存在图形问题,请尝试以下代码。它将标记为你或终端用户无需做任何事的高DPI感知程序。这适用于Windows10,不确定是8还是7。不知道是否有人知道这是否适用于8和7。要测试这一点,请添加代码,设置DPI,注销并重新登录用户,以便注册表标记DPI更改,并从SHELL运行代码。你的程序现在应该知道新闻部了!在

import winreg
from os import path as ospath
from os import execl as osexecl
from sys import executable as sysex
from sys import argv as sysargv

if __name__ == '__main__':
    reg = winreg.ConnectRegistry(None,winreg.HKEY_CURRENT_USER)
    key = winreg.OpenKey(reg, r"Control Panel\Desktop\WindowMetrics")
    print(winreg.QueryValueEx(key, 'AppliedDPI'))
    filefound=True
    if winreg.QueryValueEx(key, 'AppliedDPI')[0]!=96:
        key.Close()
        key = winreg.OpenKey(reg, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers", 0, winreg.KEY_ALL_ACCESS)

        ##If testing from SHELL also add these values into registry. This is not needed for complied EXEs. Make sure the path is correct or it won't work.

        winreg.SetValueEx(key, 'C:\python35\pythonw.exe', 0, winreg.REG_SZ, 'HIGHDPIAWARE')
        winreg.SetValueEx(key, 'C:\python35\python.exe', 0, winreg.REG_SZ, 'HIGHDPIAWARE')

        ##If Testing from SHELL change YOUREXE.exe to YOURPYFILE.py, otherwise it should be the name of your compiled EXE.

        exepath=str(ospath.abspath('YourEXE.exe'))
        try:
            winreg.QueryValueEx(key, exepath)
        except:
            print('FileNotFound')
            winreg.SetValueEx(key, exepath, 0, winreg.REG_SZ, 'HIGHDPIAWARE')
            print(winreg.QueryValueEx(key, exepath))
            filefound=False
    print(filefound)
    key.Close()
    reg.Close()

    ##If DPI Scaling was detected and program marked in registry, restart program. This will work in SHELL and your compiled EXE, not IDLE.

    if filefound==False:
        print('Restarting')
        python = sysex
        osexecl(python, python, * sysargv)
    else:
        YourApp().run()

Tags: key代码fromimport程序asregshell