我正在尝试将代码整理成py文件,我的GUI带有4个QLineEdit框,并且当单击btnNewPerson时,我希望oerson.py访问输入的值。这是在单个文件中工作的摘要代码,但我正在尝试将其分解为可管理的类。
publicationgraph.py
[other imports ...]
from person import Person
class PublicationGraph(QMainWindow):
def __init__(self):
super().__init__()
self.resize(600, 400)
self.title = 'title'
self.left = 10
self.top = 10
self.width = 440
self.height = 280
self.init_ui()
def init_ui(self):
self.setWindowTitle(self.title)
#self.setGeometry(self.left, self.top, self.width, self.height)
self.lePersonFirstName = QLineEdit('First Name', self)
self.lePersonFirstName.move(40, 40)
self.lePersonLastName = QLineEdit('Last Name', self)
self.lePersonLastName.move(40, 80)
self.lePersonInitials = QLineEdit('Initials', self)
self.lePersonInitials.move(40, 120)
self.btnNewPerson = QPushButton('Add Person', self)
self.btnNewPerson.move(40, 160)
self.btnNewPerson.clicked.connect(Person.new)
person.py
class Person():
def __init__(self):
super().__init__()
def new(self):
name = self.lePersonLastName.text()
firstName = self.lePersonFirstName.text()
lastName = self.lePersonLastName.text()
initials = self.lePersonInitials.text()*
答案 0 :(得分:1)
程序自然不是一组文件,而是基于模块,库或文件中定义的类创建的对象的交互,因此您的问题应该是:如何将参数传递给对象的对象。类人?在这种情况下,它是通过构造函数之类的方法来实现的。
publicationgraph.py
from PyQt5 import QtCore, QtWidgets
from person import Person
class PublicationGraph(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.init_ui()
self._persons = []
def init_ui(self):
self.lePersonFirstName = QtWidgets.QLineEdit()
self.lePersonLastName = QtWidgets.QLineEdit()
self.lePersonInitials = QtWidgets.QLineEdit()
self.btnNewPerson = QtWidgets.QPushButton('Add Person')
self.btnNewPerson.clicked.connect(self.on_clicked)
widget = QtWidgets.QWidget()
self.setCentralWidget(widget)
flay = QtWidgets.QFormLayout(widget)
flay.addRow('First Name', self.lePersonFirstName)
flay.addRow('Last Name', self.lePersonLastName)
flay.addRow('Initials', self.lePersonInitials)
flay.addRow(self.btnNewPerson)
@QtCore.pyqtSlot()
def on_clicked(self):
first_name = self.lePersonFirstName.text()
last_name = self.lePersonLastName.text()
initials = self.lePersonInitials.text()
p = Person(first_name, last_name, initials)
self._persons.append(p)
print("Persons: ", self._persons)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = PublicationGraph()
w.show()
sys.exit(app.exec_())
person.py
class Person():
def __init__(self, fistname, lastname, initials):
self._firstname = fistname
self._lastname = lastname
self._initials = initials