首页 > 解决方案 > 无法将按钮单击值获取到 Tkinter 中的事件中

问题描述

这是我的代码

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)

我的handle_pin_button在下面

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])

它的到来就像'??' 在 event.char

标签: pythonooptkinter

解决方案


将按钮单击分配给功能的最简单方法是使用command参数。因为您希望每个按钮都提供一个特定的值(数字),所以您可以使用lambda它。

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

现在你得到了传递给函数的数字,并且可以在不参考事件的情况下编写它。

检查下面的例子;这就是你所追求的吗?

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()

推荐阅读