简体   繁体   English

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

[英]PyQt5 button in second window not working

I am writing a cipher program in Python using PyQt5, that also has email functionality. 我正在使用PyQt5用Python编写密码程序,该程序也具有电子邮件功能。 In the program, there are 2 windows, and the goal of the second window is to add a new contact to the json file. 在该程序中,有2个窗口,第二个窗口的目标是向json文件添加一个新联系人。 When I click on the button in the second window, the program does not register the click. 当我单击第二个窗口中的按钮时,该程序不会记录该单击。

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 Contacts.json

CSS StyleSheet CSS样式表

keyTestKey.txt keyTestKey.txt

Any help would be greatly appreciated. 任何帮助将不胜感激。

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文件代码

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

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

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