我创建了两个选项卡式页面。我想给每个页面稍微不同的颜色,但两个页面总是相同的颜色。如何更改我的代码以提供我正在寻找的内容?在子类框架中使用 ttk.Style() 始终对每个页面使用蓝色而不是单独的颜色。我想更改页面颜色而不是选项卡颜色。
#!/usr/bin/python3.9
import tkinter as tk
from tkinter import ttk
class MainFrame(ttk.Frame):
def __init__(self, container):
super().__init__()
s = ttk.Style()
s.configure('TFrame', background='red')
self.labelA = ttk.Label(self, text = "This is on MainFrame")
self.labelA.grid(column=1, row=2, padx = 30, pady = 30)
self.buttonA = tk.Button(self, text="R 1")
self.buttonA.grid(column=1, row=3)
class SubFrame(ttk.Frame):
def __init__(self, container):
super().__init__()
s = ttk.Style()
s.configure('TFrame', background='blue')
self.labelB = ttk.Label(self, text = "This is on SubFrame")
self.labelB.grid(column=1, row=2, padx = 30, pady = 30)
self.buttonB = tk.Button(self, text="R 1")
self.buttonB.grid(column=1, row=3)
class App(tk.Tk):
def __init__(self):
super().__init__()
s = ttk.Style()
unfocus = "gray"
focus = "#F2C84B"
s.theme_create( "custom", parent="alt", settings={
"TNotebook": {"configure": {"tabmargins": [2, 5, 2, 0] } },
"TNotebook.Tab": {
"configure": {"padding": [5, 1], "background": unfocus },
"map": {"background": [("selected", focus)],
"expand": [("selected", [1, 1, 1, 0])] } } } )
s.theme_use("custom")
self.notebook = ttk.Notebook(self)
self.Frame1 = MainFrame(self.notebook)
self.Frame2 = SubFrame(self.notebook)
self.notebook.add(self.Frame1, text='MainFrame')
self.notebook.add(self.Frame2, text='SubFrame')
self.notebook.pack(expand = 1, fill ="both")
##--------------------------------##
self.geometry('800x500')
#self.resizable(False, False)
self.title("TABS")
if __name__ == '__main__':
app = App()
app.mainloop()
您需要为两个框架使用唯一的样式名称,而不是相同的样式名称
'TFrame'
。 其中一种方法是使用对象实例的 id:
class MainFrame(ttk.Frame):
def __init__(self, container):
style_name = f'{id(self)}.TFrame' # build the style name using object ID
super().__init__(container, style=style_name) # apply the style
s = ttk.Style()
s.configure(style_name, background='red') # configure the style
...
课堂也一样
SubFrame
。