2011-07-23 17 views
2

我剛剛開始使用Tkinter作爲編程類,並且在使用文件對話框處理程序時遇到了一些問題。 fileopen和filesaveas方法工作正常,但文件方法不是。 該規範要求filesave方法應保存到上次保存的文件;如果沒有文件被保存,則保存到上次打開的文件;否則保存爲默認名稱quiz_spec.py。出於某種原因,前兩個寫入調用似乎不能保存到達文件時(並且也不會產生任何錯誤)。 如果有人可以請告訴我爲什麼保存相同的調用在filesaveas和filesave中的功能是不同的,也指向了一個tkFileDialog保存功能的好例子。tkFileDialog filesave方法不起作用

class FileMan(): 

    def __init__(self): 
     self.lastsave = None 
     self.lastopen = None 

    def fileopen(self): 
     handle = askopenfile(mode = 'r') 
     print "name of file you picked = "+str(handle.name) 
     self.lastopen = handle 
     print "first line of data from file: "+handle.readline() 

    def filesave(self): 
     if (self.lastsave): 
      self.lastsave.write("Save: Some data to save into the file\n") 
     elif (self.lastopen): 
      self.lastopen.write("Save: Some data to save into the file\n") 
     else: 
      handle = open('quiz_spec.py', 'w') 
      handle.write("Save: This is the new content of test.txt :-)") 

    def filesaveas(self): 
     handle = asksaveasfile(mode = 'w', defaultextension = '.py') 
     print "name of file you picked = "+str(handle.name) 
     self.lastsave = handle 
     handle.write("SaveAs: Some data to save into the file\n") 
+0

祝你好運我的朋友? –

回答

3

很清楚,我認爲你的文件句柄self.lastopenself.lastsave設置爲通過調用filesave時一些等價的False。您是否在fileopenfilesave函數退出後檢查它們是否持續?很簡單的調試這種方式,嘗試:

my_man = FileMan() 
my_man.fileopen() 
my_man.filesave() 
print my_man.lastopen 
print my_man.lastsave 

如果這不起作用,嘗試用這個結果更新您的問題,我們會從那裏。此外,你應該檢查是否:

print my_man.lastopen == False and my_man.lastsave == False 
+0

我試過這個,值是持久的,兩個False檢查返回false。 – Pax

2

我想通了,我沒有關閉文件。傻我。