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

时间:2021-09-02 23:03:06

I am writing a cipher program in Python using PyQt5, that also has email functionality. In the program, there are 2 windows, and the goal of the second window is to add a new contact to the json file. When I click on the button in the second window, the program does not register the click.

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

As a second question, I am also having trouble getting the new contact info dumped into the correct spot in the file.

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

Here is my second window's code:

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

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()

Here are all my files:

这是我的所有文件:

Full Python File Code

完整的Python文件代码

Contacts.json

CSS StyleSheet

keyTestKey.txt

Any help would be greatly appreciated.

任何帮助将不胜感激。

2 个解决方案

#1


0  

Your code has several problems:

您的代码有几个问题:

  • The following code: Window() .__init__() does not make sense, you are creating a new object, and you are resetting the same object that you just created, I suspect that you think that with this you are reloading the initial window, but.

    下面的代码:Window().__ init __()没有意义,你正在创建一个新对象,并且你正在重置你刚创建的同一个对象,我怀疑你认为你正在重新加载初始窗口,但。

  • On the other hand in submitBtn_click you are overwriting the data with only one contact losing the initial format, what you should do is read the json, modify it and save it.

    另一方面,在submitBtn_click中,你只用一个失去初始格式的联系人覆盖数据,你应该做的是读取json,修改它并保存它。

  • You are creating objects every time and that is not the best, it is best to reuse, in my solution I only create one window of each class, and what I do is close or show the windows as required.

    你每次都在创建对象并且这不是最好的,最好重用,在我的解决方案中我只创建每个类的一个窗口,而我所做的就是关闭或根据需要显示窗口。

  • Another problem that I see is that you are not using the layouts correctly.

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

Considering the previous thing, and others that are not so transcendental (I have not used keyCode since I do not have the .txt, I think that you can implement it)

考虑到以前的事情,以及其他不那么超然的事情(我没有使用过keyCode,因为我没有.txt,我认为你可以实现它)

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_())

#2


0  

Change the code between lines 218 and 219 to:

将第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")

Change the code in line 297 to be:

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

class AddContactWindow(QtWidgets.QDialog):

Change the code between lines 368 and 375 to:

将第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

完整的Python文件代码

#1


0  

Your code has several problems:

您的代码有几个问题:

  • The following code: Window() .__init__() does not make sense, you are creating a new object, and you are resetting the same object that you just created, I suspect that you think that with this you are reloading the initial window, but.

    下面的代码:Window().__ init __()没有意义,你正在创建一个新对象,并且你正在重置你刚创建的同一个对象,我怀疑你认为你正在重新加载初始窗口,但。

  • On the other hand in submitBtn_click you are overwriting the data with only one contact losing the initial format, what you should do is read the json, modify it and save it.

    另一方面,在submitBtn_click中,你只用一个失去初始格式的联系人覆盖数据,你应该做的是读取json,修改它并保存它。

  • You are creating objects every time and that is not the best, it is best to reuse, in my solution I only create one window of each class, and what I do is close or show the windows as required.

    你每次都在创建对象并且这不是最好的,最好重用,在我的解决方案中我只创建每个类的一个窗口,而我所做的就是关闭或根据需要显示窗口。

  • Another problem that I see is that you are not using the layouts correctly.

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

Considering the previous thing, and others that are not so transcendental (I have not used keyCode since I do not have the .txt, I think that you can implement it)

考虑到以前的事情,以及其他不那么超然的事情(我没有使用过keyCode,因为我没有.txt,我认为你可以实现它)

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_())

#2


0  

Change the code between lines 218 and 219 to:

将第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")

Change the code in line 297 to be:

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

class AddContactWindow(QtWidgets.QDialog):

Change the code between lines 368 and 375 to:

将第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

完整的Python文件代码