使用QLineEdit,QPushButton捕获文本并使用QLabel pypt5显示该文本

时间:2018-10-07 19:17:51

标签: python python-3.x pyqt pyqt5

我试图通过单击QPushButton捕获文本,并使用pyqt5在QLabel中显示文本

我对这些东西真的很陌生,所以请放轻松!

这是我到目前为止的代码:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QPushButton, QLabel, QLineEdit
from PyQt5.QtCore import pyqtSlot

class Window(QWidget):

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

        self.initUI()

    def initUI(self):

        hbox = QHBoxLayout()

        game_name = QLabel("Game Name:", self)

        game_line_edit = QLineEdit(self)

        search_button = QPushButton("Search", self)

        search_button.clicked.connect(self.on_click)

        hbox.addWidget(game_name)
        hbox.addWidget(game_line_edit)
        hbox.addWidget(search_button)

        self.setLayout(hbox)

        self.show()

    @pyqtSlot()
    def on_click(self):
        game = QLabel(game_line_edit.text(), self)
        hbox.addWidget(game)



if __name__ == '__main__':

    app = QApplication(sys.argv)
    win = Window()
    sys.exit(app.exec_())

我不断收到此错误:

game = QLabel(game_line_edit.text(), self)
NameError: name 'game_line_edit' is not defined

我不确定为什么未定义game_line_edit,但有种感觉,因为它与我的on_click类不是同一“类”,但不确定

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QPushButton, QLabel, QLineEdit
from PyQt5.QtCore import pyqtSlot

class Window(QWidget):

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

        self.initUI()

    def initUI(self):

        self.hbox = QHBoxLayout()

        self.game_name = QLabel("Game Name:", self)

        self.game_line_edit = QLineEdit(self)

        self.search_button = QPushButton("Search", self)

        self.search_button.clicked.connect(self.on_click)

        self.hbox.addWidget(self.game_name)
        self.hbox.addWidget(self.game_line_edit)
        self.hbox.addWidget(self.search_button)

        self.setLayout(self.hbox)

        self.show()

    @pyqtSlot()
    def on_click(self):
        game = QLabel(self.game_line_edit.text(), self)
        self.hbox.addWidget(game)




if __name__ == '__main__':

    app = QApplication(sys.argv)
    win = Window()
    sys.exit(app.exec_())