My button
button = ttk.Button(frame_file, text='Open file', command=lambda *args: openfile())
button.grid(row=1, column=1)
calls a function openfile()
def openfile():
return fd.askopenfile()
how do I get the path of the opened file in the main (where the button is defined?)
CodePudding user response:
Why do you want it? Tkinter, like most gui libraries, is event-oriented. The idea is that events should be handled by code called ('fired') when they happen. If you need to pass state from the button to something else, there are a few options:
global variable:
fn = None
...
def openfile(*args):
global fn
fn = ...
slightly better: global object:
state = {}
...
def openfile(*args):
state["fn"] = ...
But at this point you have state flying around. If you really need to do this, you should probably think about encapsulating that state in a class, which would handle the action:
class FileDoStuff:
def __init__(self, row, column, frame_file):
self.button = ttk.Button(frame_file, "Open File", self.on_click)
self.button.grid(row, column)
self.fn = None
def on_click(self, *args):
self.fn = ...
and as noted in the other answer your lambda isn't doing anything except gobbling arguments, which can be done in the fn itself (as I have here).
CodePudding user response:
You will have to store it in a variable accessible to both functions such as a global variable or an instance attribute. If you want to access it in the same function that creates the button, be aware that the function will likely have returned before the user has had a chance to see and click on the button.
Also, by the way, you can reduce the complexity of your button command by removing lambda
:
button = ttk.Button(frame_file, text='Open file', command=openfile)