Preventing creation of multiple GUI instances - python

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.

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

Related

Should I use a class when it only makes sense to have one instance?

I am a beginner Pythoon programmer working on the setup of a Flask video server based on this tutorial. The bit of code I have a problem with is used to initialize the computer webcam and output the frames :
class Camera(object):
thread = None # background thread that reads frames from camera
frame = None # current frame is stored here by background thread
last_access = 0 # time of last client access to the camera
start_time = 0 # time at which the camera is started
def __init__(self):
"""Start the background camera thread if it isn't running yet."""
...
def get_frame(self):
"""Return the current camera frame."""
...
#staticmethod
def frames():
""""Generator that returns frames from the camera."""
...
#classmethod
def _thread(cls):
"""Camera background thread."""
...
It does not make sense to me to use a class for this, since there should only be one instance of the Camera object. Because of this, every time a request is made to the server, a new object is a created for no reason.
I've looked at possible ways to refactor this. What I've found so far :
Use a singleton class, but that does not seem recommended in Python
Put everything in a separate module. Then all the class variables would become global variables, and that's bad from what I've read
There is nothing wrong with creating a class for which you expect to have a single instance. Classes are a fantastic way to organize and compartmentalize your code. You can use a module for that, but if you're modeling an actual object (and a "Camera" certainly seems to be an object), classes are the right tool for the job.
In addition, using a class makes it much easier to test your code, since you can import the class in a test case and interact with it outside of the program itself.
A very good reason to creating a class is to have all the methods (that will work as attributes for your object), in one place. This gives full control over the dynamics of what may be happening with the object especially when your program grows in size. A compelling example, could be when you include say, logging into your code and use the #get_log(for a get_log() wrapper method inside your class) decorator above all the functions outside the class. This logging will provide necessary debugging information.
Modularizing the code using classes compensates for the slight overhead with memory usage for one object especially when long-term code maintenance, quality and control are key.

Custom QTreeview expanded event method

When I create my own custom QTreeView with a defined 'expanded' method, do I need to do anything special to emit the default signal? I've commented out pseudo code representing what i'm asking about. Or am I safe to do what I'm currently doing?
class JMTreeView(QtGui.QTreeView):
changed = QtCore.Signal()
def __init__(self):
super(JMTreeView, self).__init__()
self.expanded.connect(self.expanded_item)
def expanded_item(self, event):
print "expanded"
# super(JMTreeView, self).expanded(event)
Similar to the way I handle when I override the 'showEvent' for a dialog, i call the 'super' at the end of the function. Do i need to add something similar to my 'expanded' method?
def showEvent(self, event):
geom = self.frameGeometry()
geom.moveCenter(QtGui.QCursor.pos())
self.setGeometry(geom)
super(Browser, self).showEvent(event)
The QTreeView class does not have an expanded method. There is only an expanded signal. More to the point, the signal and slots mechanism is completely separate from the event system, so there is no parallel with overriding protected methods like showEvent.
Most of the event-handlers (like showEvent) are related to activity that originates outside of the application. They usually implement some default behaviour, but sometimes do nothing at all. They are almost always virtual methods, which means you can provide your own implementation which Qt will call instead of the default. If your re-implementation needs to keep the default behaviour (or modify it in some way), it can do so by calling the base-class implementation.
By contrast, signals always originate inside the application. There are no default handlers for them - they simply broadcast messages (like a radio beacon). It is entirely up to the listeners to decide what to do with the messages. It doesn't matter if there are never any listeners, or if the messages are never processed.

Python Threading - Creation of a subclass?

