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

Question:

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?

Asked By: Guglie

||

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()
Answered By: Demian Wolf

I would just do this:

import sys
if sys.version_info[0] == 2:
    # Import module
    from Tkinter import *
elif sys.version_info[0] == 3:
    from tkinter import *
else:
    print ("System Config Error", str(sys.version_info))
    raise SystemError

The else block can be omitted if you want.

Answered By: Chandradhar Koneti