tkinter
in a Headless EnvironmentI am trying to test if tkinter
is installed and working by running the following command in the terminal:
python3 -m tkinter
I've installed tkinter
dependencies (e.g., sudo apt-get install python3-tk
) and verified your Python version is 3.1
Error Message When I run the command, I get the following error:
File "<frozen runpy>", line 198, in _run_module_as_main
File "<frozen runpy>", line 88, in _run_code
File "/home/codespace/.python/current/lib/python3.12/tkinter/__main__.py", line 7, in <module>
main()
File "/home/codespace/.python/current/lib/python3.12/tkinter/__init__.py", line 4633, in _test
root = Tk()
^^^^
File "/home/codespace/.python/current/lib/python3.12/tkinter/__init__.py", line 2340, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
_tkinter.TclError: no display name and no $DISPLAY environment variable
Headless environment doesn't run X11
(or Wayland
) so it can't display GUI programs - and this makes your problem.
You may try to use Xvfb to create virtual X11
.
apt install xvfb
and later
xvfb-run python3 -m tkinter
Because it doesn't display tkinter's window so it can't be closed with clicking button [X]
on window but it can be killed with Ctrl+C
. Or you may kill it using other console. It is simpler with pkill
instead of kill
pkill xvfb
Tested on Linux Mint 22 based on Ubuntu 22.04
Useful for test
xvfb-run python3 -c "import os;print(os.environ.get('DISPLAY'))"
Result: :99
Python has modules to work with Xvfb - like xvfbwrapper, pytest-xvfb
This is good for automatic tests but not for interactive work.
For automatic tests you may use pyautogui, pynput to control keyboard and mouse with code.
There is also module keyboard and mouse but keyboard
needs sudo
to run it as root
.
You can take screenshots with pyautogui
or python-mss (but I didn't test it in xvfb
)