Как установить стиль для виджетов treeview
, чтобы чередующиеся строки имели разные цвета фона, например, строки 1, 3, 5 имели белый фон, а строки 2, 4, 6 - светло-сине-серый фон?
Я также хотел бы установить gridlines
.
Как установить стиль для виджетов treeview
, чтобы чередующиеся строки имели разные цвета фона, например, строки 1, 3, 5 имели белый фон, а строки 2, 4, 6 - светло-сине-серый фон?
Я также хотел бы установить gridlines
.
У меня была такая же проблема несколько месяцев назад.
Из документов tk:
You can assign a list of tags to each item using the "tags"
item configuration option (again, when creating the item or later on).
Tag configuration options can then be specified, which will then
apply to all items having that tag.
По сути, вы применяете один тег ко всем строкам с нечетными номерами, разные теги к каждой из строк с четными номерами, а затем настраиваете теги.
Когда вы создаете элементы внутри древовидной структуры, добавьте к ним теги:
tree.insert('', 'end', text = 'your text', tags = ('oddrow',))
Этот код создает элемент в tree
, а аргумент tags
присваивает элементу тег oddrow.
После того, как вы создали все свои элементы с тегами 'oddrow' и 'evenrow', вы можете раскрасить теги:
tree.tag_configure('oddrow', background='orange')
tree.tag_configure('evenrow', background='purple')
Я понимаю, что это старый вопрос, но только для записи настройка тегов сразу после создания дерева (т.е. когда в него еще не добавлено ни одного элемента) также работает. Когда элементы будут вставлены позже, им будет присвоен цвет фона, соответствующий их тегу «нечетный» или «четный ряд».
это можно запустить без каких-либо дополнительных модулей ... можно испортить код, чтобы заставить его работать с вашим собственным.
from Tkinter import *
import ttk
class Test(Frame):
def __init__(self):
Frame.__init__(self)
self.pack()
self.listbox()
self.buttons()
def listbox(self):
global new_customer_lb
scrollbar = Scrollbar(self, orient="vertical")
new_customer_lb = ttk.Treeview(self, columns=('ID','First Name','Last Name'))
new_customer_lb['show']='headings'
new_customer_lb.heading('#1', text= 'ID')
new_customer_lb.column('#1', width=50, stretch=NO)
new_customer_lb.heading('#2', text= 'First Name')
new_customer_lb.column('#2', width=100, stretch=NO)
new_customer_lb.heading('#3', text= 'Last Name')
new_customer_lb.column('#3', width=100, stretch=NO)
new_customer_lb.configure(yscroll = scrollbar.set, selectmode="browse")
scrollbar.config(command=new_customer_lb.yview)
new_customer_lb.pack()
def buttons(self):
load = Button(self, text='show customers', command=lambda:self.load_working_customers())
test = Button(self, text='test new colors', command=lambda:self.test_colors())
load.pack()
test.pack()
def load_working_customers(self):
new_customer_lb.delete(*new_customer_lb.get_children())
for a in range(0,10):
new_customer_lb.insert('','end', values=(a,'first','last'))
def test_colors(self):
new_customer_lb.delete(*new_customer_lb.get_children())
new_customer_lb.tag_configure("evenrow",background='white',foreground='black')
new_customer_lb.tag_configure("oddrow",background='black',foreground='white')
for a in range(0,10):
if a % 2 == 0:
new_customer_lb.insert('','end', values=(a,'first','last'), tags=('evenrow',))
if a % 2 != 0:
new_customer_lb.insert('','end', values=(a,'first','last'), tags=('oddrow',))
root = Tk()
app = Test()
app.mainloop()
(' ./demo3.py: line 4:
class Test( Рамка):'
- person user216652; 16.11.2019
Это для создания базы данных SQL. затем загружает несколько клиентов из базы данных в список. затем вы можете нажать кнопку «Проверить новые цвета», чтобы показать изменение цвета для нечетных строк. это работает, пока у вас установлен sqlalchemy как модуль.
from Tkinter import *
import ttk
from sqlalchemy import Column, ForeignKey, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
base = declarative_base()
class Customer(base):
__tablename__='Customer_Details'
Id = Column(Integer, primary_key=True)
first_name = Column(String(64))
last_name = Column(String(64))
class DB_connection(object):
def __enter__(variable):
variable.engine = create_engine("sqlite:///example.db")
base.metadata.bind = variable.engine
variable.DBSession = sessionmaker(bind=variable.engine)
variable.Session = variable.DBSession
variable.session = variable.Session()
return variable
def __exit__(variable, exc_type, exc_val, exc_tb):
variable.session.commit()
variable.session.close()
class Test(Frame):
def __init__(self):
Frame.__init__(self)
self.pack()
self.listbox()
self.buttons()
def listbox(self):
global new_customer_lb
scrollbar = Scrollbar(self, orient="vertical")
new_customer_lb = ttk.Treeview(self, columns=('ID','First Name','Last Name'))
new_customer_lb['show']='headings'
new_customer_lb.heading('#1', text= 'ID')
new_customer_lb.column('#1', width=50, stretch=NO)
new_customer_lb.heading('#2', text= 'First Name')
new_customer_lb.column('#2', width=100, stretch=NO)
new_customer_lb.heading('#3', text= 'Last Name')
new_customer_lb.column('#3', width=100, stretch=NO)
new_customer_lb.configure(yscroll = scrollbar.set, selectmode="browse")
scrollbar.config(command=new_customer_lb.yview)
new_customer_lb.pack()
def buttons(self):
db = Button(self, text='make DB', command=lambda:self.create_db())
customer = Button(self, text='create customers', command=lambda:self.create_customers())
load = Button(self, text='show customers', command=lambda:self.load_working_customers())
test = Button(self, text='test new colors', command=lambda:self.test_colors())
db.pack()
customer.pack()
load.pack()
test.pack()
def create_db(self):
print("start create db function")
engine = create_engine('sqlite:///example.db')
base.metadata.create_all(engine)
print("Success create db function")
def create_customers(self):
print ('Start add customer sql')
customer1 = Customer(first_name='first1',last_name='last1')
customer2 = Customer(first_name='first2',last_name='last2')
customer3 = Customer(first_name='first3',last_name='last3')
customer4 = Customer(first_name='first4',last_name='last4')
with DB_connection() as DB:
DB.session.add_all([customer1,customer2,customer3,customer4])
print ('sucess add customer sql')
def load_working_customers(self):
new_customer_lb.delete(*new_customer_lb.get_children())
with DB_connection() as DB:
for a,b,c in DB.session.query(Customer.Id,Customer.first_name,Customer.last_name).order_by(Customer.Id):
new_customer_lb.insert('','end', values=(a,b,c))
def test_colors(self):
new_customer_lb.delete(*new_customer_lb.get_children())
### configure even and odd here
new_customer_lb.tag_configure("evenrow",background='white',foreground='black')
new_customer_lb.tag_configure("oddrow",background='black',foreground='white')
with DB_connection() as DB:
## this loop will take 'a' (Customer.Id) and test if even or odd
for a,b,c in DB.session.query(Customer.Id,Customer.first_name,Customer.last_name).order_by(Customer.Id):
if a % 2 == 0:
new_customer_lb.insert('','end', values=(a,b,c), tags=('evenrow',))
else:
new_customer_lb.insert('','end', values=(a,b,c), tags=('oddrow',))
root = Tk()
app = Test()
app.mainloop()