Ask Your Question
3

How can I access variables from other classes in Tkinter using Python?

asked 2023-07-08 00:36:26 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-07-08 00:46:01 +0000

devzero gravatar image

You can access variables from other classes in Tkinter by passing them as arguments to the functions or methods of the class that needs them. For example:

import tkinter as tk

class App1(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master

        # create a variable in App1
        self.variable1 = tk.StringVar(value="Hello")

        # create an instance of App2 and pass variable1
        self.app2 = App2(master=self.master, variable=self.variable1)

        # create a button to change variable1
        self.button = tk.Button(self.master, text="Change Variable 1", command=self.change_variable)
        self.button.pack()

    def change_variable(self):
        self.variable1.set("Goodbye")

class App2(tk.Frame):
    def __init__(self, master=None, variable=None):
        super().__init__(master)
        self.master = master
        self.variable = variable

        # create a label to display variable1
        self.label = tk.Label(self.master, textvariable=self.variable)
        self.label.pack()

root = tk.Tk()
app = App1(master=root)
app.mainloop()

In this example, App1 creates variable1 and passes it to App2 when it creates an instance of it. By passing variable1 to App2 as an argument, App2 can access and display the value of variable1 in a label.

When the button in App1 is clicked, it changes the value of variable1 to "Goodbye". Because App2 is displaying the value of variable1 in a label with textvariable=self.variable, the label automatically updates to display the new value of variable1.

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-08 00:36:26 +0000

Seen: 11 times

Last updated: Jul 08 '23