在Python TkInter应用程序中检测DPI /缩放因子 [英] Detect DPI/scaling factor in Python TkInter application

查看:428
本文介绍了在Python TkInter应用程序中检测DPI /缩放因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的应用程序能够检测它是否在HiDPI屏幕上运行,如果可以,请进行自我扩展以使其可用。如此问题中所述,我知道我需要设置一个比例因子,并且该因子应该是我的DPI除以72;我的麻烦是获取我的DPI。这就是我所拥有的:

I'd like my application to be able to detect if it's running on a HiDPI screen, and if so, scale itself up so as to be usable. As said in this question, I know I need to set a scaling factor, and that this factor should be my DPI divided by 72; my trouble is in getting my DPI. Here's what I have:

def get_dpi(window):
    MM_TO_IN = 1/25.4
    pxw = window.master.winfo_screenwidth()
    inw = window.master.winfo_screenmmwidth() * MM_TO_IN
    return pxw/inw

root = Tk()
root.tk.call('tk', 'scaling', get_dpi(root)/72)

这不起作用(在我的4k笔记本电脑屏幕上测试)。经过进一步检查,我发现 get_dpi()返回96.0,而 winfo_screenmmwidth()返回1016! (非常感谢,我的笔记本电脑的宽度没有超过一米。)

This doesn't work (testing on my 4k laptop screen). Upon further inspection, I realized get_dpi() was returning 96.0, and that winfo_screenmmwidth() was returning 1016! (Thankfully, my laptop is not over a meter wide).

我假设TkInter在这里是根据一些内部检测到的DPI计算出以毫米为单位的宽度,错误地将其检测为96 ,但我不确定从哪里得到的;我目前在Linux上, xrdb -query 返回的DPI为196,因此它没有从X服务器获取DPI。

I assume that TkInter is here calculating the width in mm from some internally-detected DPI, wrongly detected as 96, but I'm not sure where it's getting this; I'm currently on Linux, and xrdb -query returns a DPI of 196, so it's not getting the DPI from the X server.

有人知道跨平台获取我的屏幕DPI或使TkInter能够正确获取它的方法吗?或者,更重要的是:如何使TkInter在HiDPI屏幕上表现出色,并且在正常屏幕上也能正常工作?谢谢!

Does anyone know a cross-platform way to get my screen DPI, or to make TkInter be able to get it properly? Or, more to the point: how can I make TkInter play nice with HiDPI screens and also work fine on normal ones? Thanks!

推荐答案

此答案来自此链接,并留在上面,但进行搜索需要花费数小时的时间。我还没有任何问题,但是请让我知道它是否在您的系统上不起作用!

This answer is from this link and left as a comment above, but it took hours of searching to find. I have not had any issues with it yet, but please let me know if it does not work on your system!

import tkinter
root = tkinter.Tk()
dpi = root.winfo_fpixels('1i')

此文档说:

winfo_fpixels(number)
# Return the number of pixels for the given distance NUMBER (e.g. "3c") as float

距离数是一个数字,后跟一个单位,因此3c表示3厘米,该函数给出像素数在屏幕3厘米处(如此处找到)。
因此,要获得dpi,我们要求函数提供1英寸屏幕( 1i)中的像素数。

A distance number is a digit followed by a unit, so 3c means 3 centimeters, and the function gives the number of pixels on 3 centimeters of the screen (as found here). So to get dpi, we ask the function for the number of pixels in 1 inch of screen ("1i").

这篇关于在Python TkInter应用程序中检测DPI /缩放因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