我正在建立一个简单的程序,将比较两个文件。我已经完成了程序的主代码,现在我正在为它实现一个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
时,我得到了这样的结果:<bound method myButtons.getFileInfo of <__main__.myButtons instance at 0x100863ef0>>
我认为这是函数的内存地址,而不是函数在读取文件时的值。你知道吗
想法很简单。用户选择要打开的文件,打开并读取该文件,然后在比较中使用返回值后返回。你知道吗
您只需要将
print self.getFileInfo
更改为print self.getFileInfo()
。请记住,使用括号是调用函数的方式。也可以在代码中的任何其他位置执行此操作。请注意,这将再次调用函数。您可以改为print self.logFile
查看结果。你知道吗我能想到的解决这个问题的最好方法是添加另一个函数。尝试将getFileInfo(self)更改为:
它基本上与上一个函数做相同的事情,只是它使文件成为全局的。然后生成另一个名为getFileName(self)的函数,如下所示。你知道吗
现在调用process函数时,使用self.getFileName文件名而不是self.getFileInfo文件地址:
如果您想知道为什么会得到绑定方法输出,可能是因为您正在打开文件而没有读取它。基本上当你运行print时self.log文件,它正在返回一个文件对象。这是我尝试在桌面上打印打开的文件时发生的情况:
这就是我打印文件并使用read()时发生的情况:
这个文档here提供了一个关于文件及其工作方式的好主意。还要记住在读取完文件后关闭它,以防止出现其他问题。你知道吗
相关问题 更多 >
编程相关推荐