1 | initial version |
You can reference variables present in other classes in Tkinter by creating an instance of the class and accessing the variable using the instance object.
Here's an example:
import tkinter as tk
class MyClass:
def __init__(self):
self.my_variable = "Hello World!"
class GUI(tk.Tk):
def __init__(self, my_class_instance):
super().__init__()
self.my_class_instance = my_class_instance
self.my_label = tk.Label(self, text=self.my_class_instance.my_variable)
self.my_label.pack()
if __name__ == "__main__":
my_class_instance = MyClass()
my_gui = GUI(my_class_instance)
my_gui.mainloop()
In this example, there are two classes: MyClass
and GUI
. MyClass
contains a variable called my_variable
. In the GUI
class, a label widget is created with the value of my_class_instance.my_variable
as its text. In the if __name__ == "__main__"
block, an instance of MyClass
is created and passed to an instance of GUI
as an argument.
By accessing my_class_instance.my_variable
in the GUI
class, we are able to reference the my_variable
present in MyClass
.