This question has been popping up a few times here on SO. I notice that most are dead because there is no minimal working example included so I have included that this time. The other thing that happens a lot, seemingly, is multiple Tk instances, so I did my best to keep it to one.
The problem is that I cannot update the label in the InfoPane using a button in the AssetTree.
I think that I do not really share the variable but make a copy of it. I'd like to make a pointer of self.shared_data
to parent.shared_data
but this is Python.
import random
import tkinter as tk
from tkinter import ttk
class AssetTree(tk.Frame):
def __init__(self, parent):
super().__init__()
self.config(background='white')
self.shared_data = parent.shared_data
self.button = ttk.Button(self, text="Test", command=self.btn)
self.button.pack()
def btn(self):
print('click')
print(self.shared_data)
self.shared_data.set("HELLO")
class InfoPane(tk.Frame):
def __init__(self, parent):
super().__init__()
self.config(height=100, width=100, background='blue')
self.label = ttk.Label(self, text=parent.shared_data.get())
self.label.pack()
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.shared_data = tk.StringVar()
self.assettree = AssetTree(self)
self.infopane = InfoPane(self)
self.assettree.pack(side="left", fill="both", expand=True)
self.infopane.pack(side="right", fill="both", expand=True)
if __name__ == "__main__":
root = tk.Tk()
root.title("Xyrim")
MainApplication(root).pack(side="top", fill="both", expand=True)
root.mainloop()
CodePudding user response:
self.label = ttk.Label(self, text=parent.shared_data.get())
This will set the label's text to the text currently in shared_data
, but it won't update it when the textvariable changes later.
Try using the textvariable
argument instead.
self.label = ttk.Label(self, textvariable=parent.shared_data)
CodePudding user response:
Try this instead
class AssetTree(tk.Frame):
def __init__(self, parent):
super().__init__()
self.config(background='white')
self.parent = parent # get parent
self.button = ttk.Button(self, text="Test", command=self.btn)
self.button.pack()
def btn(self):
print('click')
self.parent.shared_data.set("HELLO") # use 'self.parent' here
Same deal here...
class InfoPane(tk.Frame):
def __init__(self, parent):
super().__init__()
self.parent = parent # get parent
self.config(height=100, width=100, background='blue')
# update the label to use 'shared_data' as its textvariable
# this will update your label's text whenever 'shared_data' changes
self.label = ttk.Label(self, textvariable=self.parent.shared_data)
self.label.pack()