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

Viewed 1555

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

Python3 Version

from tkinter import Tk
from tkinter.filedialog import askopenfilename

root = Tk()
root.withdraw()
filename = askopenfilename(title="Select file")
root.update()
root.destroy()

Python2.7 Version

from Tkinter import Tk
from tkFileDialog import askopenfilename

root = Tk()
root.withdraw()
filename = askopenfilename(title="Select file")
root.update()
root.destroy()

How can I come up with a unified solution?

1 Answers

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:

try:
    # Python 3.x
    from tkinter import Tk
    from tkinter.filedialog import askopenfilename
except ImportError:
    # Python 2.x
    from Tkinter import Tk
    from tkFileDialog import askopenfilename

root = Tk()
root.withdraw()
filename = askopenfilename(title="Select file")
root.update()
root.destroy()
Related