python - 无法将按钮单击值获取到 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()
推荐阅读
- android - react-native-fcm android通知不起作用
- android-studio - 开发intellij idea插件时如何创建kotlin类?
- installation - WiX 3.11.1 刻录引导程序无法提升
- tomcat8 - Tomcat8 源服务器没有找到目标资源的当前表示或不愿意透露存在的表示
- php - 无法流式传输 pdf:标头已发送
- r - 如何根据唯一用户 ID 和特定事件类型创建 for 循环
- twitter-bootstrap - 之间的区别:输入组前置和附加?(BS4)
- c# - 如何冻结集合以便可以迭代它?
- c - 避免无限的while循环
- mysql - SQL WHERE 过滤