On Fri, 13 Nov 2020 18:40:53 +0100, David KolovratnÃk wrote: > On Fri, Nov 13, 2020 at 05:12:10PM +0000, ChalaoAdda wrote: >> On Fri, 13 Nov 2020 12:04:53 -0500, Richard Damon wrote: >> >> > 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. >> >> Ok. Then how do I access the content of the file from outside the >> function? How can I access return value? >> Thanks. > What about > > def on_printfilename(): > global pic try: > print( f"C: {pic}" ) > except NameError: > print( f"C! pic not set yet" ) > > together with > > file_menu.add_command(label="Print filename", command=on_printfilename) > > Or move your print("B") block behind the mainloop(). > > David
Thanks. That solved my problem. Thanks. -- https://mail.python.org/mailman/listinfo/python-list