pyecharts 嵌入 PyQt5

2020-08-13 11:30:18 浏览数 (2)

之前介绍过用pyecharts显示地图。下面先生成显示中国各省人口地图的网页。

代码语言:javascript复制
from pyecharts import options as opts
from pyecharts.charts import Map, Page
from pyecharts.faker import Collector, Faker

def readData(path):
    populations = list()
    with open(path,"rt",encoding="utf8") as f:#读取中文文本文件
        line = f.readline()
        while line:
            a = line[:-1].split("t")
            populations.append([a[0],int(a[1])])
            line = f.readline()
    return populations

C = Collector()
@C.funcs
def map_visualmap() -> Map:
    c = (
        Map()
        .add("中华人民共和国各省人口数(第6次人口普查)", populations, "china")
        .set_global_opts(
            title_opts=opts.TitleOpts(title="pyecharts 嵌入 PyQt5 DEMO"),
            visualmap_opts=opts.VisualMapOpts(max_=max_),
        )
    )
    return c
populations = readData("人口.txt")#从国家统计局官网下载
max_ = max(x[1] for x in populations)
Page().add(*[fn() for fn, _ in C.charts]).render("ChinaPopulationMap.html")

使用PyQt5的浏览器引擎控件即可加载网页到GUI界面中,效果如下:

源码:

代码语言:javascript复制
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication,QWidget,QHBoxLayout,QFrame
from PyQt5.QtWebEngineWidgets import QWebEngineView
import sys
 
class UI(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.mainLayout()
 
    def initUI(self):
        self.setWindowTitle("中国各省人口")
    def mainLayout(self):
        self.mainhboxLayout = QHBoxLayout(self)
        self.frame = QFrame(self)
        self.mainhboxLayout.addWidget(self.frame)
        self.hboxLayout = QHBoxLayout(self.frame)
        
        #网页嵌入PyQt5
        self.myHtml = QWebEngineView()##浏览器引擎控件
        #url = "http://www.baidu.com"
        #打开本地html文件#使用绝对地址定位,在地址前面加上 file:/// ,将地址的  改为/
        self.myHtml.load(QUrl("file:///E:/Python36/MyPythonFiles/pyecharts/ChinaPopulationMap.html"))
        
        self.hboxLayout.addWidget(self.myHtml)
        self.setLayout(self.mainhboxLayout)
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = UI()
    ex.show()
    sys.exit(app.exec_())

0 人点赞