Tkinter Tutorial 3

Part 3 of this mini series will focus on adding buttons.

Now that we can add a label we can add a button in a very similar way,  buttons however are interactive, so not only do we need to place a button we need to define what the program is going to do with it.

def btn1():
	print ("button pressed")
 
btn_tog2 = Button( window, text ='button1', command=btn1)
btn_exit = Button( window, text ='exit',command=exit)	
 
btn_tog2.grid(row = 1, column = 1, padx = 5, pady = 5)
btn_exit.grid(row = 2, column = 1, padx = 5, pady = 5)

 

And how this code works, is explained below

 

def btn1(): Define the button Object function
print (“button pressed”) Actions to carry out when pressed (indented)
btn_tog2 = Button( window, text =‘button1’, command=btn1) Define the button , command=btn1() is used to call the function linked to the button
btn_exit = Button( window, text =‘exit’,command=exit) An exit button, exit is a built in function so will appear as a different colour, and simply exits the program so there is no need to call a function3 to run this,
btn_tog2.grid(row = 1, column = 1, padx = 5, pady = 5) Place the button (you can call this btn1 if you want as long as you change th
btn_exit.grid(row = 2, column = 1, padx = 5, pady = 5) Place the exit button

 

All this should result in

buttons