Priyansh Gupta
Priyansh Gupta

Reputation: 99

Tkinter : How to pass a button's text as an argument to a function when button is clicked

I have the following code that generates a random button grid of 5x5 dimensions :

import tkinter as tk
from tkinter import *
from tkinter import messagebox
import random

def numberClick(num):
    messagebox.showinfo('Message', 'You clicked the '+str(num)+' button!')

root = Tk()
#root.geometry("200x200")
w = Label(root, text='Welcome to Bingo!') 
linear_array = [i for i in range(1,26)]
random_array = []
for i in range(1,26):
    temp = random.choice(linear_array)
    linear_array.remove(temp)
    random_array.append(temp) 

for i in range(25):
    num = random.choice(random_array)
    #tk.Label(root,text=num).grid(row=i//5, column=i%5)
    redbutton = Button(root, text = num, fg ='red',height = 3, width = 5,command=lambda: numberClick(num))
    redbutton.grid(row=i//5, column=i%5)

root.mainloop()

I have implemented the command function and passed a parameter with lambda as shown :

redbutton = Button(root, text = num, fg ='red',height = 3, width = 5,command=lambda: numberClick(num))

Now when I click a button , the function call should print the text value assigned with it. Instead it just prints the same value , that is the last assigned value in num variable : Output when i clicked on button 20

Any workarounds?? TIA.

Upvotes: 2

Views: 1259

Answers (2)

Carlos Brandt
Carlos Brandt

Reputation: 61

I was just about to point out the same thing a Cool Cloud, but I'd also like to add that you are randomizing twice such that you might get duplicate numbers.

The first for loop randomizes the numbers 1-25 in random_array, but then in the second loop you randomly select one element from that list without removing it when you initialize num. I'd write the second loop as:

for i in range(25):
    num = random_array[i]
    redbutton = Button(root, text = num, fg ='red',height = 3, width = 5, command=lambda n=num: numberClick(n))
    redbutton.grid(row=i//5, column=i%5)

Upvotes: 2

Delrius Euphoria
Delrius Euphoria

Reputation: 15098

Just change your button to:

redbutton = Button(root, text = num, fg ='red',height = 3, width = 5,command=lambda num=num: numberClick(num))

This should fix the issue, this will store the value of num in lambda rather than just looping and using the last value of num.

Upvotes: 2

Related Questions