Python 我需要帮助在PyQt5中制作菜单栏

Python 我需要帮助在PyQt5中制作菜单栏,python,pyqt,pyqt5,Python,Pyqt,Pyqt5,几天来,我一直在尝试在我的程序中实现一个菜单栏,但我似乎无法运行它。我想有人看看我的代码,给我一个模板,按照我的菜单栏 class MainWindow(QMainWindow): def __init__(self, databaseFilePath, userFilePath): super(MainWindow,self).__init__() self.moviesFilePath = moviesFilePath self.cur

几天来,我一直在尝试在我的程序中实现一个菜单栏,但我似乎无法运行它。我想有人看看我的代码,给我一个模板,按照我的菜单栏

class MainWindow(QMainWindow):
    def __init__(self, databaseFilePath, userFilePath):
        super(MainWindow,self).__init__()
        self.moviesFilePath = moviesFilePath
        self.currentUserFilePath = currentUserFilePath
        self.createWindow()

    def changeFilePath(self):
        self.currentUserFilePath = functions_classes.changeFP()
        functions_classes.storeFP(self.currentUserFilePath, 1)

    def createWindow(self):
        self.setWindowTitle('Movies')
        #Menu Bar
        fileMenuBar = QMenuBar().addMenu('File')

当从菜单栏文件调用名为“更改用户数据库位置”的菜单选项时,我希望调用changeFilePath方法。我已经读到,操作是实现这一点的关键,但每次我尝试实现它们时,它们都不起作用。

添加带有可用项的菜单栏的逻辑如下所示

def createUI(self):
        self.setWindowTitle('Equipment Manager 0.3')
        #Menu Bar
        fileMenuBar = QMenuBar(self)
        menuFile = QMenu(fileMenuBar)
        actionChangePath = QAction(tr("Change Path"), self)
        fileMenuBar.addMenu(menuFile)
        menuFile.addAction(actionChangePath)
然后,您只需将动作
actionChangePath
连接到信号
triggered()
,如下所示

connect(actionChangePath,SIGNAL("triggered()"), changeFilePath)

可能有更好的解决方案(但为什么不使用设计器?),但这个解决方案应该是可行的,
QMainWindow
类已经有了一个

所以你只需要点击它,然后点击菜单,就像这样:

    def createUI(self):
        ...
        menu = self.menuBar().addMenu('File')
        action = menu.addAction('Change File Path')
        action.triggered.connect(self.changeFilePath)
编辑

下面是一个基于示例类的完整工作示例:

from PyQt5 import QtWidgets

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, databaseFilePath, userFilePath):
        super(MainWindow,self).__init__()
        self.databaseFilePath = databaseFilePath
        self.userFilePath = userFilePath
        self.createUI()

    def changeFilePath(self):
        print('changeFilePath')
        # self.userFilePath = functions_classes.changeFilePath()
        # functions_classes.storeFilePath(self.userFilePath, 1)

    def createUI(self):
        self.setWindowTitle('Equipment Manager 0.3')
        menu = self.menuBar().addMenu('File')
        action = menu.addAction('Change File Path')
        action.triggered.connect(self.changeFilePath)   

if __name__ == '__main__':

    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow('some/path', 'some/other/path')
    window.show()
    window.setGeometry(500, 300, 300, 300)
    sys.exit(app.exec_())

对于提供的两种方法,当代码运行时,python外壳看起来像是试图构建和提升窗口,但随后又重新启动。我没有使用设计器的原因是因为我不知道如何将文件转换为GUI程序。该文件是使用
pyuic
转换的,这将生成一个.py文件,该文件可以导入到您的主脚本中,用于提供的两种方法。当代码运行时,python shell看起来好像试图构建和提升窗口,但随后它会重新启动。@user1921942。我真的不明白你的评论,但我添加了一个工作示例来演示如何运行代码。我不知道第一次我做错了什么,但在你编辑之后我成功了,谢谢!