Home > Mobile >  How to bind multiple events to one function python tkinter
How to bind multiple events to one function python tkinter

Time:08-04

Is there any better way to do the following:

master.bind("<Button-1>", function)
master.bind("<Button-2>", function)
master.bind("<Button-3>", function)

I want to bind 3 events to one function in less than three lines of code. I know that this probably is not possible. I am just wondering if you could do something like this:

master.bind("<Button-1>" and "<Button-2>" and "<Button-3>", function)

This doesn't work as it only binds "<Button-3>". Using or instead of and only binds "<Button-1>".

Edit: I can use the generic "<Button>" like:

master.bind("<Button>", function)

I want a more generic example, like one that can be used for "<KP_0>" and "<Button-1>".

CodePudding user response:

I don't believe that Tkinter supports this functionality due to it being essentially a loop.

If you really need your code all on one line try this.

master.bind("<Button-1>", function), master.bind("<Button-2>", function), master.bind("<Button-3>", function)

Not Exactly the best way to do things but it should work.

CodePudding user response:

You could do something like

for b in ["<Button-1>", "<Button-2>", "<Button-3>"]: master.bind(b, function)

There really isn't a prettier way to do it with Tkinter itself. Either you make a for loop and reuse the parts that stay the same, but I'd recommend just writing it all out.

  • Related