How To Save "self" Return Value To A Variable From Class B: To Class A When Class B Gets That Value Returned By Class C
first of all im pretty new to OOP coding, so sorry for asking stupid questions. I have a problem returning a value from Class AskDir that gets its value from Class SelectDir to Cla
Solution 1:
Does this work for you?
I can see no need to have SelectDir as a class given that its purpose is just to call the askdirectory
method and return the selected folder path so I've change it to a function.
With this example, pressing the "Select directory" button will open the directory dialog and then place the selected directory text in to an Entry widget.
If the MainWindow
class wishes to do anything with the path once it has been set then you just need to call the get_dir
method of AskDir
e.g. print(askDir.get_dir()
import tkinter as tk
from tkinter import filedialog
defdoStuffFunction(value):
print(value)
classMainWindow(tk.Frame):
def__init__(self,master=None,**kw):
tk.Frame.__init__(self,master=master,**kw)
self.askDir = AskDir(self)
self.askDir.grid()
doStuffButton = tk.Button(self, text="Do Stuff", command=self.doStuff)
doStuffButton.grid()
defdoStuff(self):
doStuffFunction(self.askDir.get_dir())
classAskDir(tk.Frame):
def__init__(self, master, **kw):
tk.Frame.__init__(self, master=master,**kw)
button = tk.Button(self, text="Select directory",
command=self.select_dir)
button.grid(row=0,column=1)
self.act_dir = tk.StringVar()
self.act_dir.set("/home/")
self.pathBox = tk.Entry(self, textvariable=self.act_dir,width=50)
self.pathBox.grid(row=0,column=0)
defselect_dir(self):
selectdir = SelectDir("Select directory", "/home/user/folder/")
self.act_dir.set(selectdir)
defget_dir(self):
return self.act_dir.get()
defSelectDir(title,initial):
result = filedialog.askdirectory(initialdir=initial,title=title)
return result
if __name__ == '__main__':
root = tk.Tk()
MainWindow(root).grid()
root.mainloop()
You can now use the AskDir
class as many times as you want in the MainWindow (perhaps to select Source and Destination paths). This has been added to my example with the doStuff
method inside MainWindow
.
Post a Comment for "How To Save "self" Return Value To A Variable From Class B: To Class A When Class B Gets That Value Returned By Class C"