0

I am trying to run this code on Ubuntu 20.04 LTS using the Anaconda latest distribution of Python (3.8.3)

from tkinter import *

root = Tk() # THIS IS THE LINE CAUSING THE ERROR

label = Label(root, text='Hello World!')
label.pack()

root.mainloop()

When I run this, I get the following error:

 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

However, when I run the same lines on the bash terminal on the python shell, everything works perfectly and the window opens with the label without any issues. I am using Visual Studio Code and the Anaconda distribution of python. I would really appreciate it if you could let me know what I am doing wrong. Thanks so much, cheers!

XtremeDevX
  • 1,482
  • 2
  • 13
  • 38

2 Answers2

1

DISPLAY Environment Variable

This variable is used to indicate to graphical applications where to display the actual graphical user interface, the value consists of 3 parts: A host-name followed by a colon (:), a display number followed by a dot (.) and a screen number.

@my machine, echo $DISPLAY => :0 (have also used :0.0)

As per the Ubuntu wiki, environment vars can be set, e.g.:
export DISPLAY=:0.0
at the shell (before other commands),
or in configuration files (like ~/.profile) (to persist).

My guess is that it's an IDE configuration issue.
First, try to set DISPLAY as described above,
in a shell; then run your IDE from that shell.
If that fixes it, add the export in ~/.profile,
for a permanent solution (will require log-out / log-in).

There may also be IDE-specific ways to config/set env-vars.
Can't test myself; you can search e.g.:
is-there-any-way-to-set-environment-variables-in-visual-studio-code
and VisualStudioCode's own site/docs:
docs/python/environments

Related: what-is-the-display-environment-variable
Other similar issues e.g. here and here

0

you can use it with python instead of shell

import os

if os.environ.get('DISPLAY','') == '':
    print('no display found. Using :0.0')
    os.environ.__setitem__('DISPLAY', ':0.0')

Note based the display is :0 to make sure on GUI run on GUI terminal echo $DISPLAY
Similar Questions
tkinter.TclError: no display name and no $DISPLAY environment variable python https://raspberrypi.stackexchange.com/questions/38294/error-when-attempting-to-create-python-gui-using-tkinter-no-display-name-and-n

Zaman
  • 811
  • 7
  • 15