如何在Python中处理来自另一个类的小部件命令/函数调用?

问题描述 投票:1回答:2

当按下按钮时,我想处理那个函数调用,而不是在按钮所在的类中,而是在另一个类中。所以这里是我正在努力实现的以下代码:

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 python-3.x python-2.7
2个回答
1
投票

注意:我编辑了我的回复,因为我无法正确理解您的问题。

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

0
投票

静态功能:

如果已经定义了类并且您要传递的函数是静态的,那么您应该可以执行以下操作:

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)

注意:非静态方法通常可以通过“自我”参数来识别:例如:def function(self)

© www.soinside.com 2019 - 2024. All rights reserved.