Python treeview цвет фона

Как изменить цвет фона Treeview

Это отлично работает только для клетки, но остальные Treeview остаются белыми.

Я пытался изменить фон окна, рамка тоже, но это не работает.

Итак, как это сделать, я уверен, что вы знаете.

from tkinter import * from tkinter import ttk p=Tk() separator = PanedWindow(p,bd=0,bg="#202322",sashwidth=2) separator.pack(fill=BOTH, expand=1) _frame = Frame(p,bg="#383838") t=ttk.Treeview(_frame) t["columns"]=("first","second") t.column("first",anchor="center" ) t.column("second") t.heading("first",text="first column") t.heading("second",text="second column") t.insert("",0,"dir1",text="directory 1") t.insert("dir1","end","dir 1",text="file 1 1",values=("file 1 A","file 1 B")) id=t.insert("","end","dir2",text="directory 2") t.insert("dir2","end",text="dir 2",values=("file 2 A","file 2 B")) t.insert(id,"end",text="dir 3",values=("val 1 ","val 2")) t.insert("",0,text="first line",values=("first line 1","first line 2")) t.tag_configure("ttk",foreground="black") ysb = ttk.Scrollbar(orient=VERTICAL, command= t.yview) xsb = ttk.Scrollbar(orient=HORIZONTAL, command= t.xview) t['yscroll'] = ysb.set t['xscroll'] = xsb.set ttk.Style().configure("Treeview", background="#383838",foreground="white") p.configure(background='black') t.grid(in_=_frame, row=0, column=0, sticky=NSEW) ysb.grid(in_=_frame, row=0, column=1, sticky=NS) xsb.grid(in_=_frame, row=1, column=0, sticky=EW) _frame.rowconfigure(0, weight=1) _frame.columnconfigure(0, weight=1) separator.add(_frame) w = Text(separator) separator.add(w) p.mainloop() 

Источник

How to change the background color of a Treeview in Tkinter?

The Treeview widget is designed to display the data in a hierarchical structure. It can be used to display the directories, child directories or files in the form of a list. The items present in the Listbox are called Listbox items.

The treeview widget includes many properties and attributes through which we can change or modify its default properties. We can change the background of a treeview widget by defining the ‘background’ property in the constructor.

Example

# Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") # Create a Listbox widget lb = Listbox(win, width=100, height=10, background="purple4", foreground="white", font=('Times 13'),selectbackground="black") lb.pack() # Select the list item and delete the item first # Once the list item is deleted, we can insert a new item in the listbox def edit(): for item in lb.curselection(): lb.delete(item) lb.insert("end", "foo") # Add items in the Listbox lb.insert("end", "item1", "item2", "item3", "item4", "item5") # Add a Button To Edit and Delete the Listbox Item ttk.Button(win, text="Edit", command=edit).pack() win.mainloop()

Output

If we run the above code, it will display a window with a treeview widget having a distinct background color and some items in it.

Читайте также:  Php mysql выгрузка файла

Источник

Managing Style of Treeview

Managing Treeview Style

The last line in above code adds different background color to headings.

row height by using style.

style.configure('Treeview', rowheight=100) 

Managing style using Radio buttons

Using three RadioButtons we will configure the style of Treeview. We used on StringVar() with default value as ‘black’. On click of the radio button we will trigger the function my_upd(col) and we passed colour as parameter.

r1 = tk.Radiobutton(my_w, text='Black', variable=r1_v, value='black', command=lambda:my_upd('black'))
def my_upd(col): if col=='white': style.configure('Treeview',background="white", fieldbackground="white", foreground="black") elif col=='yellow': style.configure('Treeview',background="yellow", fieldbackground="yellow", foreground="black") else: style.configure('Treeview',background="black", fieldbackground="black", foreground="white")
 elif col=='yellow': style.configure('Treeview',background="yellow", fieldbackground="yellow", foreground="black",font=font1)
from tkinter import ttk import tkinter as tk # Creating tkinter my_w my_w = tk.Tk() my_w.geometry("300x250") # width and height of the window my_w.title("www.plus2net.com") trv=ttk.Treeview(my_w,selectmode='browse',show='headings',height=5) trv.grid(row=1,column=1,columnspan=3,padx=30,pady=10) # column identifiers trv["columns"] = ("1", "2") # Defining headings, other option is tree trv['show'] = 'headings tree' # width of columns and alignment trv.column("#0", width = 80, anchor ='c') trv.column("1", width = 10, anchor ='c') trv.column("2", width = 100, anchor ='c') # Headings # respective columns trv.heading("#0", text ="Label",anchor='c') trv.heading("1", text ="id") trv.heading("2", text ="Name",anchor='c') trv.insert("",'end',iid=1,text='First',values=(1,'n1-Alex')) trv.insert("",'end',iid=2,text='second',values=(2,'n2-Ravi')) trv.insert("",'end',iid=3,text='third',values=(3,'n3-Ronn')) style = ttk.Style(my_w) style.theme_use("clam") # set theam to clam style.configure("Treeview", background="black", fieldbackground="black", foreground="white") style.configure('Treeview.Heading', background="PowderBlue") r1_v = tk.StringVar(value='black') # We used string variable here def my_upd(col): if col=='white': style.configure('Treeview',background="white", fieldbackground="white", foreground="black") elif col=='yellow': style.configure('Treeview',background="yellow", fieldbackground="yellow", foreground="black") else: style.configure('Treeview',background="black", fieldbackground="black", foreground="white") r1 = tk.Radiobutton(my_w, text='Black', variable=r1_v, value='black', command=lambda:my_upd('black')) r1.grid(row=2,column=1) r2 = tk.Radiobutton(my_w, text='White', variable=r1_v, value='white', command=lambda:my_upd('white')) r2.grid(row=2,column=2) r3 = tk.Radiobutton(my_w, text='Yellow', variable=r1_v, value='yellow', command=lambda:my_upd('yellow')) r3.grid(row=2,column=3) my_w.mainloop()

