whtitefall
whtitefall

Reputation: 671

Couldn't connect to display error when using tcl lib in python

I'm trying to call a hello world tcl script in python on linux server, but it generates _tkinter.TclError: couldn't connect to display error.

Error as follows:

r = Tkinter.Tk()
File "/apps/cad/default/python2.7/lib/python2.7/lib-tk/Tkinter.py", line 1764, in __init__
  self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)"
_tkinter.TclError: couldn't connect to display 

I've searched on this problem, but most of the solution is to use Agg in matplotlib.use(), but I tried it and it doesn't work.

test.py

import Tkinter

r = Tkinter.Tk()

r.tk.eval("source test.tcl")

test.tcl

puts "hello py"

What causes this problem, and how am I going to solve this? Thank you!

Upvotes: 0

Views: 1152

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137567

Tk, and hence Tkinter, requires an X server (often called a “display”) on Linux so that it has something on which to pop up windows. Because that's its primary purpose; to draw windows. (How to connect to the X server is described in the DISPLAY environment variable.)

Servers don't usually have displays. If you need one, use the Xvfb program (which creates a Virtual Frame Buffer, a synthetic display) and that works fine as long as you don't actually need to interact with the windows that your script creates. If you do need to interact with the windows, you'll have to find a way to make them display somewhere else. This might be by using X forwarding with ssh, or a VNC connection somehow, or… well, there's lots of options. You are advised to not write your code to require user interaction if it is going to run on a server. It can be done, but it's devilishly tricky and should be avoided where unnecessary.

You'll need to read up on Xvfb to see how to launch it and your Python code in such a way that they can find each other.

Upvotes: 2

Related Questions