python - 使用 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 类不是同一个“类”,但我不确定
任何帮助,将不胜感激
解决方案
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_())
推荐阅读
- node.js - 节点js中的Transform流可以读取字符串,但可以在对象模式下写入吗?
- java - UML 中的注释“NonNull”?
- android - 如何在没有 GPS 和互联网连接的情况下从 Android 上的 GPRS 获取当前位置?
- node.js - 构建后的应用程序问题 - ElectronJS
- linux - 带有“if”语句的 TeamCity ssh exec
- sql - 在哪里可以找到可以由 '::' lexem (postgresql) 转换的数据类型列表?
- recursion - 为什么在 CUDA 中使用递归时会收到警告?
- android - Facebook 登录:两个不同应用的相同 Facebook KeyHash
- ruby-on-rails - 更新到最新版本后未找到设计引导视图
- ansible - 带有用户输入的 Vagrant 交互式 Ansible 配置