python - 条目无法正确响应 python 中按钮的绑定(bind)

标签 python tkinter calculator tkinter-entry

我正在尝试用 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”就会进入条目。

最佳答案

我在您的代码中注意到了很多问题 -

  1. string=StringVar - 你需要这样调用它 StringVar() ,否则你只是设置 StringVar类(不是它的对象)到`string。

  2. 当你这样做时 -

    num_one.bind("Button-1",print_one(index))
    

    您实际上首先调用函数并绑定(bind)返回值,您应该绑定(bind)函数对象(而不调用它),示例 -

    num_one.bind("<Button-1>",print_one)
    
  3. 要将函数绑定(bind)到鼠标左键单击,需要绑定(bind)到 <Button-1> (注意末尾的 <>)而不是 Button-1 .

  4. 在您的函数中,您将收到的第一个参数(绑定(bind)的函数)是事件对象,而不是下一个索引。您可以使用类似 -

    string.set(string.get() + "1")
    

关于python - 条目无法正确响应 python 中按钮的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31902389/

相关文章:

Python:用新字符串替换字符串中的字符范围

python - 在 tkinter Canvas 中嵌入来自 Arduino 的 Matplotlib 实时绘图数据

c++ - 获取过滤后的用户输入并使其对应于菜单选项

javascript - 我在这个 javascript 贷款计算器上遗漏了什么?

java - 计算器 Android 应用程序中的乘法在输出中抛出 Alphabeta

python - 在自己的描述符之后,__dict__ 中缺少该属性

当文件具有相同名称时,Python 代码覆盖率缺失

python - 如何删除第 N 行 linux 的最后一个字符

python - 在饼图上显示带有图例的数字 - Tkinter、Pyplot、Matplotlib

python - 为什么4个按钮不显示?