Im running into this problem with tkinter, where I want to set the source of a document so my code can work with the file in python using a search button and askopenfilename.
here is the snipped of my code.
...
from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("Alpha")
root.iconbitmap('images\alpha.ico')
def search():
global location
root.filename = filedialog.askopenfilename(initialdir="/", title="Select A File",
filetypes=(("txt files", "*.txt"), ("All Files", "*.*")))
location = root.filename
open_button = Button(root, text="Open File", command=search).pack()
input_txt = open(location, "r", encoding="utf8")
...
root.mainloop()
Problem: As I am running the program, the window opens for a brief moment and I am instantly getting the error that location
in the input_txt
variable is not defined, which I totally understand. I guess my python code is not waiting for me to press the button in the program window and search for my file so location
can be defined. How can I make python wait for open()
to return a value for location
before trying to define input_txt
?
I have tried with
import time
...
location = ''
open_button = Button(root, text="Open File", command=open).pack()
while not location:
time.sleep(0.1)
this however causes the program to freeze and I know sleep is not the not the best option here. Any suggestions?