Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter import filedialog error

I'm trying to use tkinter with python3 to open an image, see here a piece of code :

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# --- Python 3.4

from PIL import Image
import Tkinter as tk
from Tkinter import filedialog
import numpy as np
import os
var = 'n'

# Importing the image to correct

while var != 'o' :
    var = raw_input("Press \"o\" to open the image to correct\n")
    var = var.lower()
root = tk.Tk()
root.withdraw()
path = filedialog.askopenfilename()
image_test = Image.open(path)

I have installed python3-tk, and I have the demo window when I write

python3 -m tkinter 

in the terminal. I tried several combinations that did not work :

import tkinter as tk
from tkinter import filedialog

gives

ImportError : No module named tkinter

,

import Tkinter as tk
from Tkinter import filedialog    

gives

ImportError : cannot import name filedialog

I tried with _tinker , FileDialog, file_dialog, but I always have "ImportError : cannot import name filedialog". Any clue ?

like image 601
Rémi Vennereau Avatar asked Dec 04 '22 02:12

Rémi Vennereau


1 Answers

tkinter.filedialog is for Python 3 only.

From your attempts, it seems like you are using Python 2.x , try importing tkFileDialog

Example -

import tkFileDialog as filedialog

Or alternatively, check why it ends up running Python 2.x , instead of Python 3.x .

Tkinter module is only there in python 2 , python 3 has tkinter module, since when importing Tkinter it is successfully getting imported, but when importing tkinter it is failing to import it, we can be sure you end up running Python 2.x and not Python 3.

You can do -

import sys
print(sys.version)
print(sys.executable)

to check the version of python currently running as well as the location of python (or python3) that is running.


Most probably , the issue is occuring because even though you have python3 shebang line in your script, you are most probably running python <script.py> , this always causes python 2 to run.

The aim of adding the python3 shebang line was to be able to run the script directly, without specifying the executable. For that you would need to do -

  1. Give executable permission to the script. (Use chmod u+x <script.py> )
  2. Then run the script as - ./<script.py>
like image 195
Anand S Kumar Avatar answered Dec 19 '22 10:12

Anand S Kumar