这应该是DPI感知的问题,阅读这篇MSDN官方文档 https://learn.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows.
在 Windows 10 中:
你需要使用SetProcessDpiAwareness https://learn.microsoft.com/zh-cn/windows/win32/api/shellscalingapi/nf-shellscalingapi-setprocessdpiawareness(Or SetThreadDpiAwarenessContext https://learn.microsoft.com/windows/desktop/api/winuser/nf-winuser-setthreaddpiawarenesscontext),尝试使用:
import tkinter as tk
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(2) # your windows version should >= 8.1,it will raise exception.
root = tk.Tk()
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
print(width,height)
root.mainloop()
SetProcessDpiAwareness 的要求 https://learn.microsoft.com/zh-cn/windows/win32/api/shellscalingapi/nf-shellscalingapi-setprocessdpiawareness#requirements
在Windows XP或7中,您需要使用SetProcessDPIAware() https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setprocessdpiaware
所以所有的代码可能是:
import tkinter as tk
import ctypes
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2) # if your windows version >= 8.1
except:
ctypes.windll.user32.SetProcessDPIAware() # win 8.0 or less
root = tk.Tk()
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
print(width,height)
root.mainloop()
如果你使用tk.call('tk', 'scaling')
,也没关系。但是当你使用ImageGrab.grab((xxxx))
(以及那些需要传递位置参数的函数),也许它会得到错误的大小。