第二个窗口中的PyQt5按钮不起作用

时间:2018-10-07 01:57:03

标签: python json python-3.x pyqt pyqt5

我正在使用PyQt5用Python编写密码程序,该程序也具有电子邮件功能。在该程序中,有2个窗口,第二个窗口的目标是向json文件添加一个新联系人。当我单击第二个窗口中的按钮时,该程序不会记录该点击。

作为第二个问题,我也很难将新的联系信息转储到文件中的正确位置。

这是我第二个窗口的代码:

class AddContactWindow(QtWidgets.QWidget):

    def __init__(self):
        super().__init__()
        self.init_ui()
        self.setStyleSheet(Window.StyleSheet1)

    def init_ui(self):

        self.TitleLab = QtWidgets.QLabel('Add New Contact')
        self.NameLab = QtWidgets.QLabel('Name: ')
        self.NameLe = QtWidgets.QLineEdit(self)
        self.CodeNameLab = QtWidgets.QLabel('Code Name: ')
        self.CodeNameLe = QtWidgets.QLineEdit(self)
        self.EmailLab = QtWidgets.QLabel('Email address: ')
        self.EmailLe = QtWidgets.QLineEdit(self)
        self.KeyLab = QtWidgets.QLabel('Key: ')
        self.KeyLe = QtWidgets.QLineEdit(self)
        self.SubmitBtn = QtWidgets.QPushButton('Add Contact')

        h_box = QtWidgets.QHBoxLayout()
        h_box.addStretch()
        h_box.addWidget(self.TitleLab)
        h_box.addStretch()

        h_box1 = QtWidgets.QHBoxLayout()
        h_box1.addWidget(self.NameLab)
        h_box1.addWidget(self.NameLe)

        h_box2 = QtWidgets.QHBoxLayout()
        h_box2.addWidget(self.CodeNameLab)
        h_box2.addWidget(self.CodeNameLe)

        h_box3 = QtWidgets.QHBoxLayout()
        h_box3.addWidget(self.EmailLab)
        h_box3.addWidget(self.EmailLe)

        h_box4 = QtWidgets.QHBoxLayout()
        h_box4.addWidget(self.KeyLab)
        h_box4.addWidget(self.KeyLe)

        h_box5 = QtWidgets.QHBoxLayout()
        h_box5.addStretch()
        h_box5.addWidget(self.SubmitBtn)
        h_box5.addStretch()

        v_box = QtWidgets.QVBoxLayout()
        v_box.addLayout(h_box)
        v_box.addLayout(h_box1)
        v_box.addLayout(h_box2)
        v_box.addLayout(h_box3)
        v_box.addLayout(h_box4)
        v_box.addLayout(h_box5)

        self.setLayout(v_box)
        self.setWindowTitle('Creat New Contact')

        self.SubmitBtn.clicked.connect(self.submitBtn_click)
        #self.SubmitBtn.clicked.connect(self.test)

        self.show()

    def test(self):
        self.close()

    def submitBtn_click(self):
        print('Processing')
        data = {}
        data['Name'] = "New Contact Name"
        data['CodeName'] = "New Code Name"
        data['Email'] = "New Email Address"
        data['Key'] = "TestKey"
        with open('Contacts.json', 'a') as fp:
            fp.seek(0, os.SEEK_END)              # seek to end of file; f.seek(0, 2) is legal
            fp.seek(fp.tell() -5, os.SEEK_SET)   # go backwards 5 bytes
            fp.write(", \n")
            json.dump(data, fp, sort_keys=True, indent=4, separators=(',', ': '))
            fp.close()  
        Window().__init__()
        self.close()

这是我的所有文件:

Full Python File Code

Contacts.json

CSS StyleSheet

keyTestKey.txt

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

将第218行和219行之间的代码更改为:

self.hide()
AddContactWindow().exec_()
self.show()

self.ContactDropDown.clear()
self.ContactDropDown.addItem('Please select a contact')
with open('Contacts.json') as f:
    self.ContactsFile = json.load(f)
for contact in self.ContactsFile['contacts']:
    print(contact)
    self.ContactDropDown.addItem(contact['Name'] + "/" + contact['CodeName'])
self.ContactDropDown.addItem("Add new contact")

将第297行中的代码更改为:

class AddContactWindow(QtWidgets.QDialog):

将368和375行之间的代码更改为:

ContactsFile = []
with open('Contacts.json', 'r') as fp:
    ContactsFile = json.load(fp)
    fp.close()
ContactsFile["contacts"].append(data)
with open('Contacts.json', 'w') as fp:
    json.dump(ContactsFile, fp, sort_keys=True, indent=4, separators=(',', ': '))
    fp.close()

