python - 如何使用 tkinter 定义不同的样式/主题
问题描述
我正在学习 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()
解决方案
我在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')
有了这个,我可以控制每一帧的风格。
推荐阅读
- c# - 数据包格式不正确,使用 WSDL 文件从 C# 调用 SAP 服务
- javascript - 通过 id 动态删除输入
- alexa - 如何从alexa技能中获取用户输入
- python - 循环多个 SQL 查询并将输出保存为单个数据帧
- python - 解包 n 级嵌套列表
- html - 角度 p 元素作为模板内的根元素
- c# - 如何在通用 Windows 平台 (UWP) 的任何控制下呈现 MS-Word 文件,而不是在单独的文件中打开它?
- java - BASIC,在调用 %d%n 后不能再输出任何字符串?
- tensorflow - @tf.custom_gradient 处于急切模式,参数复杂
- python - 在 tmux 窗口中生成输出时无法滚动 Ipython(不是笔记本!)