Python 将文件对话框与PyQt中的按钮组合在一起
我正在努力从Tkinter过渡到PyQt更面向对象的方法。我的特别问题集中在将文件对话框与按钮结合起来。在下面的示例中,我承认我不完全理解代码行,我使用文件对话框将存储为.csv文件的时间序列加载到数据帧中,然后绘制它:Python 将文件对话框与PyQt中的按钮组合在一起,python,pyqt,Python,Pyqt,我正在努力从Tkinter过渡到PyQt更面向对象的方法。我的特别问题集中在将文件对话框与按钮结合起来。在下面的示例中,我承认我不完全理解代码行,我使用文件对话框将存储为.csv文件的时间序列加载到数据帧中,然后绘制它: import sys import pandas as pd from matplotlib import pyplot as plt from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog, class
import sys
import pandas as pd
from matplotlib import pyplot as plt
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog,
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'Series Plotter'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.openFileNameDialog()
self.show()
def openFileNameDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getOpenFileName(self,"Choose File", "","csv (*.csv)",
options=options)
df=pd.read_csv(fileName)
df.plot()
plt.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
只要它自动启动文件对话框并绘制所选的时间序列,它就可以工作。但是,我更愿意做以下工作:
尽管阅读了各种教程,但我仍在努力寻找python式的方法,这一事实归因于我对面向对象方法的有限知识。您可以尝试创建一个
主窗口
,并在那里添加按钮
,和将按钮单击事件连接到一个函数,在该函数中初始化已创建的类,如下所示:
从PyQt5导入QtWidgets
类MainWindow(QtWidgets.QMainWindow):
定义初始化(自):
超级(主窗口,自我)。\uuuu初始化
自我调整大小(300300)
frame=qtwidts.QFrame()
self.setCentralWidget(框架)
layout=qtwidts.QHBoxLayout()
frame.setLayout(布局)
self.fileOpenButton=qtwidts.QPushButton('单击打开文件对话框',self)
layout.addWidget(self.fileOpenButton)
self.fileOpenButton.clicked.connect(self.buttonClicked)
def按钮已锁定(自):
wig=App()
def main():
app=QApplication([])
mainWindow=mainWindow()
mainWindow.show()
sys.exit(app.exec_())
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()
输出:
单击按钮后:
选择文件后:
您可以创建一个主窗口
,并在其上添加按钮,效果非常好,更重要的是,它有助于弥合我对基本原理的理解差距。谢谢。@ThePyGuy为了这个例子,特别建议主窗口没有影响,因为你没有使用它的任何特定功能,因为标准的QWidget将获得完全相同的结果。是的,同样的事情也可以通过QWidget实现