单击按钮时如何从另一个 Python 文件读取 QLineEdit 值的值 [英] How to read value of QLineEdit value from another Python file when Push Button is clicked
问题描述
当单击按钮时,我试图从另一个 python 文件中读取 QLineEdit(在 prog 中的 search_dir_te)的值.但它正在失败.请指导.
Am trying to read the value of a QLineEdit (search_dir_te in prog) from another python file when push button is clicked. But it is failing. Please guide.
First.py:
class Display(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
search_dir_label = QLabel('Directory to Search')
self.search_dir_te = QLineEdit()
search_dir_layout = QHBoxLayout(self)
search_dir_layout.addWidget(search_dir_label)
search_dir_layout.addWidget(self.search_dir_te)
vert_layout1.addLayout(search_dir_layout)
search_button = QPushButton('Search')
search_button.clicked.connect(initiatesearch)
cancel_button = QPushButton('Cancel')
search_cancel_layout = QHBoxLayout(self)
search_cancel_layout.addWidget(search_button)
search_cancel_layout.addWidget(cancel_button)
search_cancel_layout.setAlignment(Qt.AlignCenter)
vert_layout1.addLayout(search_cancel_layout)
<小时>
Second.py
def initiatesearch(self):
print(self.search_dir_te.text())
我在First.py中导入了initialsearch函数
I have imported initiatesearch function in First.py
推荐答案
您将应用程序的各个部分不必要地交织在一起,这是设计不佳的标志.函数就像一个黑匣子:接收信息,处理它并返回结果.在这种情况下,initiatesearch"应该只获取文本,而不是小部件或其他元素:
You are unnecessarily intertwining the parts of your application, and that is a sign of a bad design. A function is like a black box: Receive information, process it and return results. In this case "initiatesearch" you should only get the text and not the widget or other elements:
def initiatesearch(text):
print(text)
class Display(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
search_dir_label = QLabel('Directory to Search')
self.search_dir_te = QLineEdit()
search_dir_layout = QHBoxLayout(self)
search_dir_layout.addWidget(search_dir_label)
search_dir_layout.addWidget(self.search_dir_te)
vert_layout1.addLayout(search_dir_layout)
search_button = QPushButton('Search')
search_button.clicked.connect(self.onClicked)
cancel_button = QPushButton('Cancel')
search_cancel_layout = QHBoxLayout(self)
search_cancel_layout.addWidget(search_button)
search_cancel_layout.addWidget(cancel_button)
search_cancel_layout.setAlignment(Qt.AlignCenter)
vert_layout1.addLayout(search_cancel_layout)
def onClicked(self):
initiatesearch(self.search_dir_te.text())
更新:
如果您仍然想知道这是一种不好的做法,那么您可以执行以下操作:
If you still want to do knowing that it is a bad practice then you can do the following:
def onClicked(self):
initiatesearch(self)
def initiatesearch(ui):
print(ui.search_dir_te.text())
更新 2:
from functools import partial
# ...
search_button.clicked.connect(partial(initiatesearch, self))
这篇关于单击按钮时如何从另一个 Python 文件读取 QLineEdit 值的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!