-1

This is an example code:

from tkinter import * 

root = Tk() 
my_label = Label(root, text="Hello World")
my_laber.pack()
root.mainloop()

that doesn't work on my terminal: Ubuntu (18.04):

 Traceback (most recent call last):
      File "hello_world.py", line 3, in <module>
        root = Tk() #Setting the windown, to do first.
      File "/usr/lib/python3.6/tkinter/__init__.py", line 2023, in __init__
        self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
    _tkinter.TclError: no display name and no $DISPLAY environment variable

How can I fix it?

Python version

Python 3.6.9 (default, Nov  7 2019, 10:44:02)
[GCC 8.3.0] on linux
  • 2
    Does this answer your question? [\_tkinter.TclError: no display name and no $DISPLAY environment variable](https://stackoverflow.com/questions/37604289/tkinter-tclerror-no-display-name-and-no-display-environment-variable); https://stackoverflow.com/questions/56273204/tkinter-tclerror-no-display-name-and-no-display-environment-variable-python; https://stackoverflow.com/questions/48254530/tkinter-in-ubuntu-inside-windows-10-error-no-display-name-and-no-display-env – Tomerikoo Mar 05 '20 at 11:59

1 Answers1

0

You can solve the issue by checking if there's a value assigned to environment variable DISPLAY and assigning it if returned string is empty:

from tkinter import *
import os

if os.environ.get('DISPLAY', '') == '':
    print('no display found. Using :0')
    os.environ['DISPLAY'] = ':0'

root = Tk()
my_label = Label(root, text="Hello World")
my_label.pack() # watch out here - you have a typo in your code
root.mainloop()

You can find more information about the numbers being assigned to DISPLAY in this ask ubuntu answer.

machnic
  • 2,304
  • 2
  • 17
  • 21