I am trying to save data in a file through a Tkinter app. If the file already exists and is currently open by another application, I can, of course, not write on it but I would like to inform the user that the file is open somewhere else.
In Python Console (Spyder), I receive the following message:
Exception in Tkinter callback
[...]
File "MyFile.py", line 200, in plot_data_save_file
file=open(file_name,"w")
PermissionError: [Errno 13] Permission denied: "FileToSaveDataIn.xy"
I know how to create a Tkinter messagebox but how can I know if Python Console raised the error and pass this information to Tkinter?
CodePudding user response:
What you need is a try/except statement. This allows you to attempt some code and if it errors you can then capture that error and use it however you want. In this case I am printing it to console but you can simple use that same variable to load to a messagebox.
Here is a simple example of a try/except statement:
import tkinter.messagebox as box
try:
# ... Some logic here ...
except BaseException as e:
print('Exception: {}'.format(e))
# This line should work for your needs
# box.showerror('Error!', 'Exception: {}'.format(e))
Typically you would want to write specific handlers for errors instead of doing a general exception like I have done here but for illustrations reasons this will suffice.