Insertion of data into a treeview widget on a notebook Tab - python-3.x

I have included two modules:
A treeview Module
A notebook Module
The treeview module seems to function as required and gets its data from sample data at the top of the Module
The notebook module creates a notebook with 12 tabs - one for each month of the year. each tab will have a treeview widget on it showing the data for that month.
Question # 1:
How do I enter the treeview widget and its data from the treeview module on each tab of the notebook? No Mater what I try I end up with a blank treeview widget as demonstrated in the current module
Question # 2:
Column #3 of the treeview module has both negative and positive numbers in it. How do I make the positive numbers "green" and the Negative numbers "red" while keeping the rest of the widget in its default "black".?
(every time I try to use 'tag' and 'tag-configure' it changes all the characters on the widget.)
'''the following is a tree module
in order to run this module remove "#" from the last line'''
from tkinter import *
import tkinter.ttk as ttk
CategoryList = ['Income','Taxes','Housing']
AccountsList = [['Income','Bobs'],['Income','Roses'],['Income','Als'],
['Taxes','Federal'],['Taxes','State'],['Taxes','Local'],
['Housing','Payment'],['Housing','Utilities'], ['Housing','Repairs']]
CatDiffList = [[5000,4500,500],[100,120,-20],[800,700,100]]
AcctDiffList = [[2000,2000,0],[2000,2000,0],[1000,500,500],
[70,50,20],[50,50,0],[0,40,-40],
[500,400,0],[200,100,100],[100,0,100]]
month = 3 #numbers 1 to 12 = the twelve months
def CreateTreeview():
root = Tk()
#Set up the tree
tree = ttk.Treeview(root,height = 20 )
tree["columns"]=("one","two","three")
tree.column("one", width=100,anchor = 'e' )
tree.column("two", width=100,anchor = 'e')
tree.column("three", width=100,anchor = 'e')
tree.heading('#0',text = "Account Names")
tree.heading("one", text="Budget")
tree.heading("two", text="Actual")
tree.heading("three", text="Difference")
#Bring in Data from TransactionTotals Module & insert it in the tree
for r in range(0,len(CategoryList)):
Name = CategoryList[r]
CatBud = CatDiffList[r][0]
CatAct = CatDiffList[r][1]
CatDif = CatDiffList[r][2]
if CatDif >= 0:
fg = "green" #Change color of column 3
else:
fg = "red"
tree.tag_configure("col3", foreground = fg)
tree.insert("" , r,Name, text=Name, values=(CatBud,CatAct,CatDif),
tag =("col3"))
AcctBud = AcctDiffList[r][0]
AcctAct = AcctDiffList[r][1]
AcctDif = AcctDiffList[r][2]
if AccttDif >= 0:
fg = "green" #Change color of column 3
else:
fg = "red"
tree.tag_configure("col3", foreground = fg)
for y in range(1,len(AccountsList)):
if AccountsList[y][0] == Name:
tree.insert(Name,2,text = AccountsList[y][1],
values = (AcctBud,AcctAct,AcctDif),
tag =("col3"))
tree.pack()
root.mainloop()
#CreateTreeview() #uncomment this line in order to test Tview.py
*******************************************************************************
'''This is the Notebook Module'''
import tkinter.ttk as ttk
import Tview as T2
from tkinter import *
class Notebook(Frame):
def __init__(self, parent, activerelief = RAISED, inactiverelief = RIDGE, xpad = 4, ypad = 6, activefg = 'black', inactivefg = 'black', **kw):
"""Construct a Notebook Widget
Notebook(self, parent, activerelief = RAISED, inactiverelief = RIDGE, xpad = 4, ypad = 6, activefg = 'black', inactivefg = 'black', **kw)
Valid resource names: background, bd, bg, borderwidth, class,
colormap, container, cursor, height, highlightbackground,
highlightcolor, highlightthickness, relief, takefocus, visual, width, activerelief,
inactiverelief, xpad, ypad.
xpad and ypad are values to be used as ipady and ipadx
with the Label widgets that make up the tabs. activefg and inactivefg define what
color the text on the tabs when they are selected, and when they are not"""
#Make various argument available to the rest of the class
self.activefg = activefg
self.inactivefg = inactivefg
self.deletedTabs = []
self.xpad = xpad
self.ypad = ypad
self.activerelief = activerelief
self.inactiverelief = inactiverelief
self.kwargs = kw
self.tabVars = {} #This dictionary holds the label and frame instances of each tab
self.tabs = 0 #Keep track of the number of tabs
self.noteBookFrame = Frame(parent) #Create a frame to hold everything together
self.BFrame = Frame(self.noteBookFrame) #Create a frame to put the "tabs" in
self.noteBook = Frame(self.noteBookFrame, relief = RAISED, bd = 4, **kw) #Create the frame that will parent the frames for each tab
self.noteBook.grid_propagate(0) #self.noteBook has a bad habit of resizing itself, this line prevents that
Frame.__init__(self)
self.noteBookFrame.grid()
self.BFrame.grid(row =0, sticky = W)
self.noteBook.grid(row = 1, column = 0, columnspan = 27)
def change_tab(self, IDNum):
"""Internal Function"""
for i in (a for a in range(0, len(self.tabVars.keys()))):
if not i in self.deletedTabs: #Make sure tab hasen't been deleted
if i != IDNum: #Check to see if the tab is the one that is currently selected
self.tabVars[i][1].grid_remove() #Remove the Frame corresponding to each tab that is not selected
self.tabVars[i][0]['relief'] = self.inactiverelief #Change the relief of all tabs that are not selected to "Groove"
self.tabVars[i][0]['fg'] = self.inactivefg #Set the fg of the tab, showing it is selected, default is black
else: #When on the tab that is currently selected...
self.tabVars[i][1].grid() #Re-grid the frame that corresponds to the tab
self.tabVars[IDNum][0]['relief'] = self.activerelief #Change the relief to "Raised" to show the tab is selected
self.tabVars[i][0]['fg'] = self.activefg #Set the fg of the tab, showing it is not selected, default is black
def add_tab(self, width = 2, **kw):
"""Creates a new tab, and returns it's corresponding frame"""
temp = self.tabs #Temp is used so that the value of self.tabs will not throw off the argument sent by the label's event binding
self.tabVars[self.tabs] = [Label(self.BFrame, relief = RIDGE, **kw)] #Create the tab
self.tabVars[self.tabs][0].bind("<Button-1>", lambda Event:self.change_tab(temp)) #Makes the tab "clickable"
self.tabVars[self.tabs][0].pack(side = LEFT, ipady = self.ypad, ipadx = self.xpad) #Packs the tab as far to the left as possible
self.tabVars[self.tabs].append(Frame(self.noteBook, **self.kwargs)) #Create Frame, and append it to the dictionary of tabs
self.tabVars[self.tabs][1].grid(row = 0, column = 0) #Grid the frame ontop of any other already existing frames
self.change_tab(0) #Set focus to the first tab
self.tabs += 1 #Update the tab count
return self.tabVars[temp][1] #Return a frame to be used as a parent to other widgets
def destroy_tab(self, tab):
"""Delete a tab from the notebook, as well as it's corresponding frame"""
self.iteratedTabs = 0 #Keep track of the number of loops made
for b in self.tabVars.values(): #Iterate through the dictionary of tabs
if b[1] == tab: #Find the NumID of the given tab
b[0].destroy() #Destroy the tab's frame, along with all child widgets
self.tabs -= 1 #Subtract one from the tab count
self.deletedTabs.append(self.iteratedTabs) #Apend the NumID of the given tab to the list of deleted tabs
break #Job is done, exit the loop
self.iteratedTabs += 1 #Add one to the loop count
def focus_on(self, tab):
"""Locate the IDNum of the given tab and use
change_tab to give it focus"""
self.iteratedTabs = 0 #Keep track of the number of loops made
for b in self.tabVars.values(): #Iterate through the dictionary of tabs
if b[1] == tab: #Find the NumID of the given tab
self.change_tab(self.iteratedTabs) #send the tab's NumID to change_tab to set focus, mimicking that of each tab's event bindings
break #Job is done, exit the loop
self.iteratedTabs += 1 #Add one to the loop count
def NotebookView():
root = Tk()
root.title("Yearly Budget Comparison by Month")
note = Notebook(root, width= 400, height =600, activefg = 'red', inactivefg = 'blue') #Create a Note book Instance
note.grid()
tab1 = note.add_tab(text = " January")
tab2 = note.add_tab(text = " February")
tab3 = note.add_tab(text = "March ") #Create a tab with the text "March"
tab4 = note.add_tab(text = " April")
tab5 = note.add_tab(text = "May ")
tab6 = note.add_tab(text = " June")
tab7 = note.add_tab(text = " July")
tab8 = note.add_tab(text = "August ")
tab9 = note.add_tab(text = " September")
tab10 = note.add_tab(text = " October")
tab11 = note.add_tab(text = "November ")
tab12 = note.add_tab(text = " December")
Label(tab1, text = 'January Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 1,pady = 25,padx = 25)
Label(tab2, text = 'Febuary Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab3, text = 'March Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab4, text = 'April Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab5, text = 'May Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab6, text = 'June Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab7, text = 'July Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab8, text = 'August Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab9, text = 'September Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab10, text = 'October Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab11, text = 'November Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab12, text = 'December Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
T2.CreateTreeview=ttk.Treeview(tab1,height = 20).grid(row = 4, column = 1, columnspan = 6)
note.focus_on(tab1)
root.mainloop()
if __name__ == "__main__":
NotebookView()

Without going through all of the code, there is one very clear problem: you are creating two instances of Tk, and calling mainloop twice. Within a single GUI you should only ever create exactly once instance, and call mainloop exactly once.

Related

Tkinter How to make listbox appear over a frame

making an F1 application where users can type in a driver from the current grid [supported via autofill/suggestions], and then API fetches relevant stats
The issue I'm having is that I want the listbox to appear over another frame (called left_frame). However, what this does is that the listbox goes under left_frame , and not over it. Any thoughts of how to make it appear over the frame?
some approaches that I tried:
used .lift(), but .lift() only seems to work when it's relative to objects in the same frame
since I currently use .grid and placed the listbox in the root frame, I initially tried to put it in top_frame, but it then expands the top_frame. Since I have positioned all frames using .place(), I don't think I can use propagate(False) (I tried it , didn't work)
Here's a picture of the issues
Here's my code so far:
#import necessary modules
from tkinter import *
from tkinter import ttk
from PIL import ImageTk, Image
from tkinter import messagebox
import requests
import json
#set up main window components
root = Tk()
root.title("F1 Desktop Application")
root.geometry("500x600")
root.configure(bg="white")
#since same directory, can just use filename
root.iconbitmap("formula1_logo.ico")
#images
#creating canvas for image to go into
#canvas_f1_logo = Canvas(top_frame, width = 5, height = 5)
#canvas.grid(row = 0, column = 1)
#acquire image
#formula1_logo = ImageTk.PhotoImage(Image.open("formula1_logo.png"))
#resize image
#resized_formula1_logo = formula1_logo.resize((3,3), Image.ANTIALIAS)
#new_formula1_logo = ImageTK.PhotoImage(resized_formula1_logo)
#canvas.create_image(5,5, anchor = NW, image = new_formula1_logo)
#functions
#generate 2022 drivers-list [can scale to drivers-list by changing the]
drivers_list_request = requests.get("http://ergast.com/api/f1/2022/drivers.json")
#initialize empty-list
drivers_list = []
drivers_list_object = json.loads(drivers_list_request.content)
for elements in drivers_list_object["MRData"]["DriverTable"]["Drivers"]:
drivers_list.append(elements["givenName"] + " " + elements["familyName"])
#set up frames [main frames, can put frames within frames if needed]
#frame for search bar + magnifying glass
top_frame = LabelFrame(root, padx = 80, pady = 15)
top_frame.place(relx = 0.5, rely = 0.2, anchor = CENTER)
header_label = Label(top_frame, text = "F1 2022 Drivers App", pady = 20, font = ("Arial bold",14))
header_label.grid(row = 0, column = 0, pady = 2 )
search_button = Button(top_frame, text = "search", padx = 2, pady = 2)
search_button.grid(row = 1, column = 1)
# Update the Entry widget with the selected item in list
def check(e):
v= entry.get()
if v=='':
hide_button(menu)
else:
data=[]
for item in drivers_list:
if v.lower() in item.lower():
data.append(item)
update(data)
show_button(menu)
def update(data):
# Clear the Combobox
menu.delete(0, END)
# Add values to the combobox
for value in data:
menu.insert(END,value)
def fillout(event):
try:
entry.delete(0,END)
entry.insert(0,menu.get(menu.curselection()))
#handle a complete deletion of entry-box via cursor double tap
except:
pass
def hide_button(widget):
widget.grid_remove()
def show_button(widget):
widget.grid()
# Create an Entry widget
entry= Entry(top_frame)
entry.grid(row = 1, column = 0)
entry.bind('<KeyRelease>',check)
# Create a Listbox widget to display the list of items
menu= Listbox(root)
menu.grid(row = 2, column = 0, padx = 165, pady = 165)
menu.bind("<<ListboxSelect>>",fillout)
menu.lift()
# Add values to our combobox
hide_button(menu)
left_frame = LabelFrame(root, padx = 30, pady = 30)
left_frame.place(relx = 0.24, rely = 0.5, anchor = CENTER)
bottom_left_frame = LabelFrame(root, padx = 30, pady = 30)
bottom_left_frame.place(relx = 0.24, rely = 0.82, anchor = CENTER)
bottom_right_frame = LabelFrame(root, padx = 30, pady = 30)
bottom_right_frame.place(relx = 0.6, rely = 0.82)
basic_info = Label(left_frame, text = "Basic Info ", font = ("Arial bold",14))
basic_info.grid(row = 0, column = 0, pady = 3)
full_name = Label(left_frame, text = "Full Name : ")
full_name.grid(row = 1, column = 0, pady = 2)
driver_code = Label(left_frame, text = "Driver Code : ")
driver_code.grid(row = 2, column = 0, pady = 2)
nationality = Label(left_frame, text = "Nationality : ")
nationality.grid(row = 3, column = 0, pady = 2)
F1_career = Label(bottom_left_frame, text = "F1 Career ", font = ("Arial bold",14))
F1_career.grid(row = 0, column = 0, pady = 3)
wins = Label(bottom_left_frame, text = "Wins :")
wins.grid(row = 1, column = 0, pady = 2)
poles = Label(bottom_left_frame, text = "Poles :")
poles.grid(row = 2, column = 0, pady = 2)
drivers_championships = Label(bottom_left_frame, text = "Championships :")
drivers_championships.grid(row = 3, column = 0 , pady = 2)
F1_22_stats = Label(bottom_right_frame, text = "F1 22 Stats", font = ("Arial bold",14))
F1_22_stats.grid(row = 0, column = 0, pady = 3)
root.mainloop()
would appreciate the help!

Getting a list variable out of Tkinter window

I am trying to get a list out of Tkinter and I want to add a Y-axis scroll bar to the list box but don't know-how. My code is as follows:
window = Tk()
window.title('Select Multiple Industries')
window.geometry('400x800')
def showindowelected():
industries = []
iname = lb.curselection()
for i in iname:
op = lb.get(i)
industries.append(op)
print (industries)
window.destroy()
#for val in industries:
#print(val)
show = Label(window, text = "Select Multiple Industries", font = ("Times", 14), padx = 10, pady = 10)
show.pack()
lb = Listbox(window, selectmode = "multiple")
lb.pack(padx = 10, pady = 10, expand = YES, fill = "both")
x = ["Brewing","Papermills","Cheese Manufacturing","Steel Mill", "Salt Making"]
for item in range(len(x)):
lb.insert(END, x[item])
lb.itemconfig(item, bg = "whitesmoke" if item % 2 == 0 else "silver")
Button(window, text=" Select > ", command=showindowelected, bg='green', fg='white').pack()
window.mainloop()
Once the window is destroyed, I want the selected variables stored in a list.

Tkinter button displays center under a ttk.text

I have a small notepad that I'm creating for myself.
However, in the section of "Troubleshooting Steps" I have a TTK.text that is takint a wide column. Now I need to add two buttons underneath. "Save" and "Clear"
The "save" button shows center under the TEXT box. (Expected) but when I try to add "Clear" next to "Save" it is displayed in a different column way to the rigth.
Here is the code below.
from tkinter import *
from tkinter import ttk
from tkinter import Text
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("Inbound Mail")
self.pack(fill=BOTH, expand=True)
frame = LabelFrame(self, text = "CUSTOMER INFORMTION ")
frame.grid(row =0, column = 0, pady = 20, padx = 10)
case_number = Label(frame, text = "Case Number ")
case_number.grid(row = 0, column = 0, pady = 3, padx = 3)
self.case_entry = Entry(frame, width = 30)
self.case_entry.grid(row = 0, column = 1, pady = 5)
customer_name = Label(frame, text = "Contact Name ")
customer_name.grid(row =1, column = 0, pady = 3, padx = 3)
self.name_entry = Entry(frame, width = 30)
self.name_entry.grid(row = 1, column = 1)
customer_phone = Label(frame, text = "Phone Number ")
customer_phone.grid(row =2, column = 0, pady = 3, padx = 3)
self.phone_entry = Entry(frame, width = 30)
self.phone_entry.grid(row = 2, column = 1)
customer_email = Label(frame, text = "Email Address ")
customer_email.grid(row =3, column = 0, pady = 3, padx = 3)
self.email_entry = Entry(frame, width = 30)
self.email_entry.grid(row = 3, column = 1)
Label(frame, text = "Product").grid(row = 4, column = 0, pady = 3, padx = 3)
self.product = ttk.Combobox(frame,
values = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8"], width = 27)
self.product.grid(row = 4, column = 1, pady = 3, padx = 3)
self.product.current(0)
#ISSUE DESCRIPTION
frame2 = LabelFrame(self, text = "ISSUE")
frame2.grid(row = 5 , column = 0, pady = 20, padx = 10)
Label(frame2, text = "ISSUE DESCRIPTION").grid(row = 6, column = 0, pady = 3, padx = 3)
self.issue = Entry(frame2, width = 55)
self.issue.grid(row = 7, column = 0, pady = 3, padx = 3)
# TROUBLESHOOTING STEPS
frame3 = LabelFrame(self, text = "TROUBLESHOOTING STEPS")
frame3.grid(row = 8, column = 0)
self.troubles = Text(frame3, height = 15, width = 40, wrap = WORD)
self.troubles.grid(row = 9, column = 0,padx = 10, pady = 10)
#SCROLLBAR FOR TEXT
scroll = Scrollbar(self, command = self.troubles.yview)
scroll.grid(row = 8, column = 1, sticky = "nsew")
self.troubles.config(yscrollcommand = scroll.set)
#SAVE BUTTON AND CLEAR BUTTON.
self.save = Button(frame3, text = "Save")
self.save.grid(row = 10, column = 0)
def main():
root = Tk()
app = Example()
root.geometry("380x650")
# root.resizable(False, False)
root.mainloop()
if __name__ == '__main__':
main()
Make another small Frame to act as a container for the Buttons. You may also want to know that a scrolled Text widget is part of standard tkinter, you don't have to reinvent that. Just add this import:
from tkinter.scrolledtext import ScrolledText
And then:
# TROUBLESHOOTING STEPS
frame3 = LabelFrame(self, text = "TROUBLESHOOTING STEPS")
frame3.grid(row = 8, column = 0)
self.troubles = ScrolledText(frame3, height = 15, width = 40, wrap = WORD)
self.troubles.grid(row = 9, column = 0,padx = 10, pady = 10)
#SAVE BUTTON AND CLEAR BUTTON.
buttonframe = Frame(frame3)
buttonframe.grid(row = 10, column = 0)
self.save = Button(buttonframe, text = "Save")
self.save.pack(side=LEFT)
self.clear = Button(buttonframe, text = "Clear")
self.clear.pack(side=LEFT)

Tkinter Frame and griding

I am designing a front end using Tkinter but the .grid() option doesn't work as expected. I want to divide my screen to two section, LEFT and Right. All the buttons and labels on the left and the rest on the right.
# Initialise frames
self.frame_left = tk.Frame(root, bg = "pink", width = 100, height = 100).grid(row = 0, column = 0, sticky = 'E')
self.frame_right = tk.Frame(root, bg = "red", width = 100, height = 100).grid(row = 0, column = 1, sticky = 'W')
root.grid_columnconfigure(0, weight=0)
root.grid_columnconfigure(1, weight=0)
#labels
self.Name_Label = tk.Label(self.frame_left, text = "Name", font = 12, fg = 'green').grid(row = 1, column = 1)
self.Phone_Label = tk.Label(self.frame_left, text = "Phone Number", font = 12, fg= 'green').grid(row = 1, column =2)
self.University_label = tk.Label(self.frame_left, text = "University", font = 12, fg = 'green').grid(row = 1, column = 3)
#Search boxex
self.Name_box = tk.Entry(self.frame_left, width = 12, borderwidth = 2).grid(row = 2, column = 1)
self.Phone_box = tk.Entry(self.frame_left, width = 12, borderwidth = 2).grid(row = 2, column = 2)
self.Phone_box = tk.Entry(self.frame_left, width = 12, borderwidth = 2).grid(row = 2, column = 3)
# Buttons
self.Search_button = tk.Button(self.frame_left, text='Search', padx = 10, pady = 10, font = 12, fg = 'black').grid(row = 5, column = 1)
#Screen
#self.Screen = tk.Listbox(self.frame_right, width = 20, height = 20, font = 1).grid(row = 0, column = 0)
It seems the labels and buttons are being placed on the root window not the frames that has been defined.
Appreciate your help.
Regards
Khisrow
To divide your screen into 2 parts, you need to use the option columnconfigure:
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)
This creates a grid on the root window with 2 columns in which your self.frame_left and self.frame_right can be placed.
When you store a .grid() item you are not storing the widget:
self.frame_left = tk.Frame(root, bg = "pink", width = 100, height = 100).grid(row = 0, column = 0, sticky = 'E')
Stores the grid object to the variable, not the Frame.
This can be fixed by doing the creation and grid in two lines.
import tkinter as tk
class Test():
def __init__(self):
root = tk.Tk()
#EXAMPLE OF DIFFERENCE
self.frame_left = tk.Frame(root, bg = "pink", width = 100, height = 100).grid(row = 0, column = 0, sticky = 'E')
print(self.frame_left, "DIDN'T STORE THE FRAME")
self.frame_left = tk.Frame(root, bg = "pink", width = 100, height = 100)
self.frame_left.grid(row = 0, column = 0, sticky = 'E')
print(self.frame_left, "STORED THE FRAME")
#EXAMPLE OF DIFFERENCE
# Initialise frames
self.frame_left = tk.Frame(root, bg = "pink", width = 100, height = 100)
self.frame_left.grid(row = 0, column = 0, sticky = 'E')
self.frame_right = tk.Frame(root, bg = "red", width = 100, height = 100)
self.frame_right.grid(row = 0, column = 1, sticky = 'W')
root.grid_columnconfigure(0, weight=0)
root.grid_columnconfigure(1, weight=0)
#labels
self.Name_Label = tk.Label(self.frame_left, text = "Name", font = 12, fg = 'green').grid(row = 1, column = 1)
self.Phone_Label = tk.Label(self.frame_left, text = "Phone Number", font = 12, fg= 'green').grid(row = 1, column =2)
self.University_label = tk.Label(self.frame_left, text = "University", font = 12, fg = 'green').grid(row = 1, column = 3)
#Search boxex
self.Name_box = tk.Entry(self.frame_left, width = 12, borderwidth = 2)
self.Name_box.grid(row = 2, column = 1)
self.Phone_box = tk.Entry(self.frame_left, width = 12, borderwidth = 2)
self.Phone_box.grid(row = 2, column = 2)
self.Phone_box = tk.Entry(self.frame_left, width = 12, borderwidth = 2)
self.Phone_box.grid(row = 2, column = 3)
# Buttons
self.Search_button = tk.Button(self.frame_left, text='Search', padx = 10, pady = 10, font = 12, fg = 'black').grid(row = 5, column = 1)
#Screen
#self.Screen = tk.Listbox(self.frame_right, width = 20, height = 20, font = 1).grid(row = 0, column = 0)
Test()
EDIT: added a listbox with scrollbar
# Screen
scrollbar = tk.Scrollbar(self.frame_right)
scrollbar.grid(row = 0, column = 1, sticky = 'nsw')
self.Screen = tk.Listbox(self.frame_right, width = 20, height = 5, font = 1)
self.Screen.grid(row = 0, column = 0, sticky = 'e')
self.Screen.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=self.Screen.yview)

