Home > OS >  Get variable from parent using container class
Get variable from parent using container class

Time:06-29

I have Tkinter main class with a notebook:

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')

For each page of the notebook, I have a class defined as container:

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)

In each Page I want get the value of the variale color_widget defined in Main class. I tried MainApplication.color_widegt but it didn't work.

CodePudding user response:

The simple way is to pass the instance of MainApplication to those pages, so that those pages can access the instance variable color_widget via the passed instance:

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()

CodePudding user response:

self.color = self.master.master.color_widget
  • Related