简体   繁体   English

如何在python中将信息从一种方法传递到另一种方法

[英]how can I pass info from one method to another in python

So I'm a noob to PyQt and to python for that matter. 所以我对PyQt和python都不感兴趣。 I'm trying to write a simple Qt app that allows you to click a button then display what you entered in the text field in the command prompt, (i know this is ridiculously basic, but I'm trying to learn it) but I can't seem to figure out how to access the textBox attribute from printTexInput() method. 我正在尝试编写一个简单的Qt应用程序,该应用程序允许您单击一个按钮,然后在命令提示符下显示在文本字段中输入的内容(我知道这很荒谬,但是我正在尝试学习)似乎无法弄清楚如何从printTexInput()方法访问textBox属性。 so my question is how would you access that value from another method? 所以我的问题是,您将如何从其他方法访问该值? or is my way of thinking about this completely wrong? 还是我的思考方式完全错误? any help would be greatly appreciated. 任何帮助将不胜感激。

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):

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

        self.initUI()

    def initUI(self):
        textBoxLabel = QtGui.QLabel('Text Input')
        self.textBox = QtGui.QLineEdit()

        okayButton = QtGui.QPushButton("Okay")

        okayButton.clicked.connect(self.printTexInput)

        grid = QtGui.QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(textBoxLabel, 0, 0)
        grid.addWidget(textBox, 0, 1)
        grid.addWidget(okayButton, 3, 3)

        self.setLayout(grid)

        self.setGeometry(300,300,250,250)
        self.setWindowTitle("test")
        self.show()

    def printTexInput(self):
        print self.textBox.text()
        self.close()




def main():

    app = QtGui.QApplication(sys.argv)
    ex  = Example()
    sys.exit(app.exec_())

if __name__=='__main__':
    main()

Right now textBox is a local variable in the initUI method, and it's lost forever when you leave that method. 眼下textBox是在一个局部变量initUI方法,当你离开这个方法,它是永远失去了。 If you want to store textBox on this instance of your class, you need to say self.textBox = QtGui.QLineEdit() instead. 如果你想存储textBox你的类的实例,你需要说self.textBox = QtGui.QLineEdit()来代替。 Then in printTextInput you can call print self.textBox.text() instead. 然后,在printTextInput您可以调用print self.textBox.text()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM