In tkinter with python, how do I pass the value of a variable from one class (window) to another class (window), when that class reuses the same frame (it's not a toplevel window).
For example I have a login window, which I would like to pass the username and account privilege type (Admin, Operator...) to the main window. How to do this?
See the example files:
main.py
#!/usr/bin/env python3
from tkinter import *
from frm_login import Wlogin
class Mainframe(Tk):
def __init__(self):
Tk.__init__(self)
self.frame = Wlogin(self)
self.frame.pack()
def change(self, frame):
self.frame.pack_forget() # delete currrent frame
self.frame = frame(self)
self.frame.pack() # make new frame
if __name__== '__main__':
app = Mainframe()
app.mainloop()
frm_login.py
from tkinter import *
from frm_default import Wmain
class Func(Frame):
def go_to_main(self, event=None):
self.myvar = self.entry_var.get() #pass the value of this variable to the class: Wmain
self.master.change(Wmain)
class Wlogin(Func):
def __init__(self, master=None, **kwargs):
Frame.__init__(self, master, **kwargs)
master.title('First Window')
master.geometry('300x200')
self.myvar = StringVar()
self.entry_var = Entry(self, textvariable=self.myvar)
self.entry_var.pack()
self.entry_var.focus()
self.btn = Button(self, text='Go', command=self.go_to_main)
self.btn.pack()
frm_default.py
from tkinter import *
class Wmain(Frame):
def __init__(self, master=None, **kwargs):
Frame.__init__(self, master, **kwargs)
master.title('Second Window')
master.geometry('600x400')
self.label_var = Label(self, bg='red', fg='#ff0', text='How to show var of first window here?')
self.label_var.pack()
CodePudding user response:
One of the way is to pass the required value via kwargs
:
main.py
class Mainframe(Tk):
def __init__(self):
Tk.__init__(self)
self.frame = Wlogin(self)
self.frame.pack()
# added **kwargs
def change(self, frame, **kwargs):
self.frame.pack_forget() # delete currrent frame
self.frame = frame(self, **kwargs) ### pass **kwargs
self.frame.pack() # make new frame
frm_login.py
class Func(Frame):
def go_to_main(self, event=None):
self.myvar = self.entry_var.get() #pass the value of this variable to the class: Wmain
self.master.change(Wmain, data=self.myvar) # pass value via keyword 'data'
...
frm_default.py
class Wmain(Frame):
def __init__(self, master=None, **kwargs):
# get the value of keyword argument 'data'
data = kwargs.pop('data', None)
Frame.__init__(self, master, **kwargs)
master.title('Second Window')
master.geometry('600x400')
self.label_var = Label(self, bg='red', fg='#ff0', text=data) # use 'data'
self.label_var.pack()