我如何创建一个tkinter mixin作为一个单例

时间:2019-05-18 19:29:27

标签: python python-3.x tkinter singleton mixins

我正在尝试使用python3 tkinter创建一个可重用表单的集合,并使用mixin来实现菜单命令等常见方法。由于大多数组件中都使用了mixin,因此似乎创建了mixin类的多个单独实例但是我尝试将mixin变成单例,但失败了,TypeError: object() takes no parameters

我是一个老的cobol程序员,他开始了这个项目,试图让我的脑袋大开-这让我很头疼

我添加了一个中间基类,该基类应该删除args而不起作用。

PROGRAM_NAME = "GuiMenuMixin"

class Base(object):
    def __init__(self, *args, **kwargs): pass

class GuiMenuMixin(Base):

    _singleton = None
    def __new__(cls,*args, **kwargs):
        if not cls._singleton:
            cls._singleton = super().__new__(cls,*args,**kwargs)
        return cls._singleton

    def __init__(self):
        try:
            self.initialProgramName
        except AttributeError: 
             try:
                self.programName  
                self.initialProgramName = self.programName   
            except AttributeError: 
                self.programName = PROGRAM_NAME

# pretty basic mixin stuff follows

# sample usage which fails

class SimpleTitleBarFrame(Frame, GuiMenuMixin):

    def __init__(self, parent=None,  **args):

        super().__init__(parent, **args)

        try: self.programName
        except AttributeError: self.programName = PROGRAM_NAME

        GuiMenuMixin.__init__(self)

        self.parent=parent

############## stuff removed


        leftMenu = SimpleMenuBarFrame(self, menuSpec=self.menuSpec, style="BW.TLabel")
        leftMenu.grid(row=0,column=6,sticky=W)
        self.columnconfigure(6, weight=0)


        rightIcons = SimpleIconBarFrame(self, iconSpec=self.iconSpec)
        rightIcons.grid(row=0,column=10,sticky=W)
        self.columnconfigure(10, weight=0)


#### This runs ok as it does not call any child frames utilising the mixin

PROGRAM_NAME = "SimpleMenuBarFrame"

class SimpleMenuBarFrame(Frame, GuiMenuMixin,):

    def __init__(self, parent=None, **args):
        super().__init__(parent, **args)

        try:
            self.programName                                                     
        except AttributeError: 
            self.programName = PROGRAM_NAME

        GuiMenuMixin.__init__(self)

        self.menuBar = self.makeMenu(menuSpec=self.menuSpec)

错误:

  

TypeError: object() takes no parameters

0 个答案:

没有答案