2011-07-11 51 views
1

我有一個將輸出寫入文件的按鈕。並檢查具有該文件名的文件是否已經存在。它應該要求用戶重寫或不重寫?但它不起作用。如果用戶說「否」,那麼程序仍會覆蓋該文件。Python TkMessageBox問題不起作用!

這是彈出消息框代碼:

if os.path.exists(self.filename.get()): 
     tkMessageBox.showinfo('INFO', 'File already exists, want to override?.') 

回答

5

您需要使用具有是/否或確定一個對話框/取消按鈕,你需要捕捉的返回值該對話框知道用戶點擊了什麼。從那裏你可以決定是否寫入文件。

例如:

import Tkinter as tk 
import tkMessageBox 

class SampleApp(tk.Tk): 
    def __init__(self, *args, **kwargs): 
     tk.Tk.__init__(self, *args, **kwargs) 
     self.button = tk.Button(self, text="Push me", command=self.OnButton) 
     self.button.pack() 

    def OnButton(self): 
     result = tkMessageBox.askokcancel(title="File already exists", 
             message="File already exists. Overwrite?") 
     if result is True: 
      print "User clicked Ok" 
     else: 
      print "User clicked Cancel" 

if __name__ == "__main__": 
    app = SampleApp() 
    app.mainloop() 

effbot.orgstandard dialogs

+0

謝謝,我得到它的工作。我所需要的就是這一行:result = tkmessage box ...然後如果結果是真的。欣賞它。 –

0
if os.path.exists(self.filename.get()) and tkMessageBox.askyesno(title='INFO', message='File already exists, want to override?.'): 
    # Overwrite your file here.. 
+0

一個可愛的小書面記錄它不工作。每次我嘗試運行它時,都會彈出它!它告訴我File存在,想要覆蓋。另外,如果文件不存在,我該怎麼辦?我將如何寫入文件呢?! –