0

So I'm generating a grid of 6x6 buttons in Tkinter using a for loop. Would there be a way for them to all use the same function when clicked, but with different arguments for each button?

(For example, the letter of the first button is C, so the function click() prints a 'C'. Then the second button's letter is J, so it would print 'J', and so on for the 36 buttons)

Here's the code :

import tkinter as tk
import random

chars = ['A', 'A', 'B', 'B', 'C', 'C', 
         'D', 'D', 'E', 'E', 'F', 'F', 
         'G', 'G', 'H', 'H', 'I', 'I', 
         'J', 'J', 'K', 'K', 'L', 'L', 
         'M', 'M', 'N', 'N', 'O', 'O', 
         'P', 'P', 'Q', 'Q', 'R', 'R']

random_chars = []
for i in range(len(chars)):
    random_index = random.randint(0, (35 - i))
    random_chars.append(chars[random_index])
    chars.pop(random_index)

def click(value):
    print(value)


window = tk.Tk()

for i in range(6):
    for j in range(6):
        frame = tk.Frame(master=window)
        frame.grid(row=i, column=j, padx=2, pady=2)
        button = tk.Button(
            master=frame, 
            text=random_chars[(i*6) + j],
            width=9,
            height=4,
            command=lambda: click('') # => THE VALUE (chars) OF THE BUTTON
        button.pack()


window.mainloop()

0 Answers0