取代" mbox = ?????????"在def start_processing(self)部分中,如何将其作为已上载的文件。这是原始的硬编码,但已将其更改为文件上传?谢谢
class App:
def __init__(self, master):
self.master = master
# call start to initialize to create the UI elemets
self.start()
def start(self):
self.master.title("Extract Email Headers")
self.now = datetime.datetime.now()
# CREATE A TEXT/LABEL
# create a variable with text
label01 = "Please select the .mbox file you would like to analyse"
# put "label01" in "self.master" which is the window/frame
# then, put in the first row (row=0) and in the 2nd column (column=1),
# align it to "West"/"W"
tkinter.Label(
self.master, text=label01).grid(row=0, column=0, sticky=tkinter.W)
# CREATE A TEXTBOX
self.filelocation = tkinter.Entry(self.master)
self.filelocation["width"] = 60
self.filelocation.focus_set()
self.filelocation.grid(row=1, column=0)
# CREATE A BUTTON WITH "ASK TO OPEN A FILE"
# see: def browse_file(self)
self.open_file = tkinter.Button(
self.master, text="Browse...", command=self.browse_file)
# put it beside the filelocation textbox
self.open_file.grid(row=1, column=1)
# now for a button
self.submit = tkinter.Button(
self.master, text="Execute!", command=self.start_processing,
fg="red")
self.submit.grid(row=3, column=0)
def start_processing(self):
date1= "Tue, 18 Jan 2015 15:00:37"
date2="Wed, 23 Jan 2015 15:00:37"
date1 = parser.parse(date1)
date2 = parser.parse(date2)
f = open("results.txt","w")
mbox = ????????????????????
count = 0
for msg in mbox:
pprint.pprint(msg._headers, stream = f)
tempdate = parser.parse(msg['Date'])
print(tempdate)
f.close()
print(count)
pass
def browse_file(self):
# put the result in self.filename
self.filename = filedialog.askopenfilename(title="Open a file...")
# this will set the text of the self.filelocation
self.filelocation.insert(0, self.filename)
答案 0 :(得分:0)
我假设您要将文件路径存储在StringVar
中。 TK使用特殊的控制变量来为Entry对象提供功能。您可以通过调用函数tk.StringVar()
来创建字符串控件变量。
您希望在初始化UI时创建变量,因此在start()
方法中
# CREATE A TEXTBOX
self.filepath = tkinter.StringVar() # This will hold the value of self.filelocation
# We set it to the "textvariable" option of the new entry
self.filelocation = tkinter.Entry(self.master, textvariable=self.filepath)
self.filelocation["width"] = 60
self.filelocation.focus_set()
self.filelocation.grid(row=1, column=0)
现在,当我们想要检索它的值时,我们使用get()
方法。在start_processing()
方法中:
# Here it opens the file, but you may want to do something else
mbox = open(self.filepath.get(),'r')
您可以更新browse_file()
方法中设置值的方式,以便轻松使用控件变量。我们将设置控制变量的值,而不是直接插入输入框,它将在文本输入字段中自动更新。在browse_file()
:
# this will set the text of the self.filelocation
self.filepath.set( self.filename )
现在,您可以按预期方式正确设置和检索self.filelocation
的值。当然,您可以将self.filepath
的名称更改为您想要的任何名称。
了解更多信息:
答案 1 :(得分:0)
我不确定mbox
是否应该是一个打开的文件,一个列表,一个元组或一些自定义对象。我打算假设它是一个打开的文件,因为你有一个选择文件名的功能。
如果是这种情况,您需要做的就是调用条目小部件的get
方法来获取用户输入的内容:
mbox_name = self.filelocation.get()
mbox = open(mbox_name, "r")
for msg in mbox:
...