I am having a problem wrapping my brain around the reason for creating a subclass when using threading in python. I've read a number of websites including tutorialspoint.
The docs say you need to define a new subclass of the Thread class. I have a basic understanding of classes but haven't played with subclasses at all. I haven't had to do anything like this yet with any other modules I've used like os & ftplib. Can anyone point me to a site that may explain this better for a newbie scripter?
#!/usr/bin/python
import threading
class myThread (threading.Thread):
I was able to write my own script without creating this subclass and it works so I am not sure why this is stated as a requirement. This is my simple little script I created to help me understand threading initially.
#!/usr/bin/python
# Import the necessary modules
import threading
import ftplib
# FTP function - Connects and performs directory listing
class
def ftpconnect(target):
ftp = ftplib.FTP(target)
ftp.login()
print "File list from: %s" % target
files = ftp.dir()
print files
# Main function - Iterates through a lists of FTP sites creating theads
def main():
sites = ["ftp.openbsd.org","ftp.ucsb.edu","ubuntu.osuosl.org"]
for i in sites:
myThread = threading.Thread(target=ftpconnect(i))
myThread.start()
print "The thread's ID is : " + str(myThread.ident)
if (__name__ == "__main__"):
main()
Thanks for the help!
I am using tutorialspoint.com for my reference material. It sounds like your saying I am biting off more than I can chew and I should keep it simple at this point considering I don't need to use the more complicated options yet. This is what the site says:
Creating Thread using Threading Module:
To implement a new thread using the threading module, you have to do the following:
- Define a new subclass of the Thread class.
- Override the __init__(self [,args]) method to add additional arguments.
- Then, override the run(self [,args]) method to implement what the thread should do when started.
Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start(), which will in turn call run() method.
The docs say you need to define a new subclass of the Thread class.
and
I was able to write my own script without creating this subclass and it works so I am not sure why this is stated as a requirement.
The Python docs say no such thing, and can't guess which docs you're talking about. Here are Python docs:
There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. No other methods (except for the constructor) should be overridden in a subclass. In other words, only override the init() and run() methods of this class.
You're using the first method specified there (passing a callable to the Thread() constructor). That's fine. Subclasses become more valuable when the callable needs access to state variables and you don't want to clutter your program with globals for that purpose, and especially when using multiple threads that each need their own state variables. Then state variables can usually be implemented as instance variables on your own subclass of threading.Thread. If you don't need that (yet), don't worry about it (yet).

How to run gtk.Builder.connect_signals multiple times?

This is a follow-up question to this other one.
I am trying to extend gtk.Builder but I found out that once the builder is instantiated one can only call the connect_signals method once: if called more than once, any call after the second will return None (which would mean: all signals have been connected, which is a blatant lie!).
The problem is that in my design I would need to pass around the builder instance to various modules (each of them has some of the handlers for managing the GUI), but this way, I can't.
I tried to see if I could understand how/where gtk.Builder stores the handler names that assigned withing the Glade GUI, in order to write my own method to overcome this limitation, but after more than an hour of console experiments I still haven't understand where this information is stored.
Any help or pointer is highly appreciated! :)
That connect_signals only works once is an old but undocumented limitation of the GtkBuilder C code. Especially from Python there is no way to access its internals to remedy that.
Instead of the builder you could pass around a dictionary. After everyone added their handlers you call connect_signals with it.
i think if you want to call connect_signals multiple times you must disconnect inbetween, kindof like
x = self.menu.connect('activate', self.func1)
self.menu.disconnect(x)
x = self.menu.connect('activate', self.func2)

About the need of creating a class in Python

Let's say that i have a Python module to control a videoconference system. In that module i have some global variables and functions to control the states of the videoconference, the calls, a phone book, etc.
To start the control system, the module self-executes a function to initialize the videoconference (ethernet connection, polling states and so)
Now, if i need to start controlling a second videoconference system, i'm not sure how to approach that problem: i thought about making the videoconference module a class and create two instances (one for each videoconference system) and then initialize both, but the problem is that i don't really need to have two instances of a videoconference class since i won't do anything with those objects because i only need to initialize the systems; after that i don't need to call or keep them for anything else.
example code:
Videoconference.py
class Videoconference:
def __init__(self):
self.state = 0
#Initialization code
Main.py
from Videoconference import Videoconference
vidC1 = Videoconference()
vidC2 = Videoconference()
#vidC1 and vidC2 will never be use again
So, the question is: should i convert the videoconference module to a class and create instances (like in the example), even if i'm not going to use them for anything else appart of the initialization process? Or is there another solution without creating a class?
Perhaps this is a matter of preference, but I think having a class in the above case would be the safer bet. Often I'll write a function and when it gets too complicated I'll think that I should have created a class (and often do so), but I've never created a class that was too simple and thought that this is too easy why didn't I just create a function.
Even if you have one object instead of two, it often helps readability to create a class. For example:
vid = VideoConference()
# vid.initialize_old_system() # Suppose you have an old system that you no longer use
# But want to keep its method for reference
vid.initialize_new_system()
vid.view_call_history(since=yesterday)
This sounds like the perfect use case for a VideoConferenceSystem object. You say you have globals (ew!) that govern state (yuck!) and calls functions for control.
Sounds to me like you've got the chance to convert that all to an object that has attributes that hold state and methods to mutate it. Sounds like you should be refactoring more than just the initialization code, so those vidC1 and vidC2 objects are useful.
I think you're approaching this problem the right way in your example. In this way, you can have multiple video conferences, each of which may have different attribute states (e.g. vidC1.conference_duration, etc.).

Categories

Resources