开发者

Python TkMessageBox Question not working!

开发者 https://www.devze.com 2023-03-19 04:43 出处:网络
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 开发者_JAVA技巧is not working. If the

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 开发者_JAVA技巧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?.')


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号