Python PyQt5:如何将一个按钮的变量输出用于另一个按钮?

Python PyQt5:如何将一个按钮的变量输出用于另一个按钮?,python,python-3.x,pyqt,pyqt5,qfiledialog,Python,Python 3.x,Pyqt,Pyqt5,Qfiledialog,我正在尝试使用PyQt5在python代码上实现GUI。我弄明白了如何使用按钮以及如何将它们与功能连接起来 按钮b3调用函数“SelectFile” 我遇到的问题是,我希望“SelectFile”返回文件的路径,然后将该路径用于另一个按钮调用的另一个函数。我该怎么做 比如说, self.b1.clicked.connect(self.btn_clk) def btn_clk(self): sender = self.sender() if sender.text() =='P

我正在尝试使用PyQt5在python代码上实现GUI。我弄明白了如何使用按钮以及如何将它们与功能连接起来

按钮b3调用函数“SelectFile”

我遇到的问题是,我希望“SelectFile”返回文件的路径,然后将该路径用于另一个按钮调用的另一个函数。我该怎么做

比如说,

self.b1.clicked.connect(self.btn_clk)

 def btn_clk(self):
    sender = self.sender()
    if sender.text() =='Print':
        test = filename
        print(test)
“filename”没有传递给“btn_clk”,我不知道怎么做。 我尝试在“btn_clk”的定义中输入“filename”和其他尝试,但没有任何效果


谢谢

只要把它放在课堂上就可以了。使用下面的代码进行测试。您可以根据自己的代码进行调整

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys

class TestSelectFile(QDialog):
    def __init__(self):
        QDialog.__init__(self)

        self.layout = QVBoxLayout()
        self.selectfilebutton = QPushButton('Select file')
        self.printpathbutton = QPushButton('Press to print')

        self.setLayout(self.layout)
        self.layout.addWidget(self.selectfilebutton)
        self.layout.addWidget(self.printpathbutton)

        self.selectfilebutton.clicked.connect(self.getpath)
        self.printpathbutton.clicked.connect(self.printpath)

    def getpath(self):
        self.path = QFileDialog.getOpenFileName(self,caption='Get a path from',filter='All Files(*.*)')

    def printpath(self):
        print(self.path)



app = QApplication(sys.argv)
dialog = TestSelectFile()
dialog.show()
app.exec_()

创建一个变量并为其指定要保存的值。
def SelectFile(self):
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    filename = QFileDialog.getOpenFileName(self, "Select file", "", "TMY3 files (*.epw)", options=options)[0]
        print(filename)
        self.b1_filename = filename
        return filename

self.b1.clicked.connect(self.btn_clk)

def btn_clk(self):
    sender = self.sender()
    if sender.text() =='Print':
        test = self.b1_filename
        print(test)
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys

class TestSelectFile(QDialog):
    def __init__(self):
        QDialog.__init__(self)

        self.layout = QVBoxLayout()
        self.selectfilebutton = QPushButton('Select file')
        self.printpathbutton = QPushButton('Press to print')

        self.setLayout(self.layout)
        self.layout.addWidget(self.selectfilebutton)
        self.layout.addWidget(self.printpathbutton)

        self.selectfilebutton.clicked.connect(self.getpath)
        self.printpathbutton.clicked.connect(self.printpath)

    def getpath(self):
        self.path = QFileDialog.getOpenFileName(self,caption='Get a path from',filter='All Files(*.*)')

    def printpath(self):
        print(self.path)



app = QApplication(sys.argv)
dialog = TestSelectFile()
dialog.show()
app.exec_()