我正在学习 tkinter,并注意到在尝试使用具有样式的不同窗口或框架时使用样式的一些事情。
在我提供的代码示例中,如果我更改 frame2 上的样式属性,它们也会显示在 frame1 中。如果我更改执行顺序,则会发生相反的情况。
如何定义特定于每个框架或窗口的样式?
谢谢 丹
from tkinter import *
import tkinter as tk
from tkinter import ttk
def showframe1():
f1_columns = ('#1', '#2')
f1_tree = ttk.Treeview(frame1, columns=f1_columns, show='headings')
f1_style = ttk.Style()
f1_style.theme_use("default")
f1_style.configure("Treeview",
background="white",
foreground="black",
rowheight=25 # Height of each row in tree
)
f1_tree.heading('#1', text='First Name')
f1_tree.heading('#2', text='Last Name')
f1_tree.column("#1", width=150)
f1_tree.column("#2", width=150)
# generate sample data
contacts = []
for n in range(1, 100):
contacts.append((f'first {n}', f'last {n}'))
# adding data to the frame1 tree
for contact in contacts:
f1_tree.insert('', tk.END, values=contact)
f1_tree.grid(row=0, column=0, sticky='nsew')
def showframe2():
f2_columns = ('#1', '#2', '#3')
f2_tree = ttk.Treeview(frame2, columns=f2_columns, show='headings')
f2_style = ttk.Style()
f2_style.theme_use("default")
f2_style.configure("Treeview",
background="lightblue",
foreground="black",
rowheight=25 # Height of each row in tree
)
f2_tree.heading('#1', text='First Name')
f2_tree.heading('#2', text='Last Name')
f2_tree.heading('#3', text='Email')
f2_tree.column("#1", width=150)
f2_tree.column("#2", width=150)
f2_tree.column("#3", width=250)
# generate sample data
contacts = []
for n in range(1, 100):
contacts.append((f'first {n}', f'last {n}', f'email{n}@example.com', f'email{n}@example.com'))
# adding data to the frame2 tree
for contact in contacts:
f2_tree.insert('', tk.END, values=contact)
f2_tree.grid(row=0, column=0, sticky='nsew')
def exit_root(event):
root.destroy()
root = tk.Tk()
root.title('Frame Styles Example')
root.geometry('600x800')
frame1 = Frame(root, bd=5, relief='sunken')
frame1.grid(row=0, column=0, padx=20, pady=10, sticky=N + W)
frame2 = Frame(root, bd=5, relief='sunken')
frame2.grid(row=1, column=0, padx=20, pady=10, sticky=N + W)
showframe1()
showframe2()
root.bind('<Return>', exit_root)
# run the app
root.mainloop()
答案 0 :(得分:0)
我在 https://www.pythontutorial.net/tkinter/ttk-style/
找到了一个很好的教程我需要为附加框架创建一个自定义的 Treeview 样式。我刚刚创建了两个自定义样式。
f1_style.configure("f1.Treeview",....) f2_style.configure("f2.Treeview",....)
然后将样式分配给每个 Treeview 定义。 ttk.Treeview(frame1, columns=f1_columns, show='headings',style='f1.Treeview') ttk.Treeview(frame2, columns=f2_columns, show='headings',style='f2.Treeview')
有了这个,我可以控制每一帧的样式。