from Tkinter import *
#----------------------------------------------------------------------
def test(x):
#print "I'm in event:", x
if x == 1: # if event on entry e1
print 'e1 event' # do some thing
elif x == 2: # also if event on entry e2
print 'e2 event' # do some thing else
else:
print 'no event'
def test1(x):
test(1)
def test2(x):
test(2)
#----------------------------------------------------------------------
root=Tk()
e1=Entry(root)
e1.pack()
e2=Entry(root)
e2.pack()
root.bind_class(e1, "<FocusOut>", test1) #this can be some thing you suggest to me
root.bind_class(e2, "<FocusOut>", test2) # can be some thing you suggest to me
root.mainloop()
编辑:
你也可以这样绑定:
e1.bind("<FocusOut>", test1)
e2.bind("<FocusOut>", test2)
但总是只给出没有参数的函数名。
函数必须获取 1 个参数才能获取事件对象
def test1(x):
print x # <Tkinter.Event instance at 0xb74a6fcc>
test(1)
编辑:
开始学习面向对象的编程来制作“更干净”的程序——更有条理。
from Tkinter import *
#----------------------------------------------------------------------
class MainWindow():
def __init__(self, root):
self.e1 = Entry(root)
self.e1.pack()
self.e2 = Entry(root)
self.e2.pack()
self.e1.bind("<FocusOut>", self.test1)
self.e2.bind("<FocusOut>", self.test2)
#-------------------
def test(self, x):
if x == 1:
print 'e1 event'
elif x == 2:
print 'e2 event'
else:
print 'no event'
#-------------------
def test1(self, x):
print x
self.test(1)
#-------------------
def test2(self, x):
self.test(2)
#----------------------------------------------------------------------
root = Tk()
MainWindow(root)
root.mainloop()
编辑:
最新版本 - 使用事件对象的一个功能
from Tkinter import *
#----------------------------------------------------------------------
class MainWindow():
def __init__(self, root):
self.e1 = Entry(root)
self.e1.pack()
self.e2 = Entry(root)
self.e2.pack()
self.e1.bind("<FocusOut>", self.test)
self.e2.bind("<FocusOut>", self.test)
# or
# root.bind_class("Entry", "<FocusOut>", self.test)
#-------------------
def test(self, event):
if event.widget == self.e1:
#print "e1:", event.widget.get()
print "e1:", self.e1.get()
if event.widget == self.e2:
#print "e2:", event.widget.get()
print "e2:", self.e2.get()
#----------------------------------------------------------------------
root = Tk()
MainWindow(root)
root.mainloop()
有关事件的更多信息:Tkinter 事件和绑定