这是我的代码
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
答案 0 :(得分:1)
将按钮单击分配给功能的最简单方法是使用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()