How to make multiple Frames in Tkinter using OOP?

7131 views python oop tkinter frame
11

So, I was learning about class and methods and was trying to make multiple frames by using init method inside a class. The following is what I did:

    from tkinter import *
    import random
    from PIL import ImageTk, Image
    
    win = Tk()
    win.attributes('-fullscreen', True)
    # Define Frame Class
    
    class MyFrame:
        def __init__(self, master):
            frame = Frame(master, width = win.winfo_screenwidth(),
                    height = win.winfo_screenheight(),
                    bg='black')
            frame.pack()
    
    def FrameOne():
        frameone = MyFrame(win)
    
    
    def FrameTwo():
        frametwo = MyFrame(win)

    #Call Frame (This is where I want the following frames to have different unique attributes)
    
    FrameOne()
    FrameTwo()
    
    win.mainloop()

My question is how can I set different Frame background, border and other Frame attributes to make each Frame have unique attributes.

answered question

1 Answer

6

The easiest way to specify frame arguments while using a class is by passing key word args through to the frame. This can be done pretty easily by adding **kwargs to the end of the arguments in init. then you can pass through all the arguments as you normally would while declaring a frame.

The code would look like:

from tkinter import *
import random
from PIL import ImageTk, Image

win = Tk()
win.attributes('-fullscreen', True)
# Define Frame Class

class MyFrame:
    def __init__(self, master, **kwargs):
        frame = Frame(master, **kwargs)
        frame.pack()

def FrameOne():
    frameone = MyFrame(win, width = win.winfo_screenwidth(),
                       height = win.winfo_screenheight()//2,
                       bg='black')


def FrameTwo():
    frametwo = MyFrame(win, width=win.winfo_screenwidth(),
                       height = win.winfo_screenheight()//2,
                       bg='blue')

#Call Frame (This is where I want the following frames to have different unique attributes)

FrameOne()
FrameTwo()

win.mainloop()

Note: If you want to specify any default arguments to be applied to all the frames, add them before ,**kwargs in the declaration. Ex: Frame(window, bg="white", **kwargs)

posted this

Have an answer?

JD

Please login first before posting an answer.