0

I am creating a desktop application for windows using python. I used Tkinter for GUI. My code involves triggering GUI whenever I execute it. My requirement is that at any given point of time I should have only a single instance of the GUI running. Can i set some parameter which blocks creation of new instances in Tkinter?

Please suggest some options for the same.

  • Would a new instance be created from inside the process, or would it be launched externally as a new process? For the former, the class variable solution would work. – Jared Goguen Mar 29 '16 at 15:38

1 Answers1

2

What type of behaviour do you want if someone tries to generate a GUI when one is already running? Basically what you can do is add a num_instances attribute to your class which will be incremented each time an instance is created, then decremented in your class's __del__ method. You can then check, either in __init__ or __new__ depending on the behaviour you want.

class GUI:
    num_instances = 0

    def __init__(self):
        if self.__class__.num_instances:
            raise
        self.__class__.num_instances += 1

    def __del__(self):
        self.__class__.num_instances -= 1

This is just a draft, so check that it indeed always behave as desired, but it should get you going.

EDIT: I forgot to mention it but of course you can also look at the singleton pattern

EDIT 2: for preventing multiple runs, look at this post

Community
  • 1
  • 1
Silmathoron
  • 1,781
  • 1
  • 15
  • 32
  • Yes, if one GUI is already running and a new instance is triggered, still i want only a single GUI to remain. Both are independent. I doubt if this attribute addition will really help. – Sucharitha Reddy Mar 29 '16 at 15:43
  • What do you mean exactly by 'both are independent'? Do you mean that the python script could be run several times? Do you want the OS to have only one instance of your program or is it the python script? – Silmathoron Mar 29 '16 at 15:48
  • The python script would run several times and I want the OS to have only one instance of the GUI script which would be called each time the python script runs. – Sucharitha Reddy Mar 30 '16 at 05:26
  • I edited the answer, also [here](http://blog.tplus1.com/blog/2012/08/08/python-allow-only-one-running-instance-of-a-script/) is a page with details about the pid option (which might not be the best one, but I'll let you decide on that) – Silmathoron Mar 30 '16 at 06:35