2015-08-09 72 views
2

我想在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)) 

现在的问题是,字符串“1”应输入的条目只有当我点击n个num_one按钮,但是当我开始自动编程数字“1”进入条目。

回答

2

很多,我在你的代码发现问题 -

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

  2. 当你这样做 -

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

    实际上,你首先调用函数和约束的返回值,则应改为绑定函数对象(不叫它),实例 -

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

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

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

谢谢!我没有理解你在第4号的解释。你能不能再给我解释一遍? – TheTechGuy

+0

请点击此处 - http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm 单击按钮时,您不会将'index'作为第一个参数。相反,您可以获取数据,然后在添加'1'后将其设置回来。 –

+0

谢谢你!解决了问题!在函数中,我需要将它作为参数,然后将索引声明为全局变量,将第一个数字插入到条目中,并将第一个索引添加到索引中。 – TheTechGuy

2

由于阿南德说,存在着各种问题与您当前的代码,无论是在语法&设计。

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

它看起来像你打算为每个数字按钮写一个单独的回调函数。这是不必要的,它可能会变得混乱。

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

请注意,我的代码使用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代码应该进入一类,因为这使得它更容易为小部件共享数据,并且也容易使代码更简洁。

+0

哇,真的让代码更容易!我的代码中唯一不能识别的就是divemode()。它对内部的值有什么作用? – TheTechGuy

+0

@TheTechGuy:'divmod()'是一个内置的函数,可以进行整数除法。它将商和余数作为元组返回。有关更多信息,请参阅官方Python [函数](https://docs.python.org/3/library/functions.html#divmod)文档。 –