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
.
Asked: 2023-07-08 00:36:26 +0000
Seen: 11 times
Last updated: Jul 08 '23