1

I am new to coding in general (Python is my first language) and I ran into this problem while learning tkinter. My code is as follows:

from tkinter import *
window = Tk()

buttons = []

def position(pos):
    print(pos)

for i in range(7):
    buttons.append(Button(window, width = 10, height = 5, bg = "red", command = position(i)).grid(row = 0, column = i))

window.mainloop()

This does not work. I want to print the index of the button when that button is clicked. I have tried a few methods to accomplish this, but with no success. The buttons do not necessarily have to be in a list, however the first button must return 0, the second return 1, the third 2 etc. What is the simplest way to do this?

TDJSB
  • 49
  • 1
  • 2
  • 4

1 Answers1

0

See this:

from tkinter import *

root = Tk()

files = [] #creates list to replace your actual inputs for troubleshooting purposes
btn = [] #creates list to store the buttons ins

for i in range(50): #this just popultes a list as a replacement for your actual inputs for troubleshooting purposes
    files.append("Button"+str(i))

for i in range(len(files)): #this says for *counter* in *however many elements there are in the list files*
    #the below line creates a button and stores it in an array we can call later, it will print the value of it's own text by referencing itself from the list that the buttons are stored in
    btn.append(Button(root, text=files[i], command=lambda c=i: print(btn[c].cget("text"))))
    btn[i].pack() #this packs the buttons

root.mainloop()

Taken from: How can I get the button id when it is clicked?

DecaK
  • 286
  • 2
  • 13
  • That works well, however is there a way to adapt that code to make it return an integer, e.g. button1 would return 1, button2 would return 2 etc.? It is important for the program I am making, that the button returns either the float or integer values. Thanks for your help. – TDJSB Jun 11 '18 at 15:29
  • Yes, 'command' argument is used for that. You can call the function there, see the following: https://pastebin.com/mQrhpcEk If that solved your problem, you can accept it :) – DecaK Jun 11 '18 at 15:48
  • Thank you very much that is perfect! – TDJSB Jun 11 '18 at 17:30