我有Tkinter主类与笔记本:
class MainApplication(tk.Tk):
def __init__(self):
super().__init__()
self.color_widget = '#1B608E'
self.notebook = ttk.Notebook(self)
self.Page1 = Page1(self.notebook)
self.Page2 = Page2(self.notebook)
self.notebook.add(self.Page1, text='PCE Franchisés')
self.notebook.add(self.Page2, text='PVC Franchisés')
对于笔记本的每一页,我有一个定义为容器的类:
class Page1(ttk.Frame):
def __init__(self, container):
super().__init__(container)
color = MainApplication.color_widget
self.label_INPUT = tk.Label(self, text='Settings', color=color,
)
self.label_INPUT.place(relx=0.03, rely=0.04)
class Page2(ttk.Frame):
def __init__(self, container):
super().__init__(container)
在每个页面中,我想获得在Main类中定义的变量color_widget的值。我试过MainApplication。Color_widegt,但是没有效果
简单的方法是将MainApplication
的实例传递给这些页面,以便这些页面可以通过传递的实例访问实例变量color_widget
:
import tkinter as tk
from tkinter import ttk
class MainApplication(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('800x600')
self.color_widget = '#1B608E'
self.notebook = ttk.Notebook(self)
self.notebook.pack(fill='both', expand=1)
self.Page1 = Page1(self.notebook, self) # pass instance of MainApplication as well
self.Page2 = Page2(self.notebook, self)
self.notebook.add(self.Page1, text='PCE Franchisés')
self.notebook.add(self.Page2, text='PVC Franchisés')
class Page1(ttk.Frame):
# added controller argument
def __init__(self, container, controller):
super().__init__(container)
self.controller = controller
# access MainApplication.color_widget
color = controller.color_widget
self.label_INPUT = tk.Label(self, text='Settings', fg=color)
self.label_INPUT.place(relx=0.03, rely=0.04, anchor='nw')
class Page2(ttk.Frame):
def __init__(self, container, controller):
super().__init__(container)
self.controller = controller
MainApplication().mainloop()