0

i am create a Gui for a lottery Application. To apply this i need to create 49 buttons. Now i want to make it cleaner, by using one function to create the buttons i need. I use tkinter. To solve this i created a list namend buttons with a range of 1 and 49. Then i used a for-loop:

for i in button:
     button_i = tkinter.Button(Fenster, text=i, bd=20 , command= lambda :[switch(button_i,i),zahl(i,button_i) , print(Spielerzahlen)])
     button_i.grid(row=y, column=z)
     z = z + 1
     if z == 7:
            y += 1
            z = 0

The problem is now, that the commands "switch" and "zahl" dont run, because i bind the name of the button as parameter. How can i take the element i in the button name, so that by every round the name of the button changes?

Thank you.

yours sincerely

Detek001

d37oop123
  • 11
  • 2

1 Answers1

0

what you need is a "closure", you might want to read about that: https://www.programiz.com/python-programming/closure

Here's a minimal working example:


import tkinter
from tkinter import *


Fenster = Tk()


def closure(i):
    return lambda :print(i)

for i in range(49):
    button_i = tkinter.Button(Fenster, text=i, command=closure(i))
    button_i.grid(row=i%7,column=i//7)

Fenster.mainloop()
avloss
  • 2,389
  • 2
  • 22
  • 26