使函数可调用的函数无法正常工作 [英] Function to make functions callable doesn't work properly

查看:103
本文介绍了使函数可调用的函数无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建按钮时遇到了执行按钮命令的问题。要停止此操作,我有一个函数可以停止此行为

I'm having the problem of a button executing its' command when it's created. To stop this I have got a function, which can stop this behavior

此函数使函数可以调用,而无需在创建按钮时执行。通常它可以正常工作,但是通过某些功能,它似乎会随机拒绝任何输入!以下是代码:

This is the function which makes functions callable without being executed while creating my button. Usually it works fine but with some functions it seems to deny randomly any input! Here is the code:

class Callable(object):
    def __init__(self, func, *args, **kwds):
        self.func = func
        self.args = args
        self.kwds = kwds

    def __call__(self, *args, **kwds):
         return self.func(self.args)

    def __str__(self):
        return self.func.__name

似乎完全是随机的,哪些问题被接受,哪些不被接受。我真的很绝望,因为编写此类的同义词要花很多时间,所以我用 args kwds ,那么就可以了。但是现在我要知道我将要传递多少个参数,所以这将不再起作用。

It seems to be totally randomly which questions are accepted and which aren't. I'm really desperate, because it takes a lot of time to write a kind of synonym of this class, I adapt them with the number of args and kwds, then it works ok. But now I'm coming to a point where I don't know how many args I'm going to pass, so this won't work any more.

问题:


  • 为什么此类不接受每个函数?

  • 如何更改此行为?

推荐答案

您的类用于为tkinter回调提供其他上下文,因此该回调实际上可以做一些有用的事情。除了调用该函数时需要解压原始args和kwds之外,您几乎完全正确。另外,不要在 __ call __ 中包含任何参数,因为您不接受任何参数。

Your class is used to provide additional context to tkinter callbacks so the callback can actually do something useful. You almost have it right except that you need to unpack the original args and kwds when calling the function. Also, don't include any args in __call__ because you don't accept any.

class Callable(object):
    def __init__(self, func, *args, **kwds):
        self.func = func
        self.args = args
        self.kwds = kwds

    def __call__(self):
         return self.func(*self.args, **self.kwargs)

    def __str__(self):
        return self.func.__name


def some_callback(a, b, c=None):
    print(a,b,c)

Button(text="Do not press", 
    command=Callable(some_callback, 1, 2, 3))

这也可以不使用class而是使用lambda来完成。

This can also be done without a class, using lambdas instead

def some_callback(a, b, c=None):
    print(a,b,c)

Button(text="Do not press", 
    command=lambda: some_callback(1, 2, 3))

这篇关于使函数可调用的函数无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