繁体   English   中英

无法在Tkinter中将按钮点击值转化为事件

[英]Not able to get button click value into event in 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

将按钮单击分配给功能的最简单方法是使用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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM