gpt4 book ai didi

python - 按下按钮时打印 LineEdit 文本

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:44 27 4
gpt4 key购买 nike

如何更改以下代码,使其在按下“确定”按钮时打印行编辑小部件中写入的内容?当前版本返回“'Example'对象没有属性'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_())

`

最佳答案

如果您希望可以在类的所有部分访问变量,就像您的例子中的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

关于python - 按下按钮时打印 LineEdit 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48835586/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com