A screen of what I want to do is better than explanations =>
No matter how big the frame is I want to know if I can choose the color for some part of the frame
EDIT : example of what I mean, I want the top to be in blue for example even though it's the same frame (if a "slicing" can be done like strings It would be good but I don't think it exist)
import tkinter as tk
from tkinter import CENTER, ttk
root = tk.Tk()
root.geometry('500x200')
frame = tk.Frame(root,width=100,height=100,bg='red')
frame.pack_propagate(0)
frame.pack()
label = tk.Label(frame,text='test',bg='red')
label.place(relx=0.5,rely=0.5,anchor=CENTER)
root.mainloop()
CodePudding user response:
To make a Frame
two-colored, you need to put some other widget inside to create the color stripe, for instance, another Frame
. Then, use place
to put the second frame inside the first one, this way you can pack
/grid
/place
other widgets in your first frame without being affected by the presence of the second one.
Here is an example where the height of the color stripe is a fraction of frame's height. The stripe automatically resizes with the frame thanks to the use of the relheight
option in place()
.
import tkinter as tk
class TwoColoredFrame(tk.Frame):
def __init__(self, master, bg1, bg2, fraction=0.5, **kw):
kw["bg"] = bg2 # color of the lower part of the Frame
tk.Frame.__init__(self, master, **kw)
# upper color stripe
tk.Frame(self, bg=bg1).place(relx=0, rely=0, relwidth=1, relheight=fraction)
root = tk.Tk()
root.geometry('500x200')
frame = TwoColoredFrame(root, width=100, height=100, bg2='red', bg1="blue", fraction=0.2)
frame.pack_propagate(0)
frame.pack(fill="both", expand=True)
label = tk.Label(frame, text='test', bg='red')
label.pack(side="bottom")
label = tk.Label(frame, text='test', bg='blue', fg="white")
label.pack(side="top")
root.mainloop()
If you would rather have a fixed height stripe, use instead the height
option in place()
:
class TwoColoredFrame(tk.Frame):
def __init__(self, master, bg1, bg2, top_height, **kw):
kw["bg"] = bg2 # color of the lower part of the Frame
tk.Frame.__init__(self, master, **kw)
tk.Frame(self, bg=bg1).place(relx=0, rely=0, relwidth=1, height=top_height) # upper color stripe