繁体   English   中英

PyQt5 QfileDialog专门将文件保存为python文件

[英]PyQt5 QfileDialog specifically save file as python file

我正在为抽认卡编写一个简单的gui应用程序。 用户生成闪存卡,并将其保存到列表中。 我只想将列表保存到文件中,这样用户可以有多个平台,只需File->打开他们想要的内容即可。 在我的未受过教育的大脑中,我觉得将它们保存在python文件中会使整个过程更容易,假设我在加载时遵循以下步骤进行了操作:

for c in filename.allCards:
    allCards.append(c)

我试过同时使用

name.setNameFilters(["*.py"])

name.selectNameFilter("Python Files (*.py)")

没有运气。 所以现在我基本上有两个问题。 1)这是执行此操作的最有效方法吗?2)如果是这样,我还缺少什么,因为即使在手动添加.py扩展名后进行保存,它仍然保存为文本文件吗?

供参考,这是我的保存功能

def saveFunc(self):
    name = QtWidgets.QFileDialog.getSaveFileName(self, 'Save File',"Python Files (*.py)")
    name.setNameFilters(["*.py"])
    name.selectNameFilter("Python Files (*.py)")
    file = open(name, 'w')

我通过菜单操作在主窗口中调用它。

这是整个脚本

import os
import sys
from PyQt5.QtWidgets import * #QApplication, QWidget, QPushButton
from PyQt5.QtGui import* # QIcon 
from PyQt5.QtCore import pyqtSlot
from PyQt5 import QtWidgets, QtCore
import cards
from PyQt5.Qt import QPlainTextEdit
from PyQt5.uic.Compiler.qtproxies import QtGui


class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'Flash Cards'
        self.left = 10
        self.top = 10
        self.width = 640
        self.height = 480

        self.initUI()

    def initUI(self):
        self.allCards = []
        self.cardShow = 0
        self.backShow = 0
        self.setWindowTitle(self.title)
        self.windowApp = self.frameGeometry()
        self.screenRes = app.desktop().screenGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()

        self.windowApp.moveCenter(centerPoint)

        self.move(self.windowApp.topLeft())
        self.setFixedSize((self.screenRes.width() / 2.5),(self.screenRes.height() /2.25))

        #text displays
        self.l1 = QPlainTextEdit(self)
        self.l1.move(500,30)#60,200)
        self.l1.resize(200,200)
        self.l1.insertPlainText('Fronts of cards will be displayed here')
        self.l1.setReadOnly(True)

        self.l2 = QPlainTextEdit(self)
        self.l2.move(500,250)
        self.l2.resize(200,200)
        self.l2.setReadOnly(True)


        #textboxes
        self.frontText = QLineEdit(self)
        self.frontText.move(20,30)
        self.frontText.resize(280,40)
        self.frontText.setText('Front of card')

        self.backText = QLineEdit(self)
        self.backText.move(20,80)
        self.backText.resize(280,40)
        self.backText.setText('Back of card')

        #buttons
        self.addCard = QPushButton('Add Card', self)
        self.addCard.setToolTip('Add a flash card')
        self.addCard.move(110,130)
        self.addCard.clicked.connect(self.on_click)

        self.nextCard = QPushButton('Next Card', self)
        self.nextCard.move(110,250)
        self.nextCard.clicked.connect(self.next_click)

        self.revealAns = QPushButton('Reveal answer', self)
        self.revealAns.move(110,300)
        self.revealAns.clicked.connect(self.ans_click)


        self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint)
        exitAct = QAction(QIcon('exit.png'), '&Exit', self)        
        exitAct.setShortcut('Ctrl+Q')
        exitAct.setStatusTip('Exit application')
        exitAct.triggered.connect(qApp.quit)

        saveAct = QAction(QIcon('exit.png'), '&Save', self)        
        saveAct.setShortcut('Ctrl+S')
        saveAct.setStatusTip('Save Current Deck')
        saveAct.triggered.connect(self.saveFunc)

        openAct = QAction(QIcon('exit.png'), '&Open', self)        
        openAct.setShortcut('Ctrl+O')
        openAct.setStatusTip('Open A Deck')
        openAct.triggered.connect(self.openFunc)

        self.statusBar()

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAct)
        fileMenu.addAction(openAct)
        fileMenu.addAction(saveAct)

        self.show()


    @pyqtSlot()
    def on_click(self):
        newCard = cards.Card(self.frontText.text(), self.backText.text())
        self.allCards.append(newCard)
        self.frontText.setText('Front of card')
        self.backText.setText('Back of card')

    def next_click(self):
        if self.cardShow == self.backShow:
            sameShow = True
        if self.backShow >= len(self.allCards):
            self.backShow = 0
        if self.cardShow >= len(self.allCards):
            self.cardShow = 0
        if len(self.allCards) > 0 & sameShow:
            self.l1.clear()
            self.l1.insertPlainText(self.allCards[self.cardShow].frontSide)
            self.l2.clear()
            QtWidgets.qApp.processEvents()
        elif len(self.allCards) == 0:
            self.l1.clear()
            self.l1.insertPlainText('Fronts of cards will be displayed here')
            QMessageBox.about(self, 'Try Again', "You haven't added any cards")
    def ans_click(self):
        #self.l2.clear()
        self.l2.insertPlainText(self.allCards[self.backShow].backSide)
        self.backShow+=1
        self.cardShow+=1
    #def last_click(self):
    def saveFunc(self):
        name = QtWidgets.QFileDialog.getSaveFileName(self, 'Save File',"Python Files (*.py)")
        name.setNameFilters(["*.py"])
        name.selectNameFilter("Python Files (*.py)")
        file = open(name, 'w')
            #write the list
    def openFunc(self):
        name = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File')
        file = open(name, 'r')
        with file:
            deck = file.read()
            self.allCards.append(file.allCards)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

cards是我用来为card对象编写类的脚本。 这很简单:

class Card:
    def __init__(self, frontSide, backSide):
        self.frontSide = frontSide
        self.backSide = backSide

谢谢您的帮助。 我最后只用泡菜。 从上面我将功能更改为

保存

def saveFunc(self):
    with open('CardSet.pkl', 'wb') as f:
        pickle.dump(self.allCards, f)

开场

def openFunc(self):
    with open('CardSet.pkl', 'rb') as f:
        self.allCards = pickle.load(f)

作品惊人

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM