Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell tkinter application to run only one instance?

Tags:

python

tkinter

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.

like image 567
Saul Han Avatar asked Sep 17 '25 18:09

Saul Han


2 Answers

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.

like image 191
Jeremiah Rose Avatar answered Sep 19 '25 08:09

Jeremiah Rose


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.

like image 34
Bryan Oakley Avatar answered Sep 19 '25 08:09

Bryan Oakley