如何在Python中处理来自另一个类的小部件命令/函数调用?
当按下按钮时,我不希望在按钮所在的类中处理该函数调用,而是在另一个类中处理该函数调用。下面是我试图实现的代码:如何在Python中处理来自另一个类的小部件命令/函数调用?,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,当按下按钮时,我不希望在按钮所在的类中处理该函数调用,而是在另一个类中处理该函数调用。下面是我试图实现的代码: class TestButton: def __init__(self, root): self.testButton = Button(root, text ="Test Button", command = testButtonPressed).grid(row = 11, column = 0) #testButtonPressed is
class TestButton:
def __init__(self, root):
self.testButton = Button(root, text ="Test Button", command = testButtonPressed).grid(row = 11, column = 0)
#testButtonPressed is called in the TestButton class.
class TestClass:
#The testButtonPressed function is handled in the TestClass.
def testButtonPressed():
print "Button is pressed!"
请让我知道这是如何实现的,非常感谢 注意:我编辑了我的回答,因为我不能正确理解你的问题 在python中,可以将函数作为参数传递:
class TestButton:
def __init__(self, root, command):
self.testButton = Button(root, text ="Test Button", command = command).grid(row = 11, column = 0)
#testButtonPressed is called in the TestButton class.
class TestClass:
#The testButtonPressed function is handled in the TestClass.
def testButtonPressed(self):
print "Button is pressed!"
TestButton(root, TestClass().testButtonPressed)
静态功能:
如果已经定义了类,并且要传递的函数是静态的,则应该能够执行以下操作:
class TestClass:
def testButtonPressed(self):
print "Button is pressed!"
class TestButton:
def __init__(self, root):
self.testButton = Button(root, text="Test Button", command=TestClass.testButtonPressed).grid(row=11, column=0)
记住:将函数作为参数传递时,需要删除括号“()”。如果不这样做,则传递的是函数返回的内容,而不是函数本身
非静态功能:
如果要传递的函数不是静态的(需要在类的实例中调用),则必须具有对该实例的引用:
class TestClass:
def __init__(self):
self.message = "Button is pressed!"
def testButtonPressed(self):
print self.message
class TestButton:
def __init__(self, root):
instance = TestClass()
self.testButton = Button(root, text="Test Button", command=instance.testButtonPressed).grid(row=11, column=0)
或者,如果实例不在类的范围内:
instance = TestClass()
class TestButton:
def __init__(self, root, reference):
self.testButton = Button(root, text="Test Button", command=reference.testButtonPressed).grid(row=11, column=0)
test = TestButton(root, instance)
注意:非静态方法通常可以通过具有“self”参数来识别:例如:def function(self)
Do
def\uuu init\uuu(self,root,):…command=.testButtonPressed
Yup。成功了。非常感谢。