条目无法正确响应 python 中的按钮绑定

entry does not respond correctly to buttons' binding in python

我尝试在 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 class (不是它的对象)设置为`字符串.

  2. 当你做 -

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

    你实际上先调用函数并绑定 return 值,你应该改为绑定函数对象(而不调用它),示例 -

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

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

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

正如 Anand 所说,您当前的代码在语法和设计方面都存在各种问题。

我不确定您为什么要自己跟踪 Entry 的索引,因为 Entry 小部件已经这样做了。要在当前光标位置插入文本,您可以在 entry.insert() 方法调用中使用 Tkinter.INSERT

您似乎打算为每个数字按钮编写一个单独的回调函数。这是不必要的,它可能会变得混乱。

下面的代码展示了一种为多个按钮使用单个回调函数的方法。我们将按钮的编号作为属性附加到按钮本身。回调函数可以轻松访问该数字,因为调用回调的事件对象参数包含将其激活为属性的小部件。

请注意,我的代码使用 import Tkinter as tk 而不是 from Tkinter import *。当然,它使代码有点冗长,但它可以防止名称冲突。

import Tkinter as tk

window = tk.Tk()
window.title("Calculator")

entry_string = tk.StringVar()
entry = tk.Entry(window, width=40, textvariable=entry_string)
entry.grid(row=0, column=0, columnspan=6, ipady=10)
entry.focus()

def button_cb(event):
    entry.insert(tk.INSERT, event.widget.number)

for i in range(10):
    y, x = divmod(9 - i, 3)
    b = tk.Button(window, text=i, width=2, height=2, padx=20, pady=20)
    b.grid(row=1+y, column=2-x, padx=1, pady=1)
    #Save this button's number so it can be accessed in the callback
    b.number = i
    b.bind("<Button-1>", button_cb)

window.mainloop()

理想情况下,GUI 代码应该放在 class 中,因为这样可以使小部件更容易共享数据,并且往往会使代码更整洁。