Skip to content
Advertisement

Making child class inherit methods from parent in tkinter

I’m new to Tkinter and OOP. I’ve been trying to make child class inherit some methods from parent class because I’d have repeated code if I didn’t do it like that. But I’ve stumbled on a problem, caused probably by my limited knowledge of Tkinter and OOP.

Here is my code: (it’s really simplified, but it is enough to solve problem in complete build):

main.py

from app import App
import tkinter as tk

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Title")
    root.minsize(300, 300)
    App(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

app.py

import tkinter as tk
from tkinter import ttk
from smalerscale.test import FormFill


class App(tk.Frame):

    def __init__(self, parent, *args, **kwargs):

        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        # notebook variable
        self.notebook = ttk.Notebook(self)
        self.note1 = FormFill(self)

        self.notebook.add(self.note1, text='From')
        self.notebook.pack()

form_parent.py

import tkinter as tk
from tkinter import ttk

class FormParent(tk.Frame):
    """Form frame """

    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        self.main_message = tk.Label(self, text="Some text").pack(fill='x', padx=50, pady=5)



    def print_something(self):
        print(self.main_message)

test.py

import tkinter as tk
from tkinter import ttk

class FormFill(FormParent):

    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        super().__init__(self)

        print("It works maybe!")

        self.print_something()

And this is the error I get (something gets printed out, but no window appears):

It works maybe!
None
Traceback (most recent call last):
  File "C:/Users/kryst/PycharmProjects/covidForm/smalerscale/main.py", line 8, in <module>
    App(root).pack(side="top", fill="both", expand=True)
  File "C:UserskrystPycharmProjectscovidFormsmalerscaleapp.py", line 17, in __init__
    self.notebook.add(self.note1, text='Formulář')
  File "C:UserskrystAnaconda3libtkinterttk.py", line 844, in add
    self.tk.call(self._w, "add", child, *(_format_optdict(kw)))
_tkinter.TclError: can't add .!app.!formfill.!formfill as slave of .!app.!notebook

I’m pretty sure I messed up the __init__ and some attributes, but I can’t find a way to make it right and working.

I’d be really grateful for any help.

Advertisement

Answer

Working answer by @JacksonPro

tk.Frame.__init__(self, parent, *args, **kwargs) super().__init__(self) in FormFill class -> super().__init__(parent, *args, **kwargs)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement