【问题标题】:How to print a return value from a function inside a class如何从类中的函数打印返回值
【发布时间】:2015-12-01 02:21:06
【问题描述】:

我正在构建一个简单的程序来比较两个文件。我已经完成了程序的主要代码,现在我正在为它实现一个 GUI。

所以当我尝试制作一个按钮时出现了我的问题,按下该按钮将允许用户选择一个文件然后读取该文件。那是一个功能。另一个按钮将比较两个文件,一个是用户选择的文件,另一个是另一个文件。所以这是另一个功能。所以我需要将第一个函数的返回值输入到另一个函数中。

from Tkinter import *
from tkFileDialog import *




def make_dict(data):
    return dict((line.split(None, 1)[0], line)for line in data)


class myButtons:
    def __init__(self, master):
        firstFrame = Frame(master)
        firstFrame.pack()

        self.openLogButton = Button(firstFrame, text="Browse", command=self.getFileInfo)
        self.openLogButton.pack()

        self.printButton = Button(firstFrame, text="Print", command=self.compareAction)
        self.printButton.pack()

        self.quitButton = Button(firstFrame, text="Quit", command=firstFrame.quit)
        self.quitButton.pack()

        self.scroll = Scrollbar(firstFrame)
        self.inputText = Text(firstFrame, height=4, width=50)

        self.scroll.pack(side=RIGHT, fill=Y)
        self.inputText.pack(side=LEFT, fill=Y)

        self.scroll.config(command=self.inputText.yview)
        self.inputText.config(yscrollcommand=self.scroll.set)

        self.logFile = self.getFileInfo()

        thisIsTest = self.getFileInfo

    def printMessage(self):
        print "This works"
        test = self.inputText.get("1.0", END)
        print test

    def getFileInfo(self):
        return askopenfile(mode='rb')

    def compareAction(self):
        def process(infile, outfile, keywords):
            keys = [[k[0], k[1], 0] for k in keywords]
            endk = None
            with open(infile, 'rb') as fdin:
                with open(outfile, 'ab') as fdout:
                    fdout.write("<" + words + ">" + "\r\n")
                    for line in fdin:
                        if endk is not None:
                            fdout.write(line)
                            if line.find(endk) >= 0:
                                fdout.write("\r\n")
                                endk = None
                        else:
                            for k in keys:
                                index = line.find(k[0])
                                if index >= 0:
                                    fdout.write(line[index + len(k[0]):].lstrip())
                                    endk = k[1]
                                    k[2] += 1
            if endk is not None:
                raise Exception(endk + "Not found before end of file")
            return keys
        start_token = self.inputText.get("1.0", END)
        end_token = "[+][+]"
        split_start = start_token.split(' ')
        outputText = 'test.txt'

        print self.logFile

        # for words in split_start:
        #     process(self.getFileInfo, outputText, split_start)


root = Tk()
b = myButtons(root)

root.mainloop()

现在我只是想测试我的compareAction 函数是否收到了来自getFileInfo 函数的返回值。到目前为止,当我尝试print self.getFileInfo 时,我得到了这样的结果:&lt;bound method myButtons.getFileInfo of &lt;__main__.myButtons instance at 0x100863ef0&gt;&gt;

我认为是函数的内存地址,而不是读取文件时函数的值。

这个想法很简单。用户选择要打开的文件,该文件被打开并读取,然后在比较操作中使用该返回值后返回。

【问题讨论】:

    标签: python function tkinter return return-value


    【解决方案1】:

    我能想到的解决这个问题的最佳方法是添加另一个函数。尝试将 getFileInfo(self) 更改为:

    def getFileInfo(self):
        global filename
        filename = askopenfilename()
        return open(filename, mode="rb")
    

    它基本上和你之前的函数做同样的事情,除了它使文件全局。然后像这样创建另一个名为 getFileName(self) 的函数。

    def getFileName(self):
        return filename
    

    现在调用流程函数时,使用 self.getFileName 代替 self.getFileInfo:

    process(self.getFileName, outputText, split_start)
    

    如果您想知道为什么会得到绑定的方法输出,可能是因为您正在打开文件而不是读取它。本质上,当您运行 print self.logFile 时,它​​会返回一个文件对象。这是我尝试在我的桌面上打印打开的文件时发生的情况:

    #Input
    print askopenfile(mode="rb")
    
    #Output
    <open file u'C:/Users/User/Desktop/stuff.txt', mode 'rb' at 0x029BA078>
    

    这是我打印文件并使用 read() 时发生的情况:

    #Input
    print askopenfile(mode="rb").read()
    
    #Output
    These are words in the file stuff.txt.
    

    本文档here 提供了有关文件及其工作方式的好主意。还记得在阅读完文件后关闭文件以防止出现其他问题。

    【讨论】:

      【解决方案2】:

      您只需将print self.getFileInfo 更改为print self.getFileInfo()。请记住,使用括号是调用函数的方式。也可以在代码中的任何其他位置执行此操作。请注意,这将再次调用该函数。你可以改为print self.logFile 来查看结果。

      【讨论】:

      • 我已经厌倦了这个问题是这将再次重新执行该功能。所以如果我点击 compareAction 按钮,它会提示我选择一个文件。我不希望该按钮执行此操作,我只希望它“执行其功能内的任何操作”使用print self.getFileInfo() 在这里对我不起作用。
      • 我在使用self.logFile 时不断获取函数&lt;bound method myButtons.getFileInfo of &lt;__main__.myButtons instance at 0x10a50aef0&gt;&gt; 的地址,也许我错误地从getFileInfo 函数返回了一个值?
      • 您是否将 self.logfile=getFileInfo 更改为 self.logfile=getFileInfo()?
      • 是的。如果我这样做了,那么当我启动程序时,getFileInfo 函数会立即执行,而无需按下按钮。它仍然返回一个内存地址。
      • 当然。编辑它
      猜你喜欢
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 2021-07-22
      • 2018-08-28
      相关资源
      最近更新 更多