Expand Python Tkinter Object Types

218 Views Asked by At

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?

2

There are 2 best solutions below

9
On BEST ANSWER

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.

6
On

Object Oriented Programming is probably the solution.

If I want to create a "new type" of tkinter button I can sub-class it.

class MySpecialButton(tkinter.Button):
    pass

This doesn't do anything special at the moment but will give it a unique type (If it have understood your interpretation correctly)

The following example from another one of my answers, creates a special button with custom behaviour for hovering over the button

class HoverButton(tk.Button):
    def __init__(self, master, **kw):
        tk.Button.__init__(self,master=master,**kw)
        self.defaultBackground = self["background"]
        self.bind("<Enter>", self.on_enter)
        self.bind("<Leave>", self.on_leave)

    def on_enter(self, e):
        self['background'] = self['activebackground']

    def on_leave(self, e):
        self['background'] = self.defaultBackground

With regard to canvas object, You can obviously create classes for these too which can contain methods for moving/resizing the object. As to how to create custom events for these, you can use tag_bind(item, event=None, callback=None, add=None) to bind a call back to a canvas object. A quick example below

import tkinter as tk

class CanvasShape:
    def __init__(self, canvas, callback = None):
        self.canvas = canvas
        self.id = canvas.create_oval(10,10,50,50,fill='blue')
        self.canvas.tag_bind(self.id,'<Button-1>',callback)

def clicked(e):
    print("You clicked on a shape")

root = tk.Tk()
c = tk.Canvas(root,width=200,height=200)
c.grid()
shape = CanvasShape(c,callback=clicked)

root.mainloop()

This will create a circle that when you click on it will fire an event that is received by the clicked function.