Guglie
Guglie

Reputation: 2441

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

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?

Upvotes: 2

Views: 2661

Answers (2)

Chandradhar Koneti
Chandradhar Koneti

Reputation: 247

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.

Upvotes: 1

demian-wolf
demian-wolf

Reputation: 1858

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()

Upvotes: 3

Related Questions