Monday, 13 April 2015

Using the 'command' option of the Button widget

In this post I will show how to put some buttons and assign a command to one of them, yeah, at last something with functionality :P

Well, first goes the code like this:
from Tkinter import *

def printMessage():
    print "Channel open"

root = Tk()
root.title("Happy hour")
label_1 = Label(root, text = "Spoon - 'Got Nuffin'. Available since this summer!")
label_2 = Label(root, text = "Yeah!")
label_1.pack()
label_2.pack()
Button(root, text = "Let's hear it", state = DISABLED).pack(side = LEFT)
Button(root, text = "Let's see").pack(side = RIGHT)
Button(root, text = "Tune", command = printMessage).pack(side = RIGHT)
root.mainloop()



When running the previous code, you should get something like the next picture:





If you haven't noticed, the button that says "Let's hear it" its gray and cannot be clicked like the other buttons in the created window. If you look the part of the code in which the respective button has the text "Let's hear it", you can see that it has been used the option "state" of the Button widget, in this case it is selected the option "DISABLED".


The phrase "Available since this summer!" does't sound well to me, but I decided to leave it like that, at least for some time.

Anyway, back to the code, there is a function called printMessage, well, at the moment that it's assigned a command to a button, one must use the "command" option of the Button widget, and just put then name of the function without the parenthesis.

Of course the result of clicking the button will be related to the command assigned, in this case is just a text printed in the console window.



And the last thing that I'm going to mention here is that in this code we opted to use the "pack" method, and also we used its options, like using the allignemts with the "side" method. The first button assigned to the left, the other two for the right side, but the order of the buttons is like: the first one packed is put to the right side, then the next one is put at the left side of the first one, and so this will be the way in which the other created buttons will be organizated.

No comments:

Post a Comment