Changing Row Background Color and Font in TreeView - The Advantages of Learning Python Programming for Beginners: A Comprehensive Guide

Latest

Dive into the world of Python programming with our comprehensive resources

Music

logo

Monday, March 4, 2024

Changing Row Background Color and Font in TreeView

 In this article we are connecting to My Sql database. We show the data in our table in treeview. We change the row background color and font in TreeView.


Output:

 


 










import mysql.connector

 

from tkinter import ttk

 

import tkinter as tk

 

# Creating tkinter root

root = tk.Tk()

root.geometry("850x450")

root.title("treeview..bs") 

 

# Using treeview widget

trv = ttk.Treeview(root, selectmode ='browse',height=18, style="Custom.Treeview")

 

trv.grid(row=1,column=1,padx=20,pady=20)

# number of columns

trv["columns"] = ("1", "2", "3","4")

 

# Defining heading

trv['show'] = 'headings'

 

# wirowh of columns and alignment

trv.column("1",  anchor ='c')

trv.column("2",  anchor ='c')

trv.column("3",  anchor ='c')

trv.column("4",  anchor ='c')

 

 

# Headings 

# respective columns

trv.heading("1", text ="Author Id")

trv.heading("2", text ="Author Name")

trv.heading("3", text ="Book")

trv.heading("4", text ="Price") 

 

s = ttk.Style()

 

# Set the selection background color to green.

s.map("Custom.Treeview", background=[("selected", "red")])

 

style_head=ttk.Style()

style_head.configure("Treeview.Heading",foreground="green", font = ('Arial', 14, 'bold'))

 

# getting data from MySQL world classics table

con1 =  mysql.connector.connect(

    host="localhost",

    database="book",

    user="root",

    password="2344" )

 

cur1 = con1.cursor()

cur1.execute('''SELECT * from worldclassics LIMIT 0,15''')

rows = cur1.fetchall()

 

i=0

for row in rows:

    if row[0]%2==0 :

     trv.insert("", i, text="",

               values =(row[0],row[1],row[2],row[3]),tags=("even",))

    else :

     trv.insert("", i, text="",

               values =(row[0],row[1],row[2],row[3]),tags=("odd",))

    i=i+1

trv.tag_configure("even", background="white", foreground="black", font = ('Arial', 12, 'normal'))

trv.tag_configure("odd", background="greenyellow", foreground="white",font = ('Arial', 12, 'normal'))

 

root.mainloop()

 

Hope to see you in the next article. Happy coding

No comments:

Post a Comment

Featured post

Python Introduction

What is Python? Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built ...