用python写一个GIS界面,界面有一个按钮,点击按钮可以选择本地dwg和shp文件进行显示
时间: 2024-06-11 11:10:27 浏览: 161
这是一个基于PyQt5的简单示例,可以实现你所描述的功能:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFileDialog
from PyQt5.QtGui import QPixmap
import ezdxf
import shapefile
class GISViewer(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 800, 600)
self.setWindowTitle('GIS Viewer')
# 创建按钮
self.btn = QPushButton('选择文件', self)
self.btn.move(20, 20)
self.btn.clicked.connect(self.selectFile)
# 创建用于显示DWG和SHP文件的标签
self.dwgLabel = QLabel(self)
self.dwgLabel.setGeometry(20, 60, 380, 520)
self.shpLabel = QLabel(self)
self.shpLabel.setGeometry(400, 60, 380, 520)
self.show()
def selectFile(self):
# 打开文件选择对话框
fileNames, _ = QFileDialog.getOpenFileNames(self, '选择文件', '', 'DWG Files (*.dwg);;SHP Files (*.shp)')
# 加载DWG和SHP文件到标签中
for fileName in fileNames:
if fileName.endswith('.dwg'):
self.loadDwg(fileName)
elif fileName.endswith('.shp'):
self.loadShp(fileName)
def loadDwg(self, fileName):
# 使用ezdxf库加载DWG文件
doc = ezdxf.readfile(fileName)
modelspace = doc.modelspace()
msp = list(modelspace)
if msp:
# 将DWG文件转换为QPixmap并显示在标签上
pix = QPixmap.fromImage(msp[0].render(qt_mode=True))
self.dwgLabel.setPixmap(pix)
def loadShp(self, fileName):
# 使用shapefile库加载SHP文件
sf = shapefile.Reader(fileName)
shapes = sf.shapes()
if shapes:
# 创建一个空的QImage,大小与标签相同
img = QImage(self.shpLabel.width(), self.shpLabel.height(), QImage.Format_RGB32)
img.fill(Qt.white)
painter = QPainter(img)
# 遍历所有形状并绘制
for shape in shapes:
points = shape.points
if shape.shapeType == shapefile.POLYGON:
# 绘制多边形
polygon = QPolygonF([QPointF(x, y) for x, y in points])
painter.drawPolygon(polygon)
elif shape.shapeType == shapefile.POLYLINE:
# 绘制折线
polyline = QPolygonF([QPointF(x, y) for x, y in points])
painter.drawPolyline(polyline)
painter.end()
# 将QImage转换为QPixmap并显示在标签上
pix = QPixmap.fromImage(img)
self.shpLabel.setPixmap(pix)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = GISViewer()
sys.exit(app.exec_())
```
这个界面中有一个“选择文件”按钮,点击后可以选择DWG和SHP文件。选择的文件将显示在左侧和右侧的标签中。DWG文件使用ezdxf库加载并显示,SHP文件使用shapefile库加载并绘制在QImage上,然后将QImage转换为QPixmap并显示。
阅读全文