0

Ok sorry again for the title. I did not know what to call it. So my problem is that I am trying to make my code create 11 buttons that each execute their own separate command. For example, when I click button one, it prints usrGruFunc.addusr, and if I click button 5, I should get a response saying usrGruFunc.adusrtogru. I know there are easier ways to do what I am trying to do but I want to avoid writing a bunch of repetitive code.

The code:

from threading import *
from tkinter import *
from tkinter.ttk import *
from ugmfunctions import * #this is something I made in a different file. It is not required to run the code. It is just the names of the commands for the targets

targets = [usrGruFunc.addusr, usrGruFunc.rmuser, usrGruFunc.adgru, usrGruFunc.rmgru, usrGruFunc.adusrtogru, usrGruFunc.rmusrfrogru, usrGruFunc.lslocausr, usrGruFunc.lslocagru, usrGruFunc.lsmemgru, usrGruFunc.lsgruusrin, usrGruFunc.chngusrspass]


class ThreadUGMfunc:
    buttonname = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']
    buttons = []

    def __init__(self):
        for c in range(0, 11):
            self.buttons.append(Button(root, text=c, command= lambda: ThreadUGMfunc.threader(c)))
            print(self.buttons[c])
            self.buttons[c].grid()

    def threader(c):
        try:
            #self.threader = Thread(target=targets[c])
            #self.threader.start
            print(targets[c])
        except Exception as e:
            print(e)
            print('Could not start thread')


if __name__ == '__main__':
    root = Tk()
    root.title('Apple CIDR Script Runner')
    main = ThreadUGMfunc()
    root.mainloop()

When the code is run, It loads up and everything but when I click a button, it always outputs saying that it is the last one in the list of targets, usrGruFunc.chngusrspass

Output when I click any button:

<function usrGruFunc.chngusrspass at 0x0000020E008E1B80>

I recommend copying the code and testing it yourself to see what I am seeing. I am not very good at explaining things. Sorry :(

Any help with this problem is greatly appreciated!

Also if there is any way to help improve my question or summary please tell me in a comment or something :) (Example: please help me with a better title to this question)

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
ViperSniper0501
  • 300
  • 6
  • 15
  • 1
    change your code `self.buttons.append(Button(root, text=c, command= lambda: ThreadUGMfunc.threader(c)))` to `self.buttons.append(Button(root, text=c, command= lambda c=c: ThreadUGMfunc.threader(c)))`. – jizhihaoSAMA Apr 07 '20 at 09:30
  • There is a good explanation in the official Programming FAQ: [Why do lambdas defined in a loop with different values all return the same result?](https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result) – figbeam Apr 07 '20 at 10:11

0 Answers0