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]

31 March 2005, 2:55 UTC in software

Setting the NET_WM_ICON for Tkinter application windows



The icon created by the example program
This somewhat hackish module can be used to set the NET_WM_ICON for your Tkinter application.

read more…

All older entries
Website Copyright © 2004-2024 Jeff Epler