0

I iteratively generate a grid of entry boxes, which are identified by 'ixj' where i and j are the indexes of the box. I would like to attatch traces on their StringVars so that I only operate on one row of this grid at a time.

I currently use:

tk_variable.trace("w", function)

This is then bound to an entry box via it's constructor.

Then 'function' just iterates through every entry box. Is there some way I can pass 'i' to that function, so that when each box is edited, it calls the function, passes its row, and the function then operates on all entry boxes in that row.

Something like:

tk_variable.trace("w", function(i))

However, I know that this syntax actually calls the function, rather than returning an index to it.

I have tried lambda functions:

tk_variable.trace("w", lambda i: function(i))

but I get errors such as:

Exception in Tkinter callback

Traceback (most recent call last):

File "[...]\anaconda3\lib\tkinter\__init__.py", line 1883, in __call__

return self.func(*args)

TypeError: <lambda>() takes 1 positional argument but 3 were given

My function is defined:

def function(*args):

Expected results: I can print args, and see the row affected. Any tips?

  • 1
    Can you show your entire code, I do not understand what you mean. How do you bind the function to i*j `StringVar`'s? – Delrius Euphoria Jun 08 '21 at 01:42
  • 2
    Try `tk_variable.trace("w", lambda *args, i=i: function(i))`. – acw1668 Jun 08 '21 at 01:45
  • @Sujay Unfortunately this presented the same issue as in the post –  Jun 08 '21 at 02:08
  • @CoolCloud My problem has been solved, but for completeness I added the fact that I use the entry box's constructor to link the stringVars. The trace was already shown. –  Jun 08 '21 at 02:10
  • This should instead have been closed as unclear and/or lacking an MRE. Voting to delete now. – Karl Knechtel Aug 18 '22 at 03:04

1 Answers1

0

The solution was this:

tk_variable.trace("w", lambda *args, i=i: function(i))

by user: acw1668

  • Actually this question is a duplicate of https://stackoverflow.com/questions/17677649/tkinter-assign-button-command-in-loop-with-lambda – Delrius Euphoria Jun 08 '21 at 04:52
  • It isnt though, because the solution breaks without the "*args", which is not present in your link –  Jun 08 '21 at 09:47
  • It is actually an additional step that you have to implement on your own, nothing complicated. – Delrius Euphoria Jun 08 '21 at 10:55
  • Not for those new to python/lambda, like myself, who had seen that question and still was unable to fix my code. –  Jun 08 '21 at 14:17