1

I have a button that writes output to a file. And checks if the file with that filename already exists. It is supposed to ask the user to override or not? But it is not working. If the user says No, then the program will still override the file.

This is the code to pop up the MessageBox:

    if os.path.exists(self.filename.get()):
        tkMessageBox.showinfo('INFO', 'File already exists, want to override?.')
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Don Code
  • 781
  • 3
  • 12
  • 25

2 Answers2

5

You need to use a dialog that has yes/no or ok/cancel buttons, and you need to capture the return value of that dialog to know what the user clicked on. From that you can then decide whether to write to the file or not.

For example:

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.org has a nice little writeup on standard dialogs

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Thanks, I got it to work. All i needed was this line: result = tkmessage box... and then if result is true. Appreciate it. – Don Code Jul 11 '11 at 15:33
0
if os.path.exists(self.filename.get()) and tkMessageBox.askyesno(title='INFO', message='File already exists, want to override?.'):
    # Overwrite your file here..
ba__friend
  • 5,783
  • 2
  • 27
  • 20
  • It's not working. Everytime I try to run it, this is what pops up! It tells me that File exists, want to override. Also, what would I do if the file did not exist? How would i write to the file then?! – Don Code Jul 11 '11 at 15:26