Tkinter freezing Python and Windows Explorer

863 Views Asked by At

I often used Tkinter to prompt users and get the path to a file. However, I am facing a recurrent issue, when the filedialog appears it often crashes Windows.

The screen freezes, everything is blocked and when I enter the Task Manager I can see "Python is not responding", when I try to kill Python, then the Task Manager itself freezes and my only option then is to reboot my laptop.

Here is a sample code of what I usually do :

import tkinter as tk
from tkinter import filedialog
import os

window=tk.Tk()
currdir=os.getcwd()

path=filedialog.askopenfilename(parent=window, initialdir=currdir, title="Select file")

Am I doing something wrong ? Any tips ? Is it just bad performances from this library ?

3

There are 3 best solutions below

0
On BEST ANSWER

Have you tried using a try/ except block so that you'll exit the loop even if you hit an exception?

import tkinter as tk
from tkinter import filedialog
import os

try:
    window=tk.Tk()
    currdir=os.getcwd()

    path=filedialog.askopenfilename(parent=window, initialdir=currdir, title="Select file")
finally:
    window.mainloop()
0
On

Include

window.mainloop()

At the end of your GUI file and see if it works that way

0
On

Thanks @User9701 and @Linden

Following your advice, I updated my code as per the below :

import tkinter as tk
from tkinter import filedialog
import os

try:
    window=tk.Tk()
    currdir=sos.getcwd()
    path=filedalog.asopenfilename(parent=window,initialdir=currdir, title="Select file")

finally:
    window.destroy()