Search code examples
pythontkinterubuntu-server

Tkinter setup on headless server


I wrote a Python app with a Tkinter GUI, and later added in some CLI functionalities to use it without the GUI for use on a headless server (Ubuntu Server 16.04).

To limit the code I had to change, some of the Tkinter setup is still done, even in CLI mode

root = tk.Tk()
canvas = tk.Canvas(root, borderwidth=0)
frame = tk.Frame(canvas)
...

Now if I ssh onto the server using -X as suggested here 34584827, it works fine. But the way I want it to run is that a NodeJs chatbot (running unattended on the same server) launches the app and uses the result.

This gives me the error:

Traceback (most recent call last):
  File "sim.py", line 60, in <module>
    root = tk.Tk()
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1818, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

If there anything I can do to salvage this situation? A parameter I can use in the chatbot, a configuration for Tkinter...?

Note: this app also generates graphs with Matplotlib, but the solutions proposed in 37604289 take care of that part.


Solution

  • If there anything I can do to salvage this situation?

    The only thing you can do is modify your code to not initialize tkinter if running in command line mode. You can add an option, or you can catch the exception thrown when instantiating Tk.