简体   繁体   中英

How to bind multiple events to one function python tkinter

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>" .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM