Home > Mobile >  if I use bind_all, can I make exceptions for some widgets?
if I use bind_all, can I make exceptions for some widgets?

Time:10-06

It occurred to me to make use of event.widget.winfo_parent(), but it returns a str with the full path of the widget and I can't grab wrapper to put it inside an if to prevent the statement block from executing. Hence my question if there is a more correct method to do this or some way to grab the container, in this case from of self.btn and use it in a statement. Thanks

The challenge is making exceptions between buttons, in the example I only put two, but what do I do if I want the exception to be for a few buttons and not all?

from tkinter import *

class Example(Frame)
    def __init__(self, master, *args, **kwargs):
        super().__init__(master, *args, **kwargs)
        self.frame = Frame(self, bg='yellow')
        self.frame .pack(side=TOP, fill=BOTH)
         
        self.cnt = Frame(self.frame, bg='green2')
        self.cnt .pack(side=TOP, fill=BOTH)

        self.btn = Button(self.cnt, text='Button 1 ')
        self.btn.pack()
        self.btn2 = Button(self.cnt, text='Button 2')
        self.btn2.pack()
        

        self.bind_all('<Motion-1>', self.hellow)

    def hellow(self, event):
        print('I always run how I want')

root = Tk()
app = Example(root)
app .pack(side=TOP, fill=BOTH)
root.mainloop()

CodePudding user response:

You can use isinstance to check weather the widget is a Button or whatever.

def hellow(self, event):
    if not isinstance(event.widget,Button):
        print('I always run how I want, except when hovered over buttons')

This will run the print every time you hover over any widget other than Button. But keep in mind, this will run hellow for every widget, but it wont execute the code put inside the if block for the avoided widget.

After the question is updated: You can create a list with buttons to avoid and then just check if the widget belongs in the list.

class Example(Frame):
    def __init__(self, master, *args, **kwargs):
        super().__init__(master, *args, **kwargs)
        self.frame = Frame(self, bg='yellow')
        self.frame .pack(side=TOP, fill=BOTH)
        self.cnt = Frame(self.frame, bg='green2')
        self.cnt .pack(side=TOP, fill=BOTH)

        self.btn = Button(self.cnt, text='First')
        self.btn.pack()

        self.btn1 = Button(self.cnt, text='Second')
        self.btn1.pack()

        self.btn2 = Button(self.cnt, text='Third')
        self.btn2.pack()

        self.bind_all('<Motion>', self.hellow)

        self.to_avoid = [self.btn1,self.btn2] # Buttons to avoid list

    def hellow(self, event):
        if event.widget not in self.to_avoid:
            print('I always run how I want, except for some widgets')
  • Related