Home > Net >  How to pass a data between different classes defined for tabs in my tkinter GUI?
How to pass a data between different classes defined for tabs in my tkinter GUI?

Time:05-11

I have this code below, and I want to pass variable n in class Data to be used in class tab1 and be used as the textvariable of entry1. however, I get this error:

AttributeError: 'dict' object has no attribute 'n'

or in general, I want to be able to pass variables between tabs.

import tkinter as tk
from tkinter import ttk

class Data:
    def __init__(self):
        self.n = tk.IntVar()

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.minsize(400, 400)
        self.maxsize(400, 400)

        self.my_notebook = ttk.Notebook(self)
        self.my_notebook.pack(fill="both", expand=True)

        self.app_data = {}

        lst = [tab1, tab2, tab3]
        for N, F in enumerate(lst):
            tab = F(self.my_notebook, self.app_data)
            self.my_notebook.add(tab, text="Tab" str(N 1))

        self.data = Data()


class tab1(tk.Frame):
    def __init__(self, parent, data):
        super().__init__(parent)
        self.data = data

        entry1 = tk.Entry(self, textvariable=data.n)
        entry1.pack()


class tab2(tk.Frame):
    def __init__(self, parent, data):
        super().__init__(parent)
        self.data = data

        label2 = tk.Label(self, text="Tab2")
        label2.pack()


class tab3(tk.Frame):
    def __init__(self, parent, data):
        super().__init__(parent)
        self.data = data

        label3 = tk.Label(self, text="Tab3")
        label3.pack()

app = SampleApp()
app.mainloop()

CodePudding user response:

You never create an instance of Data. Instead, you're initializing self.data to an empty dictionary. You need to create an instance of Data and pass that to the tabs.

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        ...
        self.app_data = Data()
        ...
  • Related