Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Tkinter – Error message box – File already in use – Permission denied

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading