I'm trying to make GTK3 and Python3 work under windows to my project.
I have an continuum anaconda setup with a 32-bit python 3.4 and Matplotib via
conda install matplotlib.
I've installed PyGobject(https://sourceforge.net/projects/pygobjectwin32/) and installed GTK+ / Glade via the installer.
The basic exemple from the GTK3 tutorial works well (empty screen)
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
I want now to embed matplotlib in gtk, I got the example from matplotlib (http://matplotlib.org/examples/user_interfaces/embedding_in_gtk3.html)
I saw then that I needed cairocffi because some incompabilities. (PyCairo has no support for a matplotlib function)
I got the windows binaries for cffi from Gohlke
And finnaly did a
pip install cairocffi
And now I just get a python.exe stopped working.
Tried with GTK3agg and GTK3Cairo backends and I have the same result
Looking around I found that maybe the cairo version is outdated for the functions used by matplotlib, but I dont know how to proceed.
Cairocffi works if I try running something else.
More information (from the comment below):
I still got an unhandled win32 error. I managed to open the error and it says:
Unhandled exception at 0x08CF6D58 (libcairo-2.dll) in python.exe:
0xC0000005: Access violation reading location 0x000000A8.
If there is a handler for this exception, the program may be safely continued.
It just crashes...
I've had my share of problems using matplotlib in Python3 + Gtk3. I found this cookbook page with working examples. Try to run the examples in the cookbook - particularly the simplest one:
#!/usr/bin/python3
from gi.repository import Gtk
from matplotlib.figure import Figure
from numpy import arange, pi, random, linspace
import matplotlib.cm as cm
#Possibly this rendering backend is broken currently
#from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo as FigureCanvas
myfirstwindow = Gtk.Window()
myfirstwindow.connect("delete-event", Gtk.main_quit)
myfirstwindow.set_default_size(400, 400)
fig = Figure(figsize=(5,5), dpi=100)
ax = fig.add_subplot(111, projection='polar')
N = 20
theta = linspace(0.0, 2 * pi, N, endpoint=False)
radii = 10 * random.rand(N)
width = pi / 4 * random.rand(N)
bars = ax.bar(theta, radii, width=width, bottom=0.0)
for r, bar in zip(radii, bars):
bar.set_facecolor(cm.jet(r / 10.))
bar.set_alpha(0.5)
ax.plot()
sw = Gtk.ScrolledWindow()
myfirstwindow.add(sw)
canvas = FigureCanvas(fig)
canvas.set_size_request(400,400)
sw.add_with_viewport(canvas)
myfirstwindow.show_all()
Gtk.main()
Also, not that you need a fairly recent version of matplotlib to make things work on Python3.
If you still have problems, please show us the complete error message.
Note: I tested this on Linux (don't have Windows), but, from you description of problems, the issue is (was) a common one.
I have the same issue on Windows since years. The documentation of matplotlib 2.0.0 realease states that Gtk3 backend is not supported on Windows. Recently, I had an issue running the Gtk3Agg backend under Linux (Ubuntu). In both cases, it is always related to Cairo.
Thus, I wrote my own implementation of this backend, you can find it here. import the FigureCanvasGtk3Agg from my module and use it the same way as the official one. It lacks some features, but, if you just want to display a plot, it'll do the job.
You can try the module by running it, it should display a simple colorful graph in a window. I tried it under both Linux and Windows and had no issue.
How does it works:
The trick is to avoid importing Cairo in Python3 as it usually doesn't work (to my experience). It is done by using a GdkPixbuf.
Then Gdk.cairo_set_source_pixbuf does the rest of the job along with calling two methods of the cairo context provided by Gtk in the 'draw-event' callback. Cairo is never imported in the module.
Related
I'm learning python via this course
I'm using Ubuntu 22.04 and Python 3.10.7
I have to use pyautogui like this
import pyautogui
from time import sleep
sleep(1)
pyautogui.write( ' This is written by a computer')
On the video, the tutor switches to the text editor and just starts writing. Nothing happens on mine when I run this code.
So I go to the pyautogui docs and try the alertbox code sample just to see if I can get anything working.
import pyautogui
pyautogui.alert(text='', title='', button='OK')
This gives me the error AssertionError: Tkinter is required for pymsgbox
Similarly, on the video, using matplotlib allows drawing a graph with this code
import matplotlib, matplotlib.pyplot as plt
from time import sleep
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
It tells me Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure. Then when I configure a GUI backend with matplotlib.use('TkAgg') I fall into a loop where python3 reports module not found: _tkinter and simultaneously Ubuntu reports that python3-tk is the latest version so there's nothing to do.
So I've tried
reinstalling python3
installing python3-tk then reinstalling python
pip install tk
setting up venv and doing the above
Google - but I only get the above answers. Which don't work.
So basically everything wants Tkinter but tk is there and python seems to just ignore it. I don't get it
Thank you to everyone that replied. It turns out that the solution was to recompile Python from source, telling it at configure where to look for tkinter as described in these instructions
I have a program that helps visualize some data in 3D by plotting a surface and a cloud of points to see how they relate to the surface. For the visualization I am using mayavi since it was easy to set up and does a better job than matplotlib in 3D. The program works great when I run it in my python environment and makes beautiful visualizations. However, I need to distribute this to a few people who don't have Python and would prefer not to have to install python and all the add-ins on each computer, so I have been using pyinstaller to create standalone .exe files that they can run after I develop a program.
For reference, this is all done on Windows 10, Python 3.6, pyqt 4.11.4, pyface 6.0.0, traits 4.6.0, pyinstaller 3.3.1, mayavi 4.5.0+vtk81. Just about every module I use was installed using pip.
The problem is that I can't seem to get a working exe if I use/import the mayavi module. I have been reading so much github documentation on different hook files and hidden-imports and each time I fix one error another pops up. It all started with scipy but I believe I have those worked out. So I have a few questions that could help me solve the problem:
1) Has anyone successfully created a standalone exe using pyinstaller with a mayavi import (specifically from mayavi import mlab)? What is your secret?!?
This seems similar but I haven't been able to figure it out yet... SO_link
I have used the following links (scipy,h5py,pandas,traits/qt4,ETS_TOOLKIT) to add hidden imports or fix other issues but I am stuck now after setting my ETS_TOOLKIT=qt4. Before setting it, I would get a pyface/traits error RuntimeError: No traitsui.toolkits plugin found for toolkit null, but now it says the same thing for qt4 instead of null. I have qt4 installed so I don't understand that... It is in the import_toolkit function in pyface/base_toolkit.py.
2) Is there a better route to go in terms of 3D visualization / exe creation? I need a 3D program that can accurately render if the points are in front of or behind the surface and be able to rotate/zoom/pan interactively, plus it needs to be intuitive. Mayavi had very simple commands similar to matplotlib but others seem very complicated working around how the UI interacts with everything.
3) How do I interpret all of these error codes I get? They are usually pretty cryptic saying a certain line threw an exception nested in 10 other function calls and it seems very difficult to back out where exactly things went wrong, especially when nothing pops up on Google that seems to be related.
EDIT
While I am still very confused, I have been able to change where the error occurs. Following the traceback, I commented out a line setting the marker color in traitsui/editors/code_editor.py (line 49), at which point the exception then started the next time the Color method was called... but I still get the same RuntimeError. So that doesn't tell me much other than I am still looking for what hidden import I need to include for this thing to work.
Also note that I get the exact same error with both PyInstaller and cx_Freeze, in case that helps...
Edit 2
I have now tried it using anaconda for python 2.7, SAME EXACT ISSUE..... I'm starting to believe the universe doesn't want this to happen. Is there somewhere else I should bring this issue up?? I have posted on the traitsui GitHub but that wasn't very helpful. This seems to be bigger than pyinstaller/cx_freeze since it happens in both....
I dealt with the same problem and finally switched to cx_freeze, which now works fine on linux and windows. The problems you are dealing with arise from statements like in the SE answer, you found, i.e. dynamic import statements, where what is imported is only determined at runtime:
be = 'pyface.ui.%s.' % tk
__import__(be + 'init')
I couldn't fix that in pyinstaller, while in cx_freeze it works, when you explicitely add the required packages in the build file. Here is the package list I used:
"packages": ["pyface.ui.qt4", "tvtk.vtk_module", "tvtk.pyface.ui.wx", "matplotlib.backends.backend_qt4",'pkg_resources._vendor','pkg_resources.extern','pygments.lexers',
'tvtk.pyface.ui.qt4','pyface.qt','pyface.qt.QtGui','pyface.qt.QtCore','numpy','matplotlib','mayavi']
Here is a full build script that works with python3.6, cx_freeze 5.0.2, mayavi 4.5.0+vtk71, traits 4.6.0, pyface 5.1.0 and traitsui 5.1.0.
import os
from cx_Freeze import setup, Executable
import cx_Freeze.hooks
def hack(finder, module):
return
cx_Freeze.hooks.load_matplotlib = hack
import scipy
import matplotlib
scipy_path = os.path.dirname(scipy.__file__) #use this if you are also using scipy in your application
build_exe_options = {"packages": ["pyface.ui.qt4", "tvtk.vtk_module", "tvtk.pyface.ui.wx", "matplotlib.backends.backend_qt4",'pygments.lexers',
'tvtk.pyface.ui.qt4','pyface.qt','pyface.qt.QtGui','pyface.qt.QtCore','numpy','matplotlib','mayavi'],
"include_files": [(str(scipy_path), "scipy"), #for scipy
(matplotlib.get_data_path(), "mpl-data"),],
"includes":['PyQt4.QtCore','PyQt4.QtGui','mayavi','PyQt4'],
'excludes':'Tkinter',
"namespace_packages": ['mayavi']
}
executables = [
Executable('main.py', targetName="main.exe",base = 'Win32GUI',)
]
setup(name='main',
version='1.0',
description='',
options = {"build_exe": build_exe_options},
executables=executables,
)
I import pyface in the following way:
os.environ['ETS_TOOLKIT'] = 'qt4'
import imp
try:
imp.find_module('PySide') # test if PySide if available
except ImportError:
os.environ['QT_API'] = 'pyqt' # signal to pyface that PyQt4 should be used
from pyface.qt import QtGui, QtCore
before importing mayavi
I have met this pretty weird bug when using wxPython today. This simple code works fine:
import wx
app = wx.App()
frame = wx.Frame(None, -1, 'simple.py')
frame.Show()
app.MainLoop()
However, once I add an import statement for matplotlib.pyplot at top:
import matplotlib.pyplot as plt
# then same code as above...
the simple window does not show up anymore (without errors, program halts). Anyone know what the problem is?
Env: macOS High Sierra, Python 3.6.3, wxPython 4.0.0b2, matplotlib 2.1.0
Thanks!
I suspect that it is crashing because you don't have a specific library available for the backend, probably python3-tk
Try:
from matplotlib import use
use('WXAgg')
from matplotlib import pyplot as plt
import wx
app = wx.App()
frame = wx.Frame(None, -1, 'simple.py')
frame.Show()
app.MainLoop()
I had this exact same problem. It only happens on macOS for me. I can run the program fine in Windows, but not Mac. I tested different versions of matplotlib to no avail. I wanted to test against the "classic" version of wxpython but I couldn't get it to download correctly from SourceForge.
I got around it by importing matplotlib inside of my function that did the plotting. This ran without errors but also produced some informative warnings:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/cbook/deprecation.py:107: MatplotlibDeprecationWarning: The WX backend is deprecated. It's untested and will be removed in Matplotlib 3.0. Use the WXAgg backend instead. See Matplotlib usage FAQ for more info on backends. Use WXAgg instead.
warnings.warn(message, mplDeprecation, stacklevel=1)
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_wx.py:319: wxPyDeprecationWarning: Call to deprecated item. Use DrawText instead.
gfx_ctx.DrawRotatedText(s, x - xo, y - yo, rads)
So it looks like the problem is due to some wx deprecation inside of matplotlib.
Rolf of Saxony's answer also worked for me and did not produce the warnings.
I just installed matplotlib in Ubuntu 9.10 using the synaptic package system.
However, when I try the following simple example
>>> from pylab import plot;
>>> plot([1,2,3],[1,2,3])
[<matplotlib.lines.Line2D object at 0x9aa78ec>]
I get no plot window. Any ideas on how to get the plot window to show?
You can type
import pylab
pylab.show()
or better, use ipython -pylab.
Since the use of pylab is not recommended anymore, the solution would nowadays be
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.show()
pylab.show() works but blocks (you need to close the window).
A much more convenient solution is to do pylab.ion() (interactive mode on) when you start: all (the pylab equivalents of) pyplot.* commands display their plot immediately. More information on the interactive mode can be found on the official web site.
I also second using the even more convenient ipython -pylab (--pylab, in newer versions), which allows you to skip the from … import … part (%pylab works, too, in newer IPython versions).
Try this:
import matplotlib
matplotlib.use('TkAgg')
BEFORE import pylab
The code snippet below works on both Eclipse and the Python shell:
import numpy as np
import matplotlib.pyplot as plt
# Come up with x and y
x = np.arange(0, 5, 0.1)
y = np.sin(x)
# Just print x and y for fun
print x
print y
# Plot the x and y and you are supposed to see a sine curve
plt.plot(x, y)
# Without the line below, the figure won't show
plt.show()
Any errors show up? This might an issue of not having set the backend. You can set it from the Python interpreter or from a config file (.matplotlib/matplotlibrc) in you home directory.
To set the backend in code you can do
import matplotlib
matplotlib.use('Agg')
where 'Agg' is the name of the backend. Which backends are present depend on your installation and OS.
http://matplotlib.sourceforge.net/faq/installing_faq.html#backends
http://matplotlib.org/users/customizing.html
Modern IPython uses the "--matplotlib" argument with an optional backend parameter. It defaults to "auto", which is usually good enough on Mac and Windows. I haven't tested it on Ubuntu or any other Linux distribution, but I would expect it to work.
ipython --matplotlib
If you encounter an issue in which pylab.show() freezes the IPython window (this may be Mac OS X specific; not sure), you can cmd-c in the IPython window, switch to the plot window, and it will break out.
Apparently, future calls to pylab.show() will not freeze the IPython window, only the first call. Unfortunately, I've found that the behavior of the plot window / interactions with show() changes every time I reinstall matplotlib, so this solution may not always hold.
If you are starting IPython with the --pylab option, you shouldn't need to call show() or draw(). Try this:
ipython --pylab=inline
--pylab no longer works for Jupyter, but fortunately we can add a tweak in the ipython_config.py file to get both pylab as well as autoreload functionalities.
c.InteractiveShellApp.extensions = ['autoreload', 'pylab']
c.InteractiveShellApp.exec_lines = ['%autoreload 2', '%pylab']
If you are user of Anaconda and Spyder then best solution for you is that :
Tools
-->
Preferences
-->
Ipython console
-->
Graphic Section
Then in the Support for graphics (Matplotlib) section:
select two avaliable options
and in the Graphics Backend:
select Automatic
Another possibility when using easy_install is that you need to require the most recent version of matplotlib.
Try:
import pkg_resources
pkg_resources.require("matplotlib")
before you import matplotlib or any of its modules.
I'm not sure exactly what is going on under the hood, but here is my setup, example code, and problem:
setup:
snow leopard (10.6.8)
Python 2.7.2 (provide by EPD 7.1-2)
iPython 0.11 (provided by EPD 7.1-2)
matplotlib (provided by EPD 7.1-2)
example code:
import numpy as np
import pylab as pl
x=np.random.normal(size=(1000,))
pl.plot(x)
problem:
I can't use the standard Mac OS X shorcuts to access the window generated by the plot command.
For example, I can't Command-Tab to the window. Thus, if the window is behind some other window, I need to mouse over to it! Command-W doesn't close it.
Obviously, this is unacceptable. It seems like perhaps running Lion instead of Leopard might fix this, but i haven't upgraded yet. I feel like the problem has something to do with iPython generating windows that aren't fully Cocoa-aware in some sense, but I really know very little so I'm not particularly confident in this hypothesis.
Thus, any ideas on how to either resolve or get around this issue would be much appreciated.
From the description on the iPython page, it looks like Python uses Qt to generate
UI. This means that the windows it generates are definitely not Cocoa windows and will not act like them.
There's not likely to be an easy solution to this issue.
I experienced the same annoyance with my Anaconda installation of Python 2.7.10 on Mac OS X Yosemite 10.10.5. One solution I found was to change the backend to Mac OS X or Qt4Agg by creating a ~/.matplotlib/matplotlibrc file with the line:
backend: MacOSX
or
backend: Qt4Agg
Now I can easily get to the plot window with Application switcher using Command - Tab and close it with Command - W .