How can I let the Tkinter Button command do more than one function?

Recommended Answers

All 3 Replies

Use something like:

def callback():
    functionone(x) #tab me woot
    functiontwo(y) #tab me woot

As a base for your callback code.

* Sorry if this is incorrect; I'm new to python! vegaseat, please correct me if I'm wrong.

Yes linux, that would be the simplest way to do it!

Python allows you to pass functions as arguments to a function. This code might give you more flexibility ...

# giving a Tkinter Button command two (or multiple) functions to run
import Tkinter as tk
def do_two(s, f1, f2):
    """run 2 functions f1 and f2"""
    # after 2 sec run function f2
    root.after(2000, f2)
root = tk.Tk()
root.title('click me')
s = '123'
f1 = root.title
f2 = root.destroy
# using lambda to pass string s and two functions f1 and f2 as arguments
q1 = lambda: do_two(s, f1, f2)
b2 = tk.Button(root, text=" click to show 123, then after 2 sec quit ", command=q1)

There's one other way that I've found, although sometimes it feels like cheating: bind another function to the mouseclick of that button.

For example:

button = Button(text="Two Functions", command=f1)
button.bind('<ButtonRelease-1>', f2)

Thus the usual command is to perform f1 , while when the mouse has clicked the button and released, f2 goes.

As far as I can tell, you can only bind one function to a particular event. Although I suppose you could bind a third function to the click (rather than the release), I've found that it tends to be jarring for the user at times.

I've been searching for another way around this problem for ages, to no avail...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.