首页 > 解决方案 > 使用 QLineEdit、QPushButton 捕获文本并使用 QLabel pypt5 显示该文本

问题描述

我正在尝试通过单击 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 类不是同一个“类”,但我不确定

任何帮助,将不胜感激

标签: pythonpython-3.xpyqtpyqt5

解决方案


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_())

推荐阅读