我有一个将输出写入文件的按钮。并检查具有该文件名的文件是否已经存在。它应该要求用户覆盖与否?但它不起作用。如果用户说不,那么程序仍将覆盖该文件。
这是弹出消息框的代码:
if os.path.exists(self.filename.get()):
tkMessageBox.showinfo('INFO', 'File already exists, want to override?.')
我有一个将输出写入文件的按钮。并检查具有该文件名的文件是否已经存在。它应该要求用户覆盖与否?但它不起作用。如果用户说不,那么程序仍将覆盖该文件。
这是弹出消息框的代码:
if os.path.exists(self.filename.get()):
tkMessageBox.showinfo('INFO', 'File already exists, want to override?.')
您需要使用具有是/否或确定/取消按钮的对话框,并且您需要捕获该对话框的返回值以了解用户单击的内容。然后,您可以决定是否写入文件。
例如:
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有一篇关于标准对话框的不错的小文章
if os.path.exists(self.filename.get()) and tkMessageBox.askyesno(title='INFO', message='File already exists, want to override?.'):
# Overwrite your file here..