Change command Method for Tkinter Button in Python



Answers

Sure; just use the bind method to specify the callback after the button has been created. I've just written and tested the example below. You can find a nice tutorial on doing this at http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm

from Tkinter import Tk, Button

root = Tk()
button = Button(root, text="Click Me!")
button.pack()

def callback(event):
    print "Hello World!"

button.bind("<Button-1>", callback)
root.mainloop()
Question

I create a new Button object but did not specify the command option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created?




tkinter - bind ALL 'chosen' events of a widget to a callback

you haven't stated what method you are using to bind (but i'm guessing you bind a mouse event) instead you can add a command to the constructor of each button, then anything that changes the selection (mouse or keyboard) will call your callback, albeit without the event object:

http://effbot.org/tkinterbook/radiobutton.htm

from tkinter import *

def changed():
    print("Changed value")
master = Tk()

v = IntVar()

Radiobutton(master, text="One", variable=v, value=1, command=changed).pack(anchor=W)
Radiobutton(master, text="Two", variable=v, value=2, command=changed).pack(anchor=W)

master.mainloop()



Links