【问题标题】:Print LineEdit text on a button press按下按钮打印 LineEdit 文本
【发布时间】:2018-07-27 21:11:36
【问题描述】:

当按下“确定”按钮时,如何更改以下代码以使其打印行编辑小部件中写入的任何内容?当前版本返回“'Example' object has no attribute 'textbox'”错误。

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QPushButton,QLineEdit, QHBoxLayout, QLabel, QVBoxLayout
from PyQt5.QtGui import QIcon


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        label = QLabel('Keyword') 
        button = QPushButton('OK')
        textbox = QLineEdit()
        hbox = QHBoxLayout()
        hbox.addWidget(label)
        hbox.addWidget(textbox)
        hbox.addWidget(button)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox)
        vbox.addStretch(1)

        button.clicked.connect(self.button_clicked)

        self.setLayout(vbox)   

        self.setGeometry(300, 300, 300, 220)
        self.setWindowTitle('Icon')
        self.setWindowIcon(QIcon('web.png')) 
        self.show()

    def button_clicked(self):
        print(self.textbox.text())

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

`

【问题讨论】:

    标签: python pyqt pyqt5 qlineedit qpushbutton


    【解决方案1】:

    如果您希望在类的所有部分都可以访问一个变量,就像您的情况是 button_clicked 方法,您必须使其成为该类的成员,因为您必须在创建它时使用 self。

    class Example(QWidget):
        [...]
    
        def initUI(self):    
            label = QLabel('Keyword') 
            button = QPushButton('OK')
            self.textbox = QLineEdit() # change this line
            hbox = QHBoxLayout()
            hbox.addWidget(label)
            hbox.addWidget(self.textbox) # change this line
    

    【讨论】:

    • 太棒了,谢谢。顺便说一句,如果button_clicked def 在另一个模块中怎么办?如何将此文本框值传递给它?
    • @barciewicz 这取决于您的设计,我建议您阅读有关 OOP 的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    相关资源
    最近更新 更多