Jeff Epler's blog

6 October 2024, 14:15 UTC

Talking directly to in-process tcl/tk


I recently saw a post on a blog about using wish as a subprocess of Python, as a way to access tk without the complexity of tkinter.

To be clear the original post also calls out the situation where the tkinter part of python is not installed by default, and my technique would not be applicable there.

So what do you do if you like Tk but don't care for the high level abstraction provided by Tkinter? Well, you can import _tkinter and create a tkapp object with _tkinter.create().

The _tkinter module and the tkapp object is largely undocumented, but in Python 3.11 here are some useful methods:

  • tkapp.createcommand: Create a callback into Python code. Takes a string and a callable. Creates a Tcl command with that name, that calls back into Python code: app.createcomand("cb", lambda *args: print("cb", args))
  • tkapp.eval: Takes a command and evaluates it. Call it with a single string: app.eval("button .b -text HI -command {cb arg1 arg2}")
  • tkapp.call: Takes a series of arguments, does proper Tcl quoting, and evaluates it: app.call("pack", ".b")
Now, go forth and program your graphical app without all that Python object nonsense!

Python 3.11.2 (main, Aug 26 2024, 07:20:54) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import _tkinter
>>> app = _tkinter.create()
>>> app.createcommand("cb", lambda *args: print("cb", args))
>>> app.eval("button .b -text HI -command {cb arg1 arg2}")
'.b'
>>> app.call("pack", ".b")
''
>>> # Now I click the button several times ...
>>> cb ('arg1', 'arg2')
cb ('arg1', 'arg2')
cb ('arg1', 'arg2')

[permalink]

29 April 2006, 21:58 UTC in software

Onscreen Crosshairs in tcl/tk


I was staring too long at a screenshot of a graph on some web page, wishing I could tell if two things lined up. Well, inspiration struck, and this program was born. Two windows—one that is one pixel wide, and another that is one pixel tall—are created, and they follow the mouse around every 1/10 second or so. They're displaced by one pixel so that clicking will hit the underlying window, not the crosshair.

I apologize for the changing colors, since xor isn't available with this simple method of drawing the lines, it's the only way to be sure to get contrast. I considered making the color depend on e.g., whether SHIFT is pressed, but if Tk provides this information to a window that doesn't have focus, I overlooked it in the manpages.

read more…

All older entries
Website Copyright © 2004-2024 Jeff Epler