Inheriting from Frame or not in a Tkinter application


In the Object-Oriented Programming Paradigm, Inheritance is used for acquiring the properties of the base class and using them in a derived class. Considering the case for a Tkinter application, we can inherit all the properties of a frame defined in a base class such as background color, foreground color, font properties, etc., into a derived class or a frame.

In order to support Inheritance, we have to define a class that contains some basic properties of a frame such as height, width, bg, fg, font, etc.

Example

# Import Tkinter Library
from tkinter import *

# Create an instance of Tkinter frame
win= Tk()

# Set the size of the application window
win.geometry("700x350")

# Create a class to define the frame
class NewFrame(Frame):
   def __init__(self, win):
      super().__init__()
      self["height"] = 200
      self["width"] = 200
      self["bd"] = 10
      self["relief"] = RAISED
      self["bg"] = "#aa11bb"

# Create Frame object
frame_a= NewFrame(win)
frame_b= NewFrame(win)
frame_a.grid(row=0, column=0)
frame_b.grid(row=0, column=1)

win.mainloop()

Output

Running the above code will display a window containing two frames having the same properties of its frame defined in a class.

Updated on: 07-Jun-2021

797 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements