Sergey
Sergey

Reputation: 1001

how to implement multiple inheritance?

please help to fix the script.

import tkinter
import sys


class mainMenu(tkinter.Frame):

    def __init__(self, parent):
        tkinter.Frame.__init__(self, parent)
        self.pack(side = 'top', fill = 'x')
        self.parent = parent  
        self.make_menu_bar()

    def make_menu_bar(self):
        menubar = tkinter.Menu(self.parent) 
        self.parent.config(menu = menubar)                           

        file = tkinter.Menu(menubar, tearoff = False)
        file.add_command(label = 'Quit', command = sys.exit())
        menubar.add_cascade(label = 'File', menu = file)  


class MainFrame(tkinter.Frame, mainMenu):

    def __init__(self, parent):
        tkinter.Frame.__init__(self, parent)
        self.pack(side = 'top', fill = 'x', expand = 'yes')
        self.parent = parent  
        self.make_elements()

    def make_elements():
        self.menu = TextPadMenu.__init__(self, parent)


root = MainFrame(tkinter.Tk())
root.mainloop()

the problem is that the class MainFrame can not inherit from: tkinter.Frame, mainMenu. error message is:

Traceback (most recent call last): File "C:\Python33\projects\TEXTPADS\textPad_OOP\q.py", line 22, in class MainFrame(tkinter.Frame, mainMenu): TypeError: Cannot create a consistent method resolution order (MRO) for bases Frame, mainMenu

Upvotes: 0

Views: 282

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385950

This is not a tkinter problem, this is simply how classes work in python. The short answer to your question is, you can't do what you want. It's possible to hack a workaround, but why? You shouldn't ever inherit both from a class, and from the base class of that class.

To illustrate the fact it's not a Tkinter program, here's a minimal solution that gives the same error:

class Base(object): pass
class Example1(Base): pass
class Example2(Base, Example1): pass

When run, this yields the following output:

bash-3.2$ python example.py
Traceback (most recent call last):
  File "example.py", line 3, in <module>
    class Example2(Base, Example1): pass
TypeError: Error when calling the metaclass bases
    Cannot create a consistent method resolution
order (MRO) for bases Example1, Base

Understanding the method resolution order can be difficult when you step out of the bounds of normal use. If you want a deeper answer to the question "why can I not do this?", start here:

http://www.python.org/download/releases/2.3/mro/

Upvotes: 1

Related Questions