Determine DPI / Scale Factor in Python TkInter Application

I want my app to detect that it is running on a HiDPI screen, and if so, scale itself up to be usable. As stated in this question , I know that I need to set a scaling factor and that this factor should be my DPI divided by 72; my problem is 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)

      

It doesn't work (testing on my 4k laptop screen). Upon further inspection, I realized that I was get_dpi()

returning 96.0 and that I was winfo_screenmmwidth()

returning 1016! (Luckily, my laptop is no more than a meter wide).

I'm guessing the TkInter here is calculating the width in mm from some internally detected DPI, mistakenly detected as 96, but I'm not sure where it gets that; I'm on Linux now and it xrdb -query

returns DPI 196, so it doesn't get DPI from the X server.

Does anyone know a cross-platform way to get my DPI on screen, or to get TkInter to get it right? Or, more importantly, how can I get TkInter to play well with HiDPI screens and also work fine on normal screens? Thank!

+3


source to share





All Articles