Reputation: 35
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.
Upvotes: 0
Views: 240
Reputation: 437
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)
Edit: *args, **kwargs: *args is basically unpacking in a list format. *args accepts as many values as possible. if you print args, it'll output a list.
**kwargs is basically unpacking in a dictionary value. **kwargs accepts key-value pairs. if you print kwargs, it'll output a dictionary.
Upvotes: 2