How to change background color in ttk python

I've made a simple gui age converter app but i want to change its bg color to black.
The problem is in the ttk frame.i don't know how to configure its bg color.
I have tried different methods but that didn't work.
i would be grateful if you guys could help.
here is the code
from tkinter import *
from tkinter import ttk
from PIL import Image
def calculate(*args):
try:
age_sec = int(age.get())
age_sec = age_sec * 12 * 365 * 24 * 60 * 60
age_seconds.set(age_sec)
except:
age_seconds.set('Either the field is empty or \n value is not numeric.')
root = Tk()
root.title("Converter")
root.configure(background="black")
mainframe = ttk.Frame(root, padding = "6 6 12 12")
mainframe.grid(column = 0, row = 0, sticky = (N, W, E, S))
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
#mainframe['borderwidth'] = 2
#mainframe['relief'] = 'groove'
age = StringVar()
age_seconds = StringVar()
ttk.Label(mainframe, foreground = "#4D4E4F", text = "Enter your Age: ").grid(column = 1, row = 1, sticky = E)
age_entry = ttk.Entry(mainframe, width = 30, textvariable = age)
age_entry.grid(column = 2, row = 1, sticky = (W, E))
ttk.Label(mainframe, foreground = "#4D4E4F", text = "your age in seconds is ").grid(column = 1, row = 2, sticky = (E))
ttk.Label(mainframe, textvariable = age_seconds, background = "lightyellow", foreground = "#727475", width = 30).grid(column = 2, row = 2, sticky = W)
#Mouse Events...\\
butt_image = PhotoImage(file = 'images.gif')
ttk.Button(mainframe, compound = TOP, text = "Hit Now", image =butt_image, cursor = "hand2", width= 30, command = calculate).grid(column = 2, row = 4, sticky = W)
l2 = ttk.Label(mainframe,foreground = "#4D4E4F", text = "Mouse Events: ").grid(column = 1, row = 3, sticky = E)
l = ttk.Label(mainframe,background = "lightyellow", foreground = "#727475", text = 'Measurement is starting...', width = 30)
l.grid(column = 2, row = 3, sticky = W)
l.bind('<Enter>', lambda e: l.configure(text = 'Moved Mouse Inside'))
l.bind('<Leave>', lambda e: l.configure(text = 'Mouse Moved Out'))
l.bind('<1>', lambda e: l.configure(text = 'left Mouse clicked'))
l.bind('<Double-1>', lambda e: l.configure(text = 'Double clicked'))
l.bind('<B1-Motion>', lambda e: l.configure(text = 'Left button drag to %d, %d' %(e.x, e.y)))
image = PhotoImage(file = 'waves.gif')
ttk.Label(mainframe, compound = CENTER, text = "Image text", font = ('roman', 9, 'normal'), foreground ='green', image = image).grid(column = 3, row = 1, sticky = (N, E))
#if '__name__' == '__main__':
for child in mainframe.winfo_children(): child.grid_configure(padx = 15, pady = 15)
age_entry.focus()
root.bind('<Return>', calculate)
root.mainloop()
A ttk.Frame does not have a background / bg option. To change it you need to use style.
See ttk.Frame Info
If you don't really need to use a ttk.Frame you can just switch to a tkinter.Frame

Resources