Skip to content
Advertisement

How to open a Tkinter askopenfilename dialog compatible with Python 2 and Python 3

I’m trying to write a simple Python Tkinter file chooser that is compatible both with Python2.7 and Python3.x

Python3 Version

JavaScript

Python2.7 Version

JavaScript

How can I come up with a unified solution?

Advertisement

Answer

Try to import Tk and askopenfilename as for Python 3.x at first. If you get an ImportError (there is no tkinter and tkinter.filedialog modules), try to import them as for Python 2.x. (from Tkinter and tkFileDialog modules).
Here is the example:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement