python - 根据文本框输入在标签中打印一些文本 - PyQT5
问题描述
我需要帮助弄清楚如何使用 PyQT5 中文本框中写入的值,并使用该值来构建 IF 语句。关于如何做的任何建议?我试图将文本框中的文本声明为变量并在 IF 语句中使用它,但我似乎无法弄清楚如何正确执行它,并且每次运行代码时,都会显示一些退出代码(- 1073741819(0xC0000005))。
总结一下,不能使用将文本框的值传递给变量来执行 IF 语句。
我在下面有这段代码:
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QTextEdit
def window():
app = QApplication(sys.argv)
win = QMainWindow()
win.setGeometry(200, 200, 400, 400)
win.setWindowTitle("Register Program")
label = QtWidgets.QLabel(win)
label.setText("Random Text")
label.move(169, 15)
label2 = QtWidgets.QLabel(win)
label2.resize(300, 100)
label2.setText("1- Register new person\n2- See all regestries\n3- See last regestry\n\nPress ESC to exit\n")
label2.move(70, 50)
textbox = QtWidgets.QLineEdit(win)
textbox.setText("")
textbox.resize(250, 25)
textbox.move(70, 250)
button1 = QtWidgets.QPushButton(win)
button1.move(150, 300)
button1.setText("Submit")
button1.clicked.connect(clicked)
button2 = QtWidgets.QPushButton(win)
button2.move(150, 335)
button2.setText("Close")
button2.clicked.connect(close)
win.show()
sys.exit(app.exec_())
def clicked():
inpt = int(window().textbox.text)
if inpt == 1:
print("Hello")
def close():
sys.exit()
window()```
解决方案
如果您只是想获取用户输入,可以调用内置静态方法来请求特定类型的输入:https ://doc.qt.io/qt-5/qinputdialog.html#getText
但是,如果您想制作自己的小部件,则需要使用信号和插槽来触发 python 方法来存储值。这是在课堂上最容易做到的。每当文本随textChanged
信号变化时,您都可以触发该方法并执行您需要对其执行的任何操作。
(注意,我没有运行它,因为我目前没有安装 PyQt5,但它应该可以工作)
from PyQt5 import QtCore, QtGui, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
# type: (QtWidgets.QWidget) -> None
super(Widget, self).__init__(parent)
self.line_edit = QtWidgets.QLineEdit()
main_layout = QtWidgets.QVBoxLayout()
main_layout.addWidget(self.line_edit)
self.setLayout(main_layout)
self.line_edit.textChanged.connect(self.on_text_changed)
def get_text(self):
return self.line_edit.text()
def on_text_changed(self, text):
print("The text was changed to:", text)
if __name__ == '__main__':
app = QtWidgets.QApplication([])
widget = Widget()
widget.show()
app.exec_()
编辑:另外,为了澄清你为什么会出错, QApplication 是一个单例。这意味着只能创建一个。如果您尝试创建第二个,则会收到错误消息。访问当前 QApplication 的最佳方法是调用QApplication.instance()
. 您也只需调用app.exec_()
一次,因为一旦应用程序运行,它将继续在后台运行。您应该使用信号/插槽与 UI 交互并触发您要运行的代码。
推荐阅读
- arrays - 给定一个数组,其中 arr[i] = i-1 使用以下方法,输出将是什么?
- c# - 如何在带有复选框的组合框中继续显示选定的文本?
- c# - JsonDocument 获取 JSON 字符串
- elasticsearch - Logstash UDP 问题
- c# - 如何在部分类中实现 OnPropertyChanged 事件
- git - SourceTree - 反向提交和推送
- javascript - Javascript onchange 功能在移动设备上的选择菜单中不起作用
- android - android 应用程序消息中的本地化问题在 RTL 中反向显示
- nginx - 如何重定向到外部 https 站点?
- jenkins - 使用 Jenkins 向 JBoss 部署战争时“无法初始化命令上下文”