一、Python獲取屏幕分辨率大小
import tkinter as tk root = tk.Tk() width = root.winfo_screenwidth() height = root.winfo_screenheight() print("屏幕寬度:%d,屏幕高度:%d" % (width, height))
使用tkinter庫中的Tk()類創建一個窗口實例root,然後調用root實例的winfo_screenwidth()和winfo_screenheight()方法分別獲取屏幕寬度和屏幕高度。最後輸出結果。
二、Python獲取屏幕
from PIL import ImageGrab im = ImageGrab.grab() im.show()
使用Pillow庫(PIL)中的ImageGrab模塊的grab()函數可以截取整個屏幕的圖像,並保存在Image對象中。然後可以使用show()方法將其顯示出來。
三、Python獲取屏幕上的字
from PIL import ImageGrab import pytesseract im = ImageGrab.grab() text = pytesseract.image_to_string(im, lang='chi_sim') print(text)
使用Pillow庫中的ImageGrab模塊的grab()函數截取整個屏幕的圖像,然後使用pytesseract庫中的image_to_string()函數將圖像中的文字轉為字符串。lang參數指定轉換的語言,’chi_sim’表示中文簡體。最後輸出識別出來的內容。
四、Python獲取屏幕中的指定區域
from PIL import ImageGrab bbox = (100, 100, 300, 300) # 區域左上、右下坐標 im = ImageGrab.grab(bbox) im.show()
使用Pillow庫中的ImageGrab模塊的grab()函數可以截取指定區域的圖像,並保存在Image對象中。bbox參數為四元組,分別為區域的左上、右下坐標。然後可以使用show()方法將其顯示出來。
五、Python獲取屏幕指定區域內的顏色
from PIL import ImageGrab bbox = (100, 100, 300, 300) # 區域左上、右下坐標 im = ImageGrab.grab(bbox) color = im.getpixel((50, 50)) print(color)
使用Pillow庫中的ImageGrab模塊的grab()函數截取指定區域的圖像,並保存在Image對象中。getpixel()方法獲取坐標點的顏色值,返回一個元組表示RGB值。這裡獲取的是(50, 50)這個點的顏色值。
六、Python獲取屏幕的DPI
import ctypes user32 = ctypes.windll.user32 dc = user32.GetDC(0) dpi = user32.GetDeviceCaps(dc, 88), user32.GetDeviceCaps(dc, 90) print("DPI:", dpi)
使用ctypes庫調用Windows API函數獲取屏幕DPI(每英寸像素數)。先獲取屏幕設備上下文DC,然後使用GetDeviceCaps()函數分別獲取水平和垂直方向的DPI值。
七、Python獲取屏幕的縮放比例
import ctypes user32 = ctypes.windll.user32 k = user32.GetDpiForSystem() / 96 print("縮放比例:%f" % k)
使用ctypes庫調用Windows API函數獲取當前系統縮放比例。GetDpiForSystem()函數返回的是DPI與標準DPI值(96)的比值,即縮放比例。
八、Python獲取屏幕截圖並保存
from PIL import ImageGrab im = ImageGrab.grab() im.save("screen.png")
使用Pillow庫中的ImageGrab模塊的grab()函數可以截取整個屏幕的圖像,並保存在Image對象中。然後使用save()方法將其保存為指定的文件。這裡保存為screen.png文件。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/193525.html