On 11/13/20 11:42 AM, ChalaoAdda wrote: > On Fri, 13 Nov 2020 16:04:03 +0000, Stefan Ram wrote: > >> ChalaoAdda <chalao.a...@gmail.com> writes: >>> On Fri, 13 Nov 2020 15:41:20 +0000, Stefan Ram wrote: >>>> ChalaoAdda <chalao.a...@gmail.com> writes: >>>>> I am trying to read a file from askopenfilename outside the function. >>>>> I am getting blank file name. What am I doing wrong? Here is my code. >>>> It is possible that you try to read from "pic" before "on_openfile" >>>> ever was executed. >>> I didn't get you. I click on the menu item "Open" and then from the >>> filedialog select a file. And then outside that function I am trying to >>> read and print the file. >> I have added two additional statements to your source code: >> print( "A" ) and print( "B" ). >> >> If you now execute this new source code, you might observe that "B" is >> being printed before "A" is being printed. >> >> from tkinter import * >> from tkinter import filedialog >> >> def on_openfile(): >> print( "A" ) >> global pic pic = filedialog.askopenfilename() >> >> >> root = Tk() >> >> menubar = Menu(root) >> root.config(menu=menubar) >> file_menu = Menu(menubar) file_menu.add_command(label="Open", >> command=on_openfile) file_menu.add_command(label="Exit", >> command=root.destroy) >> menubar.add_cascade(label="File", menu=file_menu) >> >> >> print( "B" ) >> f = open(pic) >> print(f.read()) >> >> root.mainloop() > Ok. I got the point. So what do I need to do access the variable? How do > I return a value from that function? > > Thanks.
The problem is that you are accessing the variable BEFORE the box has been put up and the user clicking on it. That doesn't happen until the mainloop() call. You need to delay the opening and reading of the file till the filedialog has been used and returned. Perhaps on_openfile could open and read the file. -- Richard Damon -- https://mail.python.org/mailman/listinfo/python-list