ashish kumar
ashish kumar

Reputation: 1

Not able to get button click value into event in Tkinter

This are my code

button1= tk.Button(text ="1", height=7, width=20)
button1.bind("<Button-1>",handle_pin_button)
button1.grid(row=3,column=0)
button2 = tk.Button(text="2", height=7, width=20)
button2.bind("<Button-1>", handle_pin_button)
button2.grid(row=3,column=1)
button3 = tk.Button(text="3", height=7, width=20)
button3.bind("<Button-1>", handle_pin_button)
button3.grid(row=3,column=2)

And my handle_pin_button is below

def handle_pin_button(event):
       '''Function to add the number of the button clicked to the PIN number entry via its associated variable.'''
       print("hello")
       values_for_pin = repr(event.char)
       print(values_for_pin)
       print(event.keysym)

       pin_number_var.set(values_for_pin)
       value = str(pin_number_var.get())
       print(value)

       # Limit to 4 chars in length
       if(len(value)>4):
           pin_number_var.set(value[:4])

its coming like '??' in event.char

Upvotes: 0

Views: 600

Answers (1)

figbeam
figbeam

Reputation: 7176

The easiest way to assign a button click to a function is to use the command parameter. As you want to have each button deliver a specific value (the number) you can use lambda for that.

button1= tk.Button(root, text ="1", height=7, width=20,
               command=lambda:handle_pin_button("1"))

Now you get the number delivered to the function and can write it without referring to the event.

Examine the example below; is this what you are after?

import tkinter as tk

root = tk.Tk()

pin_number = [] # Create a list to contain the pressed digits

def handle_pin_button(number):
    '''Function to add the number of the button clicked to
    the PIN number entry via its associated variable.'''
    print("Pressed", number)
    pin_number.append(number)   # Add digit to pin_number

    # Limit to 4 chars in length
    if len(pin_number) == 4:
        pin = "".join(pin_number)
        for _ in range(4):
            pin_number.pop()    # Clear the pin_number
        print("Pin number is:", pin)
        return pin

button1= tk.Button(root, text ="1", height=7, width=20,
                   command=lambda:handle_pin_button("1"))
button1.grid(row=3,column=0)
button2 = tk.Button(root, text="2", height=7, width=20,
                   command=lambda:handle_pin_button("2"))
button2.grid(row=3,column=1)
button3 = tk.Button(root, text="3", height=7, width=20,
                   command=lambda:handle_pin_button("3"))
button3.grid(row=3,column=2)


root.mainloop()

Upvotes: 1

Related Questions