I made a Python GUI application using tkinter. The problem I have is that you can run as many instances as you want. But I only want one instance to be running, if the application is already running and I click again EXE or shortcut, instead it should bring existing running application to the focus.
I would use a lock file with e.g the filelock library. Create an arbitrary file: if the file is unlocked, launch the GUI and lock the file. If the file is locked, just exit.
A simple cross-platform trick is to write the process id (pid) of the first instance to a file in a known location (eg: my_program.pid in the system temporary directory). Each time you start up, check to see if that file exists. If it exists, read the pid and check if the process is running. If the process is still running, exit. If not, keep running and write your process id to the file. When the program that wrote the file exits, it should delete the file.
There are possible race conditions (eg: the running program could quit in the brief moment after checking but before your program decides to quit), but unless you're building a commercial-grade application, this is usually good enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With