Ask Your Question
4

How to reference variables present in other classes using Python's Tkinter?

asked 2023-07-15 14:54:09 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-15 15:10:02 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-15 14:54:09 +0000

Seen: 12 times

Last updated: Jul 15 '23