Class and tkinter problem
Terry Reedy
tjreedy at udel.edu
Thu Jan 7 04:20:53 EST 2021
On 1/7/2021 2:42 AM, Christian Gollwitzer wrote:
> Am 07.01.21 um 08:29 schrieb Paulo da Silva:
>
>> Does anybody know why cmd method isn't called when I change the button
>> state (clicking on it) in this example?
>> I know that this seems a weird class use. But why doesn't it work?
>> Thanks.
>>
>> class C:
>> from tkinter import Checkbutton
>> import tkinter
>>
>> @staticmethod
> ^^it works if you remove the staticmethod here
staticmethods are essentially useless in Python. What little was gained
by their addition is partly offset by the introduced confusion.
I am not sure is removing @staticmethod would have been sufficient in 2.x.
>> def cmd():
>> print("Test")
>>
top=tkinter.Tk()
cb=Checkbutton(command=cmd)
cb.pack()
Button commands have to be tcl functions. Tkinter wraps Python
functions as tcl function. Static methods also wrap python functions,
as a .__func__ attribute. So the code if one passes cmd.__func__.
> Maybe there is a bug in tkinter, that it doesn't work with static methods?
One could propose that tkinter test whether callables are staticmethods
and unwrap them when they are.
Classmethods also do not work as is. By experiment, the following works.
cb=Checkbutton(command=lambda: C.cmd.__func__(C))
But if the class were nested, it would be more complicated.
--
Terry Jan Reedy
More information about the Python-list
mailing list