如何导入函数并使用PyQt5从单独的python脚本?



我正在做一个项目,使用PyQt5包装scipy.odr(希望)一个简单的GUI。根据文档要求,Model类接受精确定义为的函数比如:

def linear_fit(a, x):
return a[0] * x + a[1] 

(参数向量作为第一个参数,自由变量x作为第二个参数)

我的意图是,用户将编写一个单独的python脚本,只包含一个函数,就像上面定义的那样,不包含需要在GUI python脚本中定义它(我写的,不希望用户触摸)。

很容易让用户使用PyQt5QFileDialog加载脚本,并使用如下函数获取脚本的绝对路径:

def browsefiles(self):
fname = QFileDialog.getOpenFileName(self, 'Open File', 'C:', 'Python Script (*.py)')
self.lineEdit_path.setText(fname[0])
self.script_path = fname[0]

接下来我想要另一个按钮,按下后将执行文档中描述的装配过程。我无法弄清楚的是如何将用户编写的函数传递给脚本内的Model类,我在其中编写了GUI。

我不能在文件的开头导入用户的脚本,因为我不知道用户在使用GUI加载脚本之前将脚本保存在哪里,我甚至不能指定函数名,因为用户可以随意调用她的函数。

我希望有人能帮我解决这个问题。

我的GUI看起来像这样:

from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
import scipy.odr as odr

class FitGUI(QMainWindow):
def __init__(self):
super(FitGUI, self).__init__()
loadUi('fitgui.ui', self)
self.pushButton_browse.clicked.connect(self.browsefiles)  # The function that I wrote above
self.pushButton_fit.clicked.connect(self.fit)
self.show()
def fit(self):
model = odr.Model(...)  # Here I want to pass the function that the user defined in a separate script
...  # The rest of the fitting procedure as described in the documentation
def main():
app = QApplication([])
window = FitGUI()
app.exec()

if __name__ == '__main__':
main()

在furas的评论之后,我研究了一下,很快就找到了Stefan Scherfke的答案在类似的帖子中,并在我的GUI脚本中使用了他的函数。

谢谢。

最新更新