When dealing with Python and Tkinter, you will come across an error “_tkinter.TclError: no display name and no $DISPLAY environment variable”. Tkinter is a Python-based library that helps create GUI for the code that you are writing. In other words, it helps to implement our code into a visually appealing and user-friendly interface.
In our today’s guide, we will guide you about the reasons that invoke the error and their possible solutions.
How can the “_tkinter.TclError” problem be solved?
This error is mostly encountered on Ubuntu systems. The error is invoked, when you work on a remote system and try to make use of the Tkinter library. There are many various causes that can prompt this issue. This section demonstrates those reasons and their possible solutions.
Reason 1: The “matplotlib” preference is set to Xwindows
The matplotlib is a python library that helps with animations/visualizations in the GUI of a program. The presence of this library can also invoke the error. By default, the “matplotlib” uses the XWindows backend system which can invoke the error.
Solution: Change the default setting for “matplotlib”
To fix this issue, we need to utilize the non-interactive backend instead of Xwindows. The code below will change the default settings for matplotlib:
$ echo "backend: Agg" > ~/.config/matplotlib/matplotlibrc
Add this line into your script and the default Xwindows backend will be changed.
Reason 2: The “matplotlib” is not imported
Aside from the reason above, a familiar reason for this problem is that the library matplotlib is not imported correctly into the Python script. Due to this, the library is not detected when the code is run.
Solution: Import the library
The simplest way to fix the issue is to make sure that the matplotlib library is correctly imported into the Python script. The following syntax needs to be added before the pyplot is imported:
import matplotlib matplotlib.use('Agg')
Reason 3: No Display variable
As the error statement suggests, there is an environment variable missing inside the script. If the variable is not missing, it does not have an assigned value attached to it.
Solution: Add a display variable
The very obvious solution to this issue is to add the environment variable and assign it a value alongside it. The code below shows how this variable can be added to the script:
$ export DISPLAY=:0.0
This snippet shows the addition of the display variable.
Adding the display variable with the assigned value should fix this issue easily.
To fix the “_tkinter.TclError: no display name and no $DISPLAY environment variable” error you need to change the default backend settings for the matplotlib library. Other methods of fixing the problem are to add a display environment variable. This article is equipped with all the necessary knowledge that is needed to solve the no display name and environment variable error.
TUTORIALS ON LINUX, PROGRAMMING & TECHNOLOGY