1

I am writing a GUI with Python TKinter where I have a grid of some 24 buttons which I have created using a loop (not individually). Is there any way in which I can get the Text of the button that I pressed.

Since it is in loop, a callback function even with lambda is not helping me. I don't wish to write separate code for, what happens when each different button is pressed. I just need to know the text of the corresponding button so that I could initiate another generic function which works with that text only.

ps: I am able to do the same task but with List and curselection() and don't want it this way.

self.num = 11

for r in range(0,5):

   for c in range(0,3):

       R = r; C = c

       resNum = "Ch0"+str(self.num);

       self.button1_rex = tk.Button(self.frame, text = resNum,font=("Helvetica", 14), justify = CENTER,width = 20, command = self.new_window)

       self.button1_rex.grid(row=R, column=C, sticky=W)

       self.num = self.num+1

self.new_window is the function that opens a new window and needs to do other functionalities based on the button number (like "Ch011" etc)

Ashish Sharma
  • 148
  • 3
  • 14

1 Answers1

4

The simplest way is just to, when you are constructing the button, bind the name to the command, either using functools.partial or a lambda.

Using functools.partial:

self.button1_rex = tk.Button(..., command=functools.partial(self.new_window, resNum))

Using a lambda:

self.button1_rex = tk.Button(..., command=lambda r=resNum: self.new_window(r))

For more infomation about the lambda, see What is a lambda (function)? and Python tkinter creating buttons ... arguments.

Community
  • 1
  • 1
matsjoyce
  • 5,744
  • 6
  • 31
  • 38
  • Thanks for the prompt response. I already tried with lambda, its not serving the purpose as it always returns the last value of "resNum" and not the currently selected value. However, your first suggestion of using "partial" has worked for me. Thanks a lot. – Ashish Sharma Feb 27 '15 at 11:56
  • No, its causing syntax error. I'm sorry for inconvenience. I don't have much experience in python. – Ashish Sharma Feb 27 '15 at 12:25
  • AH, that's true. I'm too used to python 3 and Qt ATM. Thanks. – matsjoyce Feb 27 '15 at 13:08
  • Thank you very much for help. Its working correctly. Can you please direct me to some tutorial/help on the usage of "lambda". It would be great if you could just explain the "lambda" approach used here. – Ashish Sharma Feb 27 '15 at 17:16
  • I've added some SO links, and maybe something like http://www.diveintopython.net/power_of_introspection/lambda_functions.html helps? – matsjoyce Feb 27 '15 at 17:23