Don Code
Don Code

Reputation: 878

Python TkMessageBox Question not working!

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?.')

Upvotes: 1

Views: 6224

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 385960

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

Upvotes: 5

ba__friend
ba__friend

Reputation: 5903

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

Upvotes: 0

Related Questions