学习python并弄乱简单的GUI数据输入/保存到文本文件。 我遇到的问题是以下代码有效但在文本文件中写了三次。喜欢它循环3次。更新了完整代码,使用PyQt Designer制作Ui文件。
import sys
import time
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication,QDialog
from PyQt5.uic import loadUi
class RefTracker(QDialog):
def __init__(self):
super(RefTracker,self).__init__()
loadUi('reftrack.ui',self)
self.setWindowTitle('r134a Tracker')
self.label7.setText(time.ctime())
# self.pushButton.clicked.connect(self.on_pushButton_clicked)
# self.pushButton.clicked.connect(self.on_pushButton2_clicked)
# self.pushButton.clicked.connect(self.on_pushButton3_clicked)
self.pushButton.clicked.connect(self.on_pushButton_clicked)
@pyqtSlot()
def on_pushButton_clicked(self):
cust = self.lineEdit.text()
plate = self.lineEdit_2.text()
self.label_13.setText(cust)
self.label_14.setText(plate)
f= open('data.txt','a')
f.write('Customer Name: '+cust+'\n')
f.write('Plate Number: '+plate+'\n')
f.close()
app=QApplication(sys.argv)
widget=RefTracker()
widget.show()
sys.exit(app.exec_())
答案 0 :(得分:0)
使用.ui文件时,该方法称为connectSlotsByName()
QtCore.QMetaObject.connectSlotsByName(Dialog)
根据docs
:
void QMetaObject :: connectSlotsByName(QObject * object)
以递归方式搜索给定对象的所有子对象,以及 将来自它们的匹配信号连接到跟随的对象的插槽 以下表格:
void
on_<object name>_<signal name>(<signal parameters>)
;让我们假设 我们的对象有一个QPushButton类型的子对象,对象名称 BUTTON1。用于捕获按钮的clicked()
信号的插槽将是:void on_button1_clicked();
如果对象本身具有正确设置的对象名称,则其自身的信号为 也连接到各自的插槽。
并且在这种情况下,插槽与该结构匹配,因此不使用self.pushButton.clicked.connect(self.on_pushButton_clicked)
已存在隐式连接。
当您创建新连接时,您将调用on_pushButton_clicked
方法两次。
对于上述内容,您有两种选择:
class RefTracker(QDialog):
def __init__(self):
super(RefTracker,self).__init__()
loadUi('reftrack.ui',self)
self.setWindowTitle('r134a Tracker')
self.label7.setText(time.ctime())
@pyqtSlot()
def on_pushButton_clicked(self):
cust = self.lineEdit.text()
plate = self.lineEdit_2.text()
self.label_13.setText(cust)
self.label_14.setText(plate)
with open('data.txt', 'a+') as f:
f.write('Customer Name: '+cust+'\n')
f.write('Plate Number: '+plate+'\n')
class RefTracker(QDialog):
def __init__(self):
super(RefTracker,self).__init__()
loadUi('reftrack.ui',self)
self.setWindowTitle('r134a Tracker')
self.pushButton.clicked.connect(self.on_slot)
@pyqtSlot()
def on_slot(self):
cust = self.lineEdit.text()
plate = self.lineEdit_2.text()
self.label_13.setText(cust)
self.label_14.setText(plate)
with open('data.txt', 'a+') as f:
f.write('Customer Name: '+cust+'\n')
f.write('Plate Number: '+plate+'\n')