How do i pass a class variable to another class? How do i pass a class variable to another class? tkinter tkinter

How do i pass a class variable to another class?


You need to create an instance of the GUI, otherwise you are just referencing to the static class for which code is not defined. You could access it like in this example

class A():    def __init__(self):        self.code = "A"class B():    def __init__(self):        self.code = "B"    def foo(self):        print(self.code + A().code)b = B()b.foo() # Outputs "BA"

Otherwise, to access it like an static variable within the class you need to define it inside the class root level

class A():    code = "C"    def __init__(self):        self.code = "A"class B():    def __init__(self):        self.code = "B"    def foo(self):        print(self.code + A.code)b = B()b.foo() # Outputs "BC"


You should pass the GUI object to the Barcode class, which at the point you create the Barcode instance is self. If you want the Barcode to be inside the GUI frame, you can also directly use it as the Canvas master.
Another thing to notice is that with the way you have it now, self.code will be and remain an empty string, since you only define it right after you've created the Entry widget, at which point it is empty. You should use get on the Entry at the time you want to do something with the contents at that point.

from tkinter import *class GUI(Frame):    def __init__(self, master=None):        Frame.__init__(self, master)        self.code_input = Entry(self)        self.code_input.pack()        self.barcode = Barcode(self, height=250, width=200)        self.barcode.pack()        Button(self, text="Update Barcode", command=self.barcode.draw).pack()class Barcode(Canvas):    def __init__(self, master, height, width):        Canvas.__init__(self, master, height=height, width=width)        self.master = master        self.text = self.create_text((100,100))    def draw(self):        self.itemconfig(self.text, text=self.master.code_input.get())        root = Tk()gui = GUI(root)gui.pack()root.mainloop()

For illustration purposes I create a text object on the canvas and update that with the current value of the Entry on a Button click.