Skip to content
Advertisement

$DISPLAY environment problem with Tkinter in VScode

I’m trying to build a simple countdown timer using tkinter, however when I run the code the following message appears:

File "/home/user/Desktop/Beginner Projects/Pythons/countdown timer.py", line 20, in <module>
    root = Tk()
  File "/usr/lib/python3.8/tkinter/__init__.py", line 2261, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

I searched a lot for answers but did not understood most of them. How can I solve this problem and get tkinter to work on VScode? Thanks in advance!

Edit 1:

from tkinter import *
from tkinter import ttk
from tkinter import font
import time
import datetime

global endTime

def quit(*args):
    root.destroy()

def cant_wait():
    timeLeft = endTime - datetime.datetime.now()
    timeLeft = timeLeft - datetime.timedelta(microseconds=timeLeft.microseconds)

    txt.set(timeLeft)

    root.after(1000, cant_wait)

root = Tk()
root.attributes("-fullscreen",False)
root.configure(background="black")
root.bind("x", quit)
root.after(1000, cant_wait)

endTime = datetime.datetime(2020,6,7,8,0,0)

fnt = font.Font(family="Helvetica", size=90, weight="bold")
txt = StringVar()
lbl = ttk.Label(root, textvariable=txt, font=fnt, foreground="white", background="black")
lbl.place(relx = 0.5, rely = 0.5, anchor="center")

root.mainloop()

Advertisement

Answer

I had the same problem on Ubuntu 20.04.1 using PySimpleGUI.

If the problem occurs when trying to run the script by clicking on the green arrow at the top right corner (which corresponds to “Run Python file in Terminal”), one solution is to go into the Terminal and set the DISPLAY variable appropriately.
In my case, the following command did the trick: export DISPLAY=:1 The actual value of the DISPLAY variable depends on the specifics of one’s environment (see for instance [https://unix.stackexchange.com/a/612453])

If instead the problem occurs when pressing F5 (Debug) or Ctrl+F5 (Run without Debugging), then it is necessary to edit the launch.json file. This file can be accessed by via the Run->Open Configurations menu. (This assumes that a configuration for Debugging/Running has already been selected.) We need to instruct VSCode to set the DISPLAY environment variable. To do that, add the line "env": {"DISPLAY": ":1"}, in the appropriate section. In my case, the section was the one starting with "name": "Python: Current File",.

Advertisement