How do I get monitor resolution in Python?

后端 未结 30 1097
深忆病人
深忆病人 2020-11-22 13:49

What is the simplest way to get monitor resolution (preferably in a tuple)?

相关标签:
30条回答
  • 2020-11-22 14:47

    Taken directly from an answer to this post: How to get the screen size in Tkinter?

    import tkinter as tk
    
    root = tk.Tk()
    
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    
    0 讨论(0)
  • 2020-11-22 14:47

    On Linux we can use subprocess module

    import subprocess
    cmd = ['xrandr']
    cmd2 = ['grep', '*']
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    p2 = subprocess.Popen(cmd2, stdin=p.stdout, stdout=subprocess.PIPE)
    p.stdout.close()
    
    resolution_string, junk = p2.communicate()
    resolution = resolution_string.split()[0]
    resolution = resolution.decode("utf-8") 
    width = int(resolution.split("x")[0].strip())
    heigth = int(resolution.split("x")[1].strip())
    
    0 讨论(0)
  • 2020-11-22 14:50

    A lot of these answers use tkinter to find the screen height/width (resolution), but sometimes it is necessary to know the dpi of your screen cross-platform compatible. This answer is from this link and left as a comment on another post, 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')
    

    The documentation for this says:

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

    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").

    0 讨论(0)
  • 2020-11-22 14:51

    For later versions of PyGtk:

    import gi
    gi.require_version("Gdk", "3.0")
    from gi.repository import Gdk
    
    display = Gdk.Display.get_default()
    n_monitors = display.get_n_monitors()
    print("there are %d monitors" % n_monitors)
    for m in range(n_monitors):
      monitor = display.get_monitor(m)
      geometry = monitor.get_geometry()
      print("monitor %d: %d x %d" % (m, geometry.width, geometry.height))
    
    0 讨论(0)
  • 2020-11-22 14:51

    For Linux, you can use this:

    import gi
    gi.require_version("Gdk", "3.0")
    from gi.repository import Gdk
    
    s = Gdk.Screen.get_default()
    screen_width = s.get_width()
    screen_height = s.get_height()
    print(screen_width)
    print(screen_height)
    
    0 讨论(0)
  • 2020-11-22 14:53

    Using Linux, the simplest way is to execute bash command

    xrandr | grep '*'
    

    and parse its output using regexp.

    Also you can do it through PyGame: http://www.daniweb.com/forums/thread54881.html

    0 讨论(0)
提交回复
热议问题