[Python] Changing matplotlib backend to Qt alters system DPI in Jupyter Notebook

Discussão em 'Python' iniciado por Stack, Janeiro 27, 2025.

  1. Stack

    Stack Membro Participativo

    For some quick background, I have tested this on a 4K monitor (28 inch diagonal) at 200% scaling, and a 1920x1200 monitor (16 inch diagonal) with 125% scaling, both have the same behavior. All of this code is executed in a Jupyter Notebook inside of VS Code using the Microsoft-supplied Jupyter extension.

    In a script I wrote recently, I noticed that when using filedialog.askopenfilename() on a 4K monitor at 200% scaling, the file dialog was at 1920x1080 resolution, instead of the expected 4K. I then implemented some plotting stuff in the script, and used %matplotlib qt to switch the backend of matplotlib to Qt for some reason that I can't recall. After changing this, I noticed that all of my Tkinter windows were at the correct resolution, even though I had not changed anything directly relating to Tkinter.

    I tried to figure out what was changed, and ran the following code to check what thing actually got changed. I ran this on my laptop, which has a 1920x1200 monitor (16 inch diagonal).

    import tkinter
    from win32api import GetSystemMetrics
    import ctypes

    # Comment out the line below to see the difference (Requires restarting the Jupyter Kernel)
    %matplotlib qt

    root = tkinter.Tk()
    dpi = root.winfo_fpixels('1i')
    print('Tkinter DPI is:', dpi)

    print("Width =", GetSystemMetrics(0))
    print("Height =", GetSystemMetrics(1))

    print('Process DPI Awareness: ', ctypes.windll.shcore.GetProcessDpiAwareness())


    The output from this WITHOUT %matplotlib qt is:

    Tkinter DPI is: 96.09458128078816
    Width = 1536
    Height = 960
    Process DPI Awareness: 0


    And when I run the code WITH %matplotlib qt I get:

    Tkinter DPI is: 120.11822660098522
    Width = 1920
    Height = 1200
    Process DPI Awareness: 0


    Clearly the DPI Awareness was not altered, unless I've made a mistake in checking that. I have no ideas for what is happening, and after searching through the matplotlib github and the ipympl github pages, but to no avail.

    Continue reading...

Compartilhe esta Página