Home > database >  Python how to change color in a spesific cell in ttk treeview
Python how to change color in a spesific cell in ttk treeview

Time:12-03

I have a simple GUI that show on the screen a table with numbers and I want to colored some spesefic cenlls. someone know how can I do it?

import tkinter as tk
from tkinter import *
from tkinter import ttk

def show_table():
    text = ""
    for letter in textDate.get():
        if letter != '/':
            text = text   letter
    print(text)
    number_array = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
    frn = Frame(root)
    frn.place(x=15, y=140)
    tv = ttk.Treeview(frn, columns=(1, 2, 3), show="headings", height="5")
    tv.pack()
    for i in number_array:
        tv.insert('', 'end', values=i)
def save_data():
    date = textDate.get()
    show_table()

root = tk.Tk()
canvas = tk.Canvas(root, height=700, width=700, bg="#A2A2A2")
root.title("test")
canvas.pack()
datelable = tk.Label(text="date", bg="#A2A2A2")
datelable.place(x=15, y=50)
textDate = tk.StringVar()
textEntry = tk.Entry(textvariable=textDate)
textEntry.place(x=15, y=70, width=100, height=15)
finishButton = tk.Button(root, text="send", width="10", height="1", bg="#FFFFFF", command=save_data)
finishButton.place(x=15, y=100)
frame = tk.Frame(root)
root.mainloop()

CodePudding user response:

Python how to change color in a spesific cell in ttk treeview

You cannot change the color of a specific cell in the Treeview widget. Formatting can only be applied to entire rows. Colors can only be applied with tags, and tags can only be applied to an item as a whole, not a part of an item.

CodePudding user response:

By replacing your tree structure with the grid structure, we can color individual cells example is following

import tkinter as tk
from tkinter import *
from tkinter import ttk
import random #for random color selection

def show_table():
    text = ""
    for letter in textDate.get():
        if letter != '/':
            text = text   letter
    print(text)
    number_array = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
    for r in range(len(number_array)):
        for c in range(len(number_array[r])):
            colour = "#x" % random.randint(0, 0xFFFFFF)
            b = Entry(root, text = StringVar(value=number_array[c][r]), bg = colour)
            b.grid(row = r, column = c)

def save_data():
    date = textDate.get()
    show_table()

root = tk.Tk()
canvas = tk.Canvas(root, height=700, width=700, bg="#A2A2A2")
root.title("test")
datelable = tk.Label(text="date", bg="#A2A2A2")
datelable.place(x=15, y=50)
textDate = tk.StringVar()
textEntry = tk.Entry(textvariable=textDate)
textEntry.place(x=15, y=70, width=100, height=15)
finishButton = tk.Button(root, text="send", width="10", height="1", bg="#FFFFFF", command=save_data)
finishButton.place(x=15, y=100)
frame = tk.Frame(root)
root.mainloop()

Output

enter image description here

  • Related