python 框选截屏
时间: 2024-01-14 11:21:54 浏览: 158
以下是使用Python实现框选截屏的方法:
1. 使用PyQt库实现框选截屏:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QRubberBand
from PyQt5.QtGui import QPixmap, QPainter, QPen
from PyQt5.QtCore import Qt, QRect
class ScreenshotWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Screenshot")
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
self.setWindowState(Qt.WindowFullScreen)
self.setMouseTracking(True)
self.rubberBand = QRubberBand(QRubberBand.Rectangle, self)
self.origin = None
def paintEvent(self, event):
if self.origin:
painter = QPainter(self)
painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
painter.drawRect(QRect(self.origin, self.end))
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.origin = event.pos()
self.end = event.pos()
self.rubberBand.setGeometry(QRect(self.origin, QSize()))
self.rubberBand.show()
def mouseMoveEvent(self, event):
if self.origin:
self.end = event.pos()
self.rubberBand.setGeometry(QRect(self.origin, self.end).normalized())
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.rubberBand.hide()
screenshot = QApplication.primaryScreen().grabWindow(0, self.origin.x(), self.origin.y(),
self.end.x() - self.origin.x(),
self.end.y() - self.origin.y())
screenshot.save("screenshot.png", "png")
self.close()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = ScreenshotWindow()
window.show()
sys.exit(app.exec_())
```
2. 使用Pillow库实现框选截屏:
```python
from PIL import ImageGrab
def screenshot():
im = ImageGrab.grab()
im.show()
if __name__ == "__main__":
screenshot()
```
阅读全文