Источник

Как изменить цвет фона Treeview

Это работает отлично только для ячейки, но остальная часть Treeview остается белой. Пробовал менять фон окна, рамку тоже, но не получается. Итак, как это сделать, я уверен, что вы знаете. До свидания и заранее спасибо 🙂 Код

from tkinter import * from tkinter import ttk p=Tk() separator = PanedWindow(p,bd=0,bg="#202322",sashwidth=2) separator.pack(fill=BOTH, expand=1) _frame = Frame(p,bg="#383838") t=ttk.Treeview(_frame) t["columns"]=("first","second") t.column("first",anchor="center" ) t.column("second") t.heading("first",text="first column") t.heading("second",text="second column") t.insert("",0,"dir1",text="directory 1") t.insert("dir1","end","dir 1",text="file 1 1",values=("file 1 A","file 1 B")) 2") t.insert("dir2","end",text="dir 2",values=("file 2 A","file 2 B")) t.insert(id,"end",text="dir 3",values=("val 1 ","val 2")) t.insert("",0,text="first line",values=("first line 1","first line 2")) t.tag_configure("ttk",foreground="black") ysb = ttk.Scrollbar(orient=VERTICAL, command= t.yview) xsb = ttk.Scrollbar(orient=HORIZONTAL, command= t.xview) t['yscroll'] = ysb.set t['xscroll'] = xsb.set ttk.Style().configure("Treeview", background="#383838",foreground="white") p.configure(background='black') t.grid(in_=_frame, row=0, column=0, sticky=NSEW) ysb.grid(in_=_frame, row=0, column=1, sticky=NS) xsb.grid(in_=_frame, row=1, column=0, sticky=EW) _frame.rowconfigure(0, weight=1) _frame.columnconfigure(0, weight=1) separator.add(_frame) w = Text(separator) separator.add(w) p.mainloop() 

Вы сказали я пытался изменить фон окна, рамку тоже, но не получается. Покажите нам код, чтобы мы могли вам помочь. — person msw &nbsp schedule 04.08.2013

Да, извините, код стиля :_frame = Frame(p,bg=#383838) p.configure(background=’black’) — person user2650746 &nbsp schedule 04.08.2013

Ответы (2)

Отсутствует параметр fieldbackground , который я нашел случайно в примере. Итак, если вы добавите его в объявление стиля

ttk.Style().configure("Treeview", background="#383838", foreground="white", fieldbackground="red") 

он работает так, как вы хотите. Я использовал red , чтобы сделать изменение очень заметным; очевидно, вы захотите изменить это для большей цветовой гармонии.

Спасибо за ваш ответ, но это не работает: image.noelshack. com/fichiers/2013/32/1375729684-capture.png Как видите, он по-прежнему белый, кроме того, я не вижу разницы с fieldbackground или без него. Странно 🙁 Почему это не работает? Я уточняю, что хочу изменить белый фон между началом древовидного представления и горизонтальной полосой прокрутки. — person user2650746; 05.08.2013

Извините, я не могу вам помочь. Я протестировал его с вашим кодом на своей установке, и он был красным, как красный. Не знаю. — person msw; 06.08.2013

Итак, проблема вызвана python? Кто-нибудь может протестировать этот код и сказать мне, работает ли он? Я использую последнюю версию Python (3.3.2) и работаю в Windows 8. В Windows 7 она тоже не работает. Какая у тебя версия? — person user2650746; 08.08.2013

Я тестировал на чистом Python 3.3.1 в Linux. Я не очень удивлен, что он не работает под Windows, поскольку Tkinter — относительно старый модуль, и, возможно, не так много тестов для малоизвестной функции на вторичной платформе. — person msw; 08.08.2013

Может быть, существует более свежая версия (бета)? Иначе я должен использовать Qt? — person user2650746; 08.08.2013

tk была единственной игрой, когда она была представлена, и ее принципы дизайна вдохновили Qt, GTK и т.д. немного грустно это говорить). Если это для коммерческого использования, имейте в виду, что Tkinter и Qt имеют разные лицензии (BSD и LGPL соответственно); Я не компетентен интерпретировать различия. — person msw; 08.08.2013

Источник

Оцените статью