######Python +pyqt5实现pandas的可视化
请问一下 通过在主界面点击‘课表’按钮 如何将课表界面 运行出来而不退出原来的窗口
这是主界面
这是‘课表’pandas的可视化界面
这是主界面的代码
import sys
from PyQt5 import QtCore, QtWidgets, QtCore
from interface import Ui_MainWindow_inter
import requests
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QApplication
from lxml import html
from PyQt5.QtCore import QTimer,QDateTime
import pandas as pd
import matplotlib.pyplot as plt
from login import Ui_MainWindow
import login
from PyQt5.QtGui import *
from PyQt5.Qt import *
from PyQt5.QtCore import *
import sys,math,string
from kebiao import PdTable as kebiao_UI
from kebiao import g
from login import Ui_MainWindow as login_UI
from interface import Ui_MainWindow_inter as interface_UI
from calculator import Calculator as Calculator_UI
from huaban import Example as huaban_UI
class mainface (QMainWindow,login_UI):
face1=QtCore.pyqtSignal()
# face2=QtCore.pyqtSignal() #跳转信号
def __init__(self,parent=None):
super().__init__(parent)
self.setupUi(self)
self.ui=Ui_MainWindow()
self.pushButton_3.clicked.connect(self.logindef)
# 设置窗口标志:隐藏窗口边框
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.setWindowFlags(Qt.FramelessWindowHint)
self.pushButton.clicked.connect(self.click_pushButton_1)
self.pushButton_2.clicked.connect(self.click_pushButton_2)
def click_pushButton_1(self):
# self.textEdit.append("当前动作:click_pushButton(登录)")
# self.textEdit.append("选择堆叠布局页面:page_0")
self.stackedWidget.setCurrentIndex(0) # 打开 stackedWidget > page_0
return
def click_pushButton_2(self):
self.stackedWidget.setCurrentIndex(1)
return
def logindef(self):
self.face1.emit()
def mouseReleaseEvent(self, event):
self.start_x = None
self.start_y = None
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
super(mainface, self).mousePressEvent(event)
self.start_x = event.x()
self.start_y = event.y()
def mouseMoveEvent(self, event):
try:
super(mainface, self).mouseMoveEvent(event)
dis_x = event.x() - self.start_x
dis_y = event.y() - self.start_y
self.move(self.x() + dis_x, self.y() + dis_y)
except:
pass
class LoginWindow(QtWidgets.QMainWindow,interface_UI):
face2=QtCore.pyqtSignal()
face3=QtCore.pyqtSignal()
def __init__(self,parent=None):
super().__init__(parent)
self.setupUi(self)
self.start_x = None
self.start_y = None
#设置窗口标志:隐藏窗口边框
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.setWindowFlags(Qt.FramelessWindowHint)
self.pushButton_7.clicked.connect(self.btn_press3_clicked)
self.pushButton_5.clicked.connect(self.btn_press5_clicked)
self.pushButton_6.clicked.connect(self.btn_press6_clicked)
self.pushButton.clicked.connect(self.btn_press_clicked)
self.widget = [{
"widget": self.frame_6,
"temp": self.label3,
'day': self.label_17,
"weather": self.label_16
}, {
"widget": self.frame_2,
"temp": self.label_2,
'day': self.label_12,
"weather": self.label
}, {
"widget": self.frame_3,
"temp": self.label_4,
'day': self.label_13,
"weather": self.label_3
}, {
"widget": self.frame_4,
"temp": self.label_6,
'day': self.label_14,
"weather": self.label_5
}, {
"widget": self.frame_5,
"temp": self.label_8,
'day': self.label_15,
"weather": self.label_7
}
]
self.get_weather_info()
self.statusShowTime()
def btn_press5_clicked(self):
self.face2.emit()
def btn_press6_clicked(self):
self.face3.emit()
#抓去肇庆的天气
def get_weather_info(self):
city_id = 101280901 # 肇庆的城市编码
url = 'http://www.weather.com.cn/weather/%s.shtml' % city_id
content = requests.get(url).content
sel = html.fromstring(content)
top = sel.xpath('//ul[@class="t clearfix"]')[0]
days = 5
for i in range(1, days + 1):
date = top.xpath('li[%d]/h1/text()' % i)[0]
weather = top.xpath('li[%d]/p[@class="wea"]/text()' % i)[0]
tem = self.get_tem(top, i)
if date:
self.widget[i - 1]['day'].setText(str(date))
if weather:
self.widget[i - 1]['weather'].setText(weather)
if tem:
self.widget[i - 1]['temp'].setText(tem)
if weather == '多云':
self.widget[i - 1]['widget'].setStyleSheet("""
image: url(:/imagesvg32/image/32svg/夜间多云.svg);
""")
elif weather == '晴':
self.widget[i - 1]['widget'].setStyleSheet("""
image: url(:/imagesvg32/image/32svg/晴.svg);
""")
elif weather == '晴转多云':
self.widget[i - 1]['widget'].setStyleSheet("""
image: url(:/image/image/32svg/fine-晴天.svg);
""")
elif weather == '阵雨':
self.widget[i - 1]['widget'].setStyleSheet("""
image: url(:/imagesvg32/image/32svg/阵雨.svg);
""")
elif weather == '阴转阵雨':
self.widget[i - 1]['widget'].setStyleSheet("""
image: url(:/image/image/32svg/天气阵雨.svg);
""")
elif weather == '阴':
self.widget[i - 1]['widget'].setStyleSheet("""
image: url(:/imagesvg32/image/32svg/阴.svg);
""")
#以此类推 可以定义更多天气的类型 显示不同的图片
# 获取温度
def get_tem(self, top, index):
tem_low = top.xpath('li[%d]/p[@class="tem"]/i/text()' % index)[0]
if len(top.xpath('li[%d]/p[@class="tem"]/span' % index)) != 0:
tem_high = top.xpath('li[%d]/p[@class="tem"]/span/text()' % index)[0] + '℃'
return tem_low + ' ~' + tem_high
else:
return tem_low
#设置界面可以拖拽和移动
def mouseReleaseEvent(self, event):
self.start_x = None
self.start_y = None
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
super(LoginWindow, self).mousePressEvent(event)
self.start_x = event.x()
self.start_y = event.y()
def mouseMoveEvent(self, event):
try:
super(LoginWindow, self).mouseMoveEvent(event)
dis_x = event.x() - self.start_x
dis_y = event.y() - self.start_y
self.move(self.x() + dis_x, self.y() + dis_y)
except:
pass
#这里设想在label_11和label_10上分别显示当地时间和日期 查找很多方法都失败了
# def get_time(self):
# datetime = QtCore.QDateTime.currentDateTime() # 获取当前日期时间
# text = datetime.toString("yyyy-MM-dd HH:mm:ss") # 对日期时间进行格式化
# self.label_11.showMessage('当前日期时间:'+text, 0) # 在状态栏中显示日期时间
def statusShowTime(self):
# self.timeLabel = QLabel() #设置一个label的控件
# self.statusBar.addPermanentWidget(self.timeLabel, 0) #将label控件放进状态栏
#这里我们已经在Frame中创建了label 所以不需要在创建新的对象
self.Timer=QTimer() #自定义QTimer类
self.Timer.start(1000) #每1s运行一次
self.Timer.timeout.connect(self.updateTime) #与updateTime函数连接
def updateTime(self):
time=QDateTime.currentDateTime() #获取现在的时间
dateshow=time.toString('yyyy-MM-dd') #设置显示时间的格式
self.label_11.setText(dateshow)
timeshow=time.toString('HH:mm:ss')
self.label_10.setText(timeshow)
def btn_press3_clicked(self):
df = pd.read_excel('myLife.xlsx',sheet_name = 'Activity') # 获取Activity表所有数据
df=df.loc[df["操作"]=="步行"] # 筛选出“步行”数据
df=df[['日期','数量']] # 选取两列
df=df.head(7) # 取头7天,尾部函数是tail()
print(df)
# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
df.plot(x='日期',y='数量') # 画图
plt.show() # 显示
def btn_press_clicked(slef):
import os
open('便笺.txt','w+')#打开文件 若没有则创建名为便笺的文件
folder=r'便笺.txt'
os.system("start explorer %s" %folder)#通过start explorer打开指定应用
class calculator (QMainWindow,Calculator_UI):
def __init__(self,parent=None):
super().__init__(parent)
self.start_x = None
self.start_y = None
class huaban(QMainWindow,huaban_UI):
def __init__(self):
super(huaban_UI, self).__init__()
self.resize(400, 300) #resize设置宽高,move设置位置
self.move(100, 100)
self.setWindowTitle("一个简单的画板")
self.setMouseTracking(False) #setMouseTracking设置为False,否则不按下鼠标时也会跟踪鼠标事件
self.Drawing_Board = []
self.start_x = None
self.start_y = None #用一个列表保存所有移动的点
# self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
# self.setWindowFlags(Qt.FramelessWindowHint)
class Controller:
def __init__(self):
pass
# 跳转到 mainface 窗口
def show_login(self):
self.mainface = mainface()
self.mainface.face1.connect(self.show_face)
self.mainface.show()
# 跳转到 LoginWindow 窗口, 注意关闭原页面
def show_face(self):
self.LoginWindow = LoginWindow()
self.mainface.close()
self.LoginWindow.show()
self.LoginWindow.face2.connect(self.show_calculator)
self.LoginWindow.face3.connect(self.show_huaban)
def show_calculator(self):
self.calculator=calculator()
self.calculator.show()
def show_huaban(self):
self.huaban=huaban()
self.huaban.show()
def main():
app = QApplication(sys.argv)
controller = Controller() # 控制器实例
controller.show_login() # 默认展示的是 hello 页面
sys.exit(app.exec_())
if __name__ == '__main__':
main()
尝试不同的方法都不行 第一次是程序闪退 但不能同时存在两个APP窗口
尝试一
class kebiao (QMainWindow,kebiao_UI):
def __init__(self):
super(kebiao_UI, self).__init__()
self.start_x = None
self.start_y = None
self.model=kebiao_UI(g)
self.view = QTableView()
self.setModel(model)
self.setWindowTitle('今日的课程')
self.resize(410, 250)
self.setAlternatingRowColors(True)
class Controller:
def __init__(self):
pass
# 跳转到 mainface 窗口
def show_login(self):
self.mainface = mainface()
self.mainface.face1.connect(self.show_face)
self.mainface.show()
# 跳转到 LoginWindow 窗口, 注意关闭原页面
def show_face(self):
self.LoginWindow = LoginWindow()
self.mainface.close()
self.LoginWindow.show()
self.LoginWindow.face2.connect(self.show_calculator)
self.LoginWindow.face3.connect(self.show_huaban)
self.LoginWindow.face4.connect(self.show_kebiao)
def show_calculator(self):
self.calculator=calculator()
self.calculator.show()
def show_huaban(self):
self.huaban=huaban()
self.huaban.show()
def show_kebiao(self):
self.kebiao=kebiao()
self.kebiao.show()
def main():
app = QApplication(sys.argv)
controller = Controller() # 控制器实例
controller.show_login() # 默认展示的是 hello 页面
sys.exit(app.exec_())
if __name__ == '__main__':
main()
尝试二
def btn_press4_clicked(self):
import pandas as pd
from PyQt5.QtWidgets import (QApplication, QTableView)
from PyQt5.QtCore import (QAbstractTableModel, Qt)
class PdTable(QAbstractTableModel):
def __init__(self, g):
QAbstractTableModel.__init__(self)
self._data = g
def rowCount(self, parent=None):
return self._data.shape[0]
def columnCount(self, parent=None):
return self._data.shape[1]
# 显示数据
def data(self, index, role=Qt.DisplayRole):
if index.isValid():
if role == Qt.DisplayRole:
return str(self._data.iloc[index.row(), index.column()])
return None
# 显示行和列头
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self._data.columns[col]
elif orientation == Qt.Vertical and role == Qt.DisplayRole:
return self._data.axes[0][col]
return None
model = PdTable(g)
view = QTableView()
view.setModel(model)
view.setWindowTitle('今日的课程')
view.resize(410, 250)
view.setAlternatingRowColors(True)
view.show()
class calculator (QMainWindow,Calculator_UI):
def __init__(self,parent=None):
super().__init__(parent)
self.start_x = None
self.start_y = None
class huaban(QMainWindow,huaban_UI):
def __init__(self):
super(huaban_UI, self).__init__()
self.resize(400, 300) #resize设置宽高,move设置位置
self.move(100, 100)
self.setWindowTitle("一个简单的画板")
self.setMouseTracking(False) #setMouseTracking设置为False,否则不按下鼠标时也会跟踪鼠标事件
self.Drawing_Board = []
self.start_x = None
self.start_y = None #用一个列表保存所有移动的点
# self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
# self.setWindowFlags(Qt.FramelessWindowHint)
class Controller:
def __init__(self):
pass
# 跳转到 mainface 窗口
def show_login(self):
self.mainface = mainface()
self.mainface.face1.connect(self.show_face)
self.mainface.show()
# 跳转到 LoginWindow 窗口, 注意关闭原页面
def show_face(self):
self.LoginWindow = LoginWindow()
self.mainface.close()
self.LoginWindow.show()
self.LoginWindow.face2.connect(self.show_calculator)
self.LoginWindow.face3.connect(self.show_huaban)
def show_calculator(self):
self.calculator=calculator()
self.calculator.show()
def show_huaban(self):
self.huaban=huaban()
self.huaban.show()
def main():
app = QApplication(sys.argv)
controller = Controller() # 控制器实例
controller.show_login() # 默认展示的是 hello 页面
sys.exit(app.exec_())
if __name__ == '__main__':
main()
这是课表单独的代码
from numpy import isin
import pandas as pd
import datetime
from time import strftime
pd.set_option('display.unicode.east_asian_width', True)#解决不对齐
df=pd.read_excel('myLife.xlsx',sheet_name='TaskList',index_col=False)
# print(df.head())#看看是否读取成功
df1=df.set_index(['日期'])
# # print(df1.head())
# df['日期']=df['日期'].astype('string')
df['日期']=pd.to_datetime(df['日期'])
time=datetime.datetime.now()
a=time.strftime("%m/%#d/%y")
# c=int(a)
# # print(type(a))
# # print(c)
# # print(type(df))
# df.info()
time = datetime.datetime.now().strftime("%Y-%m-%d")
# print(type(time))
print(time)
d=df.loc[df['日期'] == time ]
print(d)
f=d.drop_duplicates(subset=['开始时间'])#剔除相同
# print(f)
e=f[['日期','对象名','开始时间']]
# print(e)
g=e.sort_values(by=['开始时间'],ascending=False)
print(g)
import pandas as pd
from PyQt5.QtWidgets import (QApplication, QTableView)
from PyQt5.QtCore import (QAbstractTableModel, Qt)
class PdTable(QAbstractTableModel):
def __init__(self, g):
QAbstractTableModel.__init__(self)
self._data = g
def rowCount(self, parent=None):
return self._data.shape[0]
def columnCount(self, parent=None):
return self._data.shape[1]
# 显示数据
def data(self, index, role=Qt.DisplayRole):
if index.isValid():
if role == Qt.DisplayRole:
return str(self._data.iloc[index.row(), index.column()])
return None
# 显示行和列头
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self._data.columns[col]
elif orientation == Qt.Vertical and role == Qt.DisplayRole:
return self._data.axes[0][col]
return None
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
model = PdTable(g)
view = QTableView()
view.setModel(model)
view.setWindowTitle('今日的课程')
view.resize(410, 250)
view.setAlternatingRowColors(True)
view.show()
sys.exit(app.exec_())
程序代码已经实现过多个界面的跳转 利用 Controller() # 控制器 方法
######能否解答下如何用 Controller() # 控制器发射信号的方法实现课表界面的显示