簡體   English   中英

如何將返回的數據從新分配的方法分配給Python中的變量?

[英]How to assign returned data from a new assigned method to a variable in Python?

在Python3中,我需要從使用QFileDialog選擇的文件中返回數據。 我為QLineEdit對象(self.ui.my_file_lineEdit)分配了一個新方法,以便能夠在單擊它時打開QFileDialog,但是如何將數據(文件內容)分配給變量?

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
from mainwindow import *


class Main(QtWidgets.QMainWindow):

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

        self.init_ui()


    def init_ui(self):
        """Initializing GUI from mainwindow module"""
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #opens a file for selecting my_file.csv
        self.ui.my_file_lineEdit.mouseReleaseEvent = self.openfile_Dialog


    def openfile_Dialog(self, event):
        """
        Opens a dialog for choosing a file. Takes two positionals
        arguments 'self' and 'event' because 'mouseReleaseEvent' sends two
        """
        fname = QtWidgets.QFileDialog.getOpenFileName(self, "Open file", "/home")
        if fname[0]:
            f = open(fname[0], "r")
            with f:
                data = f.read()
                return data
                #self.ui.textBrowser.setText(data)

當我在momonet中選擇文件時,出現錯誤:

TypeError:Main.openfile_Dialog()的無效結果

我想為該文件的內容分配一個變量。 就像是:

self.my_variable = self.ui.lista_lineEdit.mouseReleaseEvent = self.openfile_Dialog

編輯:我意識到你想要的內容,只是調用您的方法來分配:

self.my_variable = self.ui.lista_lineEdit.mouseReleaseEvent = self.openfile_Dialog()

您忘記了調用方法,分配的方式是引用方法本身。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM