I made a script with two interactions with user. To do this, i use Tkinter. The first interaction is to get date while the second one is to get filename selection. The script runs fine for the first time execution. However, it seems that it hangs for the second run or more. I always need to restart Consoles in Spyder to make it runs again.
When i run in debug mode for the second run, it seems that the script stuck in root.mainloop() of the first user interaction. The script also runs fine for multiple executions if the second interaction to ask file selection is not there. Please find the code i wrote below. What could be the problem for this code?
def GetDate():
def my_function():
global date
date = my_entry.get()
root.destroy()
return()
root = tk.Tk()
my_label = tk.Label(root, text = "Enter date (YYYYMMDD): ")
my_label.grid(row = 0, column = 0)
my_entry = tk.Entry(root)
my_entry.grid(row = 0, column = 1)
my_button = tk.Button(root, text = "Submit", command = my_function)
my_button.grid(row = 1, column = 1)
root.mainloop()
GetDate()
tk.Tk().withdraw()
filenameDat = askopenfilename(initialdir = dayfold, filetypes=[("Dat", "*.xls*")], title = 'Open Input File')
'dayfold' is variable where the default initial directory will be prompted
CodePudding user response:
It is because the previous instance of Tk()
created by the line tk.Tk().withdraw()
still exists in the second run, so root.mainloop()
inside GetDate()
will not return as there is still other instance of Tk()
.
You need to destroy the instance of Tk()
as below:
...
root = tk.Tk()
root.withdraw()
filenameDat = askopenfilename(initialdir = dayfold, filetypes=[("Dat", "*.xls*")], title = 'Open Input File')
root.destroy() # destroy the root window