Full Python File Code

答案 1 :(得分:0)

您的代码有几个问题:

  • 以下代码:submitBtn_click没有意义,您正在创建一个新对象,并且您正在重置与刚刚创建的对象相同的对象,我怀疑您认为与此相关的是您正在重新加载初始窗口,但是。

  • 另一方面,在import json from PyQt5 import QtWidgets, QtGui, QtCore class Window(QtWidgets.QWidget): def __init__(self): super().__init__() self.init_ui() self.contact_window = AddContactWindow() self.contact_window.SubmitBtn.clicked.connect(self.loadContacts) self.contact_window.SubmitBtn.clicked.connect(self.show) def init_ui(self): lay = QtWidgets.QVBoxLayout(self) self.ContactLab = QtWidgets.QLabel('Contact') self.ContactDropDown = QtWidgets.QComboBox(self) self.ContactDropDown.addItem('Please select a contact') lay.addWidget(self.ContactLab) lay.addWidget(self.ContactDropDown) lay.addStretch() self.ContactsFile = [] self.loadContacts() @QtCore.pyqtSlot() def loadContacts(self): with open('Contacts.json') as f: self.ContactsFile = json.load(f) self.ContactDropDown.clear() for contact in self.ContactsFile['contacts']: self.ContactDropDown.addItem(contact['Name'] + "/" + contact['CodeName']) self.ContactDropDown.addItem("Add new contact") self.setWindowTitle('Cipher Program') self.ContactDropDown.activated[str].connect(self.contactBtn_clk) self.show() def contactBtn_clk(self, text): for contact in self.ContactsFile['contacts']: if text == contact['Name'] + "/" + contact['CodeName']: email = contact['Email'] contactName = text # keyCode = open(r'KEYS\key' + contact['Key'] + '.txt', 'r').read() # key = bytes(self.KeyCode, 'utf-8') elif text == "Add new contact": self.contact_window.clear() self.contact_window.show() self.close() class AddContactWindow(QtWidgets.QWidget): def __init__(self): super().__init__() self.init_ui() # self.setStyleSheet(Window.StyleSheet1) def init_ui(self): lay = QtWidgets.QVBoxLayout(self) lay.addWidget(QtWidgets.QLabel('Add New Contact')) flay = QtWidgets.QFormLayout() lay.addLayout(flay) lay.addStretch() self.NameLe = QtWidgets.QLineEdit() self.CodeNameLe = QtWidgets.QLineEdit() self.EmailLe = QtWidgets.QLineEdit(self) self.KeyLe = QtWidgets.QLineEdit(self) self.SubmitBtn = QtWidgets.QPushButton('Add Contact') self.SubmitBtn.clicked.connect(self.submitBtn_click) flay.addRow("Name: ", self.NameLe) flay.addRow("Code Name: ", self.CodeNameLe) flay.addRow("Email address: ", self.EmailLe) flay.addRow("Key: ", self.KeyLe) flay.addRow(self.SubmitBtn) self.setWindowTitle('Creat New Contact') def showEvent(self, event): if self.isVisible(): self.NameLe.setFocus() super(AddContactWindow, self).showEvent(event) def clear(self): self.NameLe.clear() self.CodeNameLe.clear() self.EmailLe.clear() self.KeyLe.clear() @QtCore.pyqtSlot() def submitBtn_click(self): contact = dict() contact['Name'] = self.NameLe.text() contact['CodeName'] = self.CodeNameLe.text() contact['Email'] = self.EmailLe.text() contact['Key'] = self.KeyLe.text() with open('Contacts.json', 'r+') as fp: data = json.load(fp) data["contacts"].append(contact) fp.seek(0) json.dump(data, fp, indent=4) fp.truncate() self.close() if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) with open('PyQt5 StyleSheet1 (Red, Black, and Blue).css', 'r') as styleSheet: qss = styleSheet.read() app.setStyleSheet(qss) a_window = Window() sys.exit(app.exec_()) 中,您正在重写数据,只有一个联系人丢失了初始格式,您应该做的是读取json,对其进行修改并保存。

    < / li>
  • 您每次都在创建对象,但这不是最好的,最好是重用。在我的解决方案中,我仅创建每个类的一个窗口,然后根据需要关闭或显示这些窗口。

  • 我看到的另一个问题是您没有正确使用布局。

考虑到前一件事,以及其他不那么先验的东西(由于我没有.txt,因此我没有使用keyCode,我认为您可以实现它)

                    while (resultSet.next()) {
                        Vector row = new Vector(columns);
                        for (int i = 1; i <= columns; i++) {
                            row.addElement(resultSet.getObject(i));
                        }
                        data.addElement(row);
                    }