Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More on passing arguments to tkinter button command

Tags:

python

tkinter

I have a number of test files in a single directory. I'm trying to write a GUI to allow me to select and run one of them.

So, I have a loop that scans the directory and creates buttons:

    for fnm in glob.glob ('Run*.py'):
        tstName = fnm[3:-3]      # Discard fixed part of filename
        btn = Button (self, text=tstName,
                      command=lambda: self.test(tstName))
        btn.grid (row=rowNum, column=0, pady=2)
        rowNum += 1

This creates my GUI correctly, with buttons labelled say, A and B but when I press on the button labelled A it passes B to the test method.

I've looked around and found this question How can I pass arguments to Tkinter button's callback command? but the answer doesn't go on to use the same variable name, with a different value, to configure another widget. (In fact, by tying the variable name to the widget name it almost implies that the technique won't work in this case, as I've found.)

I'm very new to Python, but am quite familiar with creating this kind of GUI using Tcl/TK and I recognise this problem - the value of tstName is being passed when I press the button, but I want it to pass the value the variable had when I created it. I know how I'd fix that in Tcl/Tk - I'd define a command string using [list] at creation time which would capture the value of the variable.

How do I do the same in Python?

like image 698
nurdglaw Avatar asked Oct 24 '25 03:10

nurdglaw


1 Answers

You need to bind the current value of tstName at the time you define the button. The way you're doing it, the value of tstName will whatever it is at the time you press the button.

To bind the value at the time that you create the button, use the value of tstName as the default value of a keyword parameter to the lambda, like so:

btn = Button(..., command=lambda t=tstName: self.test(t))
like image 125
Bryan Oakley Avatar answered Oct 27 '25 00:10

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!