我的主类创建了一个简单的QmainWindows
像这样:
class mcManageUiC(QtGui.QMainWindow):
def __init__(self):
super(mcManageUiC, self).__init__()
self.initUI()
def initUI(self):
self.show()
在我的文件末尾,我像这样启动它:
def main():
app = QtGui.QApplication(sys.argv)
renderManagerVar = mcManageUiC()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
我的问题是,每次我获取它时,它都会启动一个新窗口。
我想知道是否有一种方法可以检测我的脚本中是否存在先前的类实例(以便我关闭旧的实例或避免启动新的实例),或任何其他解决方案?
另外,当使用 py2exe 编译我的代码时,Windows 上的 .exe 文件也出现同样的问题;它每次都会启动一个新窗口。我可以在 Windows 的 setup.py 中添加一些内容来避免这样的行为吗?
可能吗,如果可以的话怎么办?
注意:我使用Windows 7 64位和eclipse进行编译。
有几种方法可以做到这一点,您可以使用 Class 属性来存储所有实例 - 如果您这样做,您可能希望通过weakref 模块将它们存储为弱引用,以防止垃圾收集问题:
class MyClass(object):
_instances=[]
def __init__(self):
if(len(self._instances) > 2):
self._instances.pop(0).kill() #kill the oldest instance
self._instances.append(self)
def kill(self):
pass #Do something to kill the instance
但这有点难看。您可能还想考虑使用某种工厂(有条件地)创建新实例。这个方法比较通用一点。
import weakref
class Factory(object):
def __init__(self,cls,nallowed):
self.product_class=cls #What class this Factory produces
self.nallowed=nallowed #Number of instances allowed
self.products=[]
def __call__(self,*args,**kwargs):
self.products=[x for x in self.products if x() is not None] #filter out dead objects
if(len(self.products) <= self.nallowed):
newproduct=self.product_class(*args,**kwargs)
self.products.append(weakref.ref(newproduct))
return newproduct
else:
return None
#This factory will create up to 2 instances of MyClass
#and refuse to create more until at least one of those
#instances have died.
factory=Factory(MyClass,2)
i1=factory("foo","bar") #instance of MyClass
i2=factory("bar","baz") #instance of MyClass
i3=factory("baz","chicken") #None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)