Home > database >  With Tkinter in Python, is it possible to format a column in a treeview control as currency with red
With Tkinter in Python, is it possible to format a column in a treeview control as currency with red

Time:01-08

What I really want is for the imported money numbers to be formatted with red font for negative, black for positive, with a dollar sign ($) in front.

I can't seem to find anyone else struggling with this. I have a hard time imagining I'm the only one who might want to display money columns in a tkinter treeview.

Anyway, if you have any suggestions for how I can accomplish this, please let me know.

ChatGPT suggested the following:

import tkinter as tk
import tkinter.ttk as ttk

# Create the main window
root = tk.Tk()

# Create a ttk.Treeview widget
tree = ttk.Treeview(root)
tree.pack()

# Insert some rows into the Treeview widget
tree.insert('', 'end', text='Row 1', values=('10.50', '20.00'))
tree.insert('', 'end', text='Row 2', values=('15.00', '25.00'))
tree.insert('', 'end', text='Row 3', values=('20.00', '30.00'))

# Define a formatting function for the cells
def format_currency(value):
    return '${:,.2f}'.format(float(value))

# Set the formatting function for the cells in the second column
tree.tag_configure('currency', foreground='red',
                   font='Arial 14 bold', format=format_currency)
tree.tag_bind('currency', '<1>', lambda e: e.widget.item(e.item, tags=[]))

# Set the tag for the cells in the second column
for item in tree.get_children():
    tree.item(item, tags=['currency'], text=1)

# Run the main loop
root.mainloop()

but there is no such parameter "format" for tree.tag_configure. The error I get when trying to run this code is: "TclError: unknown option "-format""

I was expecting the values in the second column to be formatted according to the format_currency function. I don't think ChatGPT quite got the format I want for the currency values, but at this point, it seems the priority is getting any format to be applied.

CodePudding user response:

With Tkinter in Python, is it possible to format a column in a treeview control as currency with red font for negative values?

No, it is not possible. You can't control the color of individual cells in a treeview widget.

  • Related