实现一个简单的html网页预览器
Python客栈
共 7899字,需浏览 16分钟
·
2021-12-20 04:05
本次分享实现一个简单的页面图片加载功能。本次代码结构由两个文件组成,主页面设置控制键和功能函数,通过页面鼠标点击事件响应调用open_html.py文件,新建窗体显示html网页图片。
#第一部分:主函数html_view.py文件,网页查看主页,点击标签lable响应循环切换加载html网页
from PyQt5.Qt import *
import os
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
class EventFilter(QWidget):
def __init__(self,parent=None):
super(EventFilter, self).__init__(parent)
self.file_name = self.setup_dir_fullname()
self.index = 0
self.setWindowTitle("html_view")
# 设置窗口图标
self.setWindowIcon(QIcon('icons/two.ico'))
self.label1 = QLabel("prev")
self.label2 = QLabel("next")
self.LabelState=QLabel("测试提示")
self.image1 = QImage("G:/Projectfile/icons/back.png")
self.image2 = QImage("G:/Projectfile/icons/next.png")
self.resize(400, 200)
# 关键1、对要过滤的控件设置installEventFilter,这些控件的所有事件都会被eventFilter函数接受并处理。
self.label1.installEventFilter(self)
self.label2.installEventFilter(self)
#设置网格布局
mainLayout=QGridLayout(self)
mainLayout.addWidget(self.label1,500,0)
mainLayout.addWidget(self.label2, 500, 2)
mainLayout.addWidget(self.LabelState, 600, 1)
self.setLayout(mainLayout)
print(self.file_name)
# 关键2、在eventFiltr函数中处理这些控件的事件信息。
def eventFilter(self, watched,event):
if watched == self.label1: #只对label1的点击事件进行过滤,重写行为,其他事件忽略
#鼠标按下事件(这里仅设置鼠标左键响应)
if event.type() ==QEvent.MouseButtonPress:
mouseEvent = QMouseEvent(event)
if mouseEvent.buttons() == Qt.LeftButton:
self.open(self.prev())
self.LabelState.setText(self.prev())
#缩放图片
transform=QTransform()
transform.scale(0.5,0.5)
tmp=self.image1.transformed(transform)
tmp2 = self.image2.transformed(transform)
self.label1.setPixmap(QPixmap.fromImage(tmp))
self.label2.setPixmap(QPixmap.fromImage(tmp2))
# 鼠标释放事件
if event.type() == QEvent.MouseButtonRelease:
self.label1.setPixmap(QPixmap.fromImage(self.image1))
if watched == self.label2: # 只对label2的点击事件进行过滤,重写行为,其他事件忽略
if event.type() == QEvent.MouseButtonPress:
mouseEvent = QMouseEvent(event)
if mouseEvent.buttons() == Qt.LeftButton:
self.open(self.next())
self.LabelState.setText(self.next())
# 转换图片大小
transform = QTransform()
transform.scale(0.5, 0.5)
tmp2 = self.image2.transformed(transform)
self.label2.setPixmap(QPixmap.fromImage(tmp2))
# 鼠标释放事件
if event.type() == QEvent.MouseButtonRelease:
self.label2.setPixmap(QPixmap.fromImage(self.image2))
return QWidget.eventFilter(self,watched,event)
def open(self,file_name1): # 显示窗体2
import open_html
self.second = open_html.myWindow(file_name1)
self.second.show()
def setup_dir_fullname(self):
# 初始化设置存储HTML文件的文件夹名称,默认“pic_html”,这里存放需要预览的html文件。
pyechart_dir = 'pic_html'
if not os.path.isdir(pyechart_dir):
os.mkdir(pyechart_dir)
self.path_dir_pyechart_html = os.getcwd() + os.sep + pyechart_dir
self.mylist = os.listdir(self.path_dir_pyechart_html)
return self.mylist
###等效代码###
# self.mylist = []
# for dirpath, dirnames, filenames in os.walk(self.path_dir_pyechart_html):
# for filepath in filenames:
# self.mylist.append(os.path.join(filepath))
def prev(self):
return self.show_file(-1)
def next(self):
return self.show_file(1)
def show_file(self, n):
self.index += n
if self.index < 0:
self.index = (len(self.file_name) - 1)
if self.index > (len(self.file_name) - 1):
self.index = 0
self.file_name1 = self.file_name[self.index]
return self.file_name1
if __name__ == '__main__':
import sys
# 1、创建一个应用程序对象
app = QApplication(sys.argv)
# 2、控件的操作
# 创建控件
window = EventFilter()
# 展示控件
window.show()
# 3、应用程序的执行,进入到消息循环
sys.exit(app.exec_())
#第二部分:调用open_html.py文件,新建窗体显示html
import os
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
import sys
class myWindow(QWidget):
def __init__(self,file_name):
super().__init__()
self.file_name=file_name
self.setWindowTitle("play")
# 设置窗口图标
self.setWindowIcon(QIcon('icons/pic.ico'))
self.resize(950,580)
self.mainLayout(self.file_name)
def mainLayout(self,file_name):
pyechart_dir = 'pic_html'
if not os.path.isdir(pyechart_dir):
os.mkdir(pyechart_dir)
self.path_dir_pyechart_html = os.getcwd() + os.sep + pyechart_dir
path_pyechart = self.path_dir_pyechart_html + os.sep +file_name
self.mainhboxLayout = QHBoxLayout(self)
self.frame = QFrame(self)
self.mainhboxLayout.addWidget(self.frame)
self.hboxLayout = QHBoxLayout(self.frame)
# 网页嵌入PyQt5
self.myHtml = QWebEngineView() ##浏览器引擎控件
self.myHtml.setGeometry(50,20,1000,600)
# 打开本地html文件#使用绝对地址定位,在地址前面加上 file:/// ,将地址的 \ 改为/
self.myHtml.load(QUrl.fromLocalFile("file:/{0}".format(path_pyechart)))
self.hboxLayout.addWidget(self.myHtml)
self.setLayout(self.mainhboxLayout)
#测试
# if __name__ == '__main__':
# app = QApplication(sys.argv)
#
# main = myWindow(file_name)
#
# main.show()
# # main.showMaximized()
# sys.exit(app.exec_())
import os
import tkinter
import tkinter.messagebox
from PIL import Image, ImageTk
# 创建tkinter应用程序窗口
root = tkinter.Tk()
# 设置窗口的大小和位置
root.geometry('430x650+40+30')
# 不允许改变窗口的大小
root.resizable(False, False)
# 设置窗口主题
root.title('PIC-view')
root.iconbitmap(r'.\Projectfile\test\two.ico')
# 获取当前文件夹中所有图片文件列表
suffix = ('.jpg', '.bmp', '.png')
pics = [p for p in os.listdir('./Projectfile/test') if p.endswith(suffix)]
pics.sort(key=lambda item: int(item[:item.index('.')]))
current = 0
def changePic(flag):
global current
new = current + flag
if new < 0:
tkinter.messagebox.showerror('', '这已经是第一张图片了')
elif new >= len(pics):
tkinter.messagebox.showerror('', '这已经是最后一张图片了')
else:
# 获取要切换图片文件名
pic = pics[new]
# 创建Image对象并进行缩放
im = Image.open('./Projectfile/test/{}'.format(pic))
w, h = im.size
# 这里假设用来显示图片的Label组件尺寸为 400x600
if w > 400:
h = int(h * 400 / w)
w = 400
if h > 600:
w = int(w * 600 / h)
h = 600
im = im.resize((w, h))
# 创建image对象,并设置Label组件图片
im1 = ImageTk.PhotoImage(im)
lbPic['image'] = im1
lbPic.image = im1
current = new
# 上一张的按钮
def btnPreClick():
changePic(-1)
# 下一张按钮
def btnNextClick():
changePic(1)
def get_ico(path):
ico_img = Image.open(path).resize((32, 32))
icoBtn = ImageTk.PhotoImage(image=ico_img)
return icoBtn
pr = get_ico(r'.\Projectfile\icons\back.png')
nt = get_ico(r'.\Projectfile\icons\next.png')
btnPre = tkinter.Button(root, image=pr, command=btnPreClick)
btnPre.place(x=100, y=20, width=80, height=30)
btnNext = tkinter.Button(root, image=nt, command=btnNextClick)
btnNext.place(x=230, y=20, width=80, height=30)
# 用来显示图片的Label组件
lbPic = tkinter.Label(root, text='test', width=400, height=600)
changePic(0)
lbPic.place(x=10, y=50, width=400, height=600)
# 启动
root.mainloop()
2、XShell 收费?5款免费且超赞的SSH工具,一个比一个香!
4、Log4j2维护者吐槽没工资还要挨骂,GO安全负责人建议开源作者向公司收费
5、欠债3000亿,宣布破产!昔日民族品牌,为何总沦为反面教材?
评论