我正在尝试用 python 编写一个计算器有一段时间了,我的条目有一个问题,我无法解决它,尽管我没有看到它有任何问题。
这是我的代码的示例:
from Tkinter import *
window =Tk()
window.title("Calculator")
#creating an entry
string=StringVar
entry = Entry(window, width=40,textvariable=string )
entry.grid(row=0, column=0, columnspan=6, ipady=10)
entry.focus()
#basically I have a function for creating buttons but here I will do it the traditional way.
num_one=Button(window,text="1",width=2,height=2,padx=20,pady=20,)
num_one.grid(row=1,column=0,padx=1,pady=1)
#crating an index for the calculator
index=0
#creating a function to insert the number one to the entry in the index position and then add one to the index
def print_one(index):
entry.insert(index,"1")
binding the num_one button to the function above
num_one.bind("Button-1",print_one(index))
现在的问题是,只有当我单击 num_one 按钮时,才应在条目中输入字符串“1”,但是当我自动启动程序时,数字“1”就会进入条目。
最佳答案
我在您的代码中注意到了很多问题 -
string=StringVar
- 你需要这样调用它StringVar()
,否则你只是设置StringVar
类(不是它的对象)到`string。当你这样做时 -
num_one.bind("Button-1",print_one(index))
您实际上首先调用函数并绑定(bind)返回值,您应该绑定(bind)函数对象(而不调用它),示例 -
num_one.bind("<Button-1>",print_one)
要将函数绑定(bind)到鼠标左键单击,需要绑定(bind)到
<Button-1>
(注意末尾的<
和>
)而不是Button-1
.在您的函数中,您将收到的第一个参数(绑定(bind)的函数)是事件对象,而不是下一个索引。您可以使用类似 -
string.set(string.get() + "1")
关于python - 条目无法正确响应 python 中按钮的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31902389/