pythontkinterobject-tagobject-types3-object-tagging

Expand Python Tkinter Object Types


There is this question to discover existing types:

However I've just developed tooltips (balloons) I've assigned to some buttons and would like to be able to recall all of them as a unique type. Also down the road I'd like to hand-craft canvas objects which will operate like pseudo buttons with <enter>, <leave>, <active>, <press> and <release> events. How might I declare a new object type for them?


Solution

  • If I understand your question correctly you want to check if an instance created is a instance of the custom class, it can be directly done using isinstance:

    class CustomTooltip():
        pass
    
    cwidget = CustomTooltip()
    btn     = tk.Button(root)
    
    print(isinstance(cwidget, CustomTooltip)) # True
    print(isinstance(b, CustomTooltip)) # False
    
    print(type(cwidget) == CustomTooltip) # Not recommended
    

    It is recommended to use isinstance rather than type, from the docs:

    The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.


    I did not quite get your 2nd question, also it is better to keep a single question focused around one main question rather than asking more than one